TagSpaces is an offline, open source, document manager with tagging support
cordova-ios 6.1.0
stanimirc9a98af91f99
diff --git a/cordova/config.xml b/cordova/config.xmlindex c0728daf4..1e41c3cbf 100644--- a/cordova/config.xml+++ b/cordova/config.xml@@ -25,11 +25,8 @@<icon density="xxxhdpi" src="res/icon/android/mipmap-xxxhdpi/ic_launcher.png" /></platform><platform name="ios">- <preference name="WKWebViewOnly" value="true" />- <feature name="CDVWKWebViewEngine">- <param name="ios-package" value="CDVWKWebViewEngine" />- </feature>- <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />+ <preference name="InterceptRemoteRequests" value="all" />+ <preference name="allowFileAccessFromFileURLs" value="true" /><allow-intent href="itms:*" /><allow-intent href="itms-apps:*" /></platform>diff --git a/cordova/package.json b/cordova/package.jsonindex 479d3f597..e958f5c98 100644--- a/cordova/package.json+++ b/cordova/package.json@@ -10,17 +10,12 @@"author": "Apache Cordova Team","license": "Apache-2.0","dependencies": {- "bamboo.cordova.plugin.downloader": "git+https://github.com/sytolk/cordova-plugin-downloader.git",- "cordova-android": "^7.1.4",- "cordova-ios": "^5.1.1","cordova-plugin-background-mode": "^0.7.3","cordova-plugin-camera": "4.1.0","cordova-plugin-device": "^2.0.3","cordova-plugin-file": "6.0.2","cordova-plugin-file-opener2": "^3.0.3","cordova-plugin-whitelist": "^1.3.4",- "cordova-plugin-wkwebview-engine": "^1.2.1",- "cordova-plugin-x-socialsharing": "^5.6.8","es6-promise-plugin": "^4.2.2"},"cordova": {@@ -35,12 +30,23 @@"cordova-plugin-file-opener2": {"ANDROID_SUPPORT_V4_VERSION": "27.+"},- "cordova-plugin-wkwebview-engine": {},- "com.whebcraft.cordova.plugin.downloader": {}+ "com.whebcraft.cordova.plugin.downloader": {},+ "cordova-plugin-x-socialsharing": {+ "ANDROID_SUPPORT_V4_VERSION": "24.1.1+",+ "PHOTO_LIBRARY_ADD_USAGE_DESCRIPTION": "This app requires photo library access to function properly.",+ "PHOTO_LIBRARY_USAGE_DESCRIPTION": "This app requires photo library access to function properly."+ },+ "cordova-plugin-ios-xhr": {}},"platforms": [- "android",- "ios"+ "ios",+ "android"]+ },+ "devDependencies": {+ "@globules-io/cordova-plugin-ios-xhr": "^1.0.3",+ "bamboo.cordova.plugin.downloader": "git+https://github.com/sytolk/cordova-plugin-downloader.git",+ "cordova-android": "^9.0.0",+ "cordova-ios": "^6.1.0"}}diff --git a/cordova/platforms/android/.gitignore b/cordova/platforms/android/.gitignoreindex 6e5244597..427a160a1 100644--- a/cordova/platforms/android/.gitignore+++ b/cordova/platforms/android/.gitignore@@ -10,5 +10,12 @@ ant-gen# Eclipse buildsgenout-# Gradle builds+# Gradle build artifacts+.gradle+.gradletasknamecache/build+/CordovaLib/build+/app/build+gradle-app.setting+# Android Studio+.ideadiff --git a/cordova/platforms/android/CordovaLib/AndroidManifest.xml b/cordova/platforms/android/CordovaLib/AndroidManifest.xmlindex 1625b896b..320c2538e 100755--- a/cordova/platforms/android/CordovaLib/AndroidManifest.xml+++ b/cordova/platforms/android/CordovaLib/AndroidManifest.xml@@ -19,5 +19,4 @@--><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="org.apache.cordova" android:versionName="1.0" android:versionCode="1">- <uses-sdk android:minSdkVersion="19" /></manifest>diff --git a/cordova/platforms/android/CordovaLib/build.gradle b/cordova/platforms/android/CordovaLib/build.gradleindex 4f7f171ca..d7e0b1f72 100644--- a/cordova/platforms/android/CordovaLib/build.gradle+++ b/cordova/platforms/android/CordovaLib/build.gradle@@ -24,36 +24,47 @@ ext {buildscript {repositories {- maven {- url "https://maven.google.com"- }+ google()jcenter()}dependencies {- classpath 'com.android.tools.build:gradle:3.0.1'- classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'+ // The gradle plugin and the maven plugin have to be updated after each version of Android+ // studio comes out+ classpath 'com.android.tools.build:gradle:4.0.0'+ classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'}}+allprojects {+ repositories {+ google()+ jcenter()+ }+}+apply plugin: 'com.android.library'apply plugin: 'com.github.dcendents.android-maven'apply plugin: 'com.jfrog.bintray'group = 'org.apache.cordova'-version = '7.1.4'+version = '9.0.0'android {compileSdkVersion cdvCompileSdkVersionbuildToolsVersion cdvBuildToolsVersion- publishNonDefault truecompileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}+ // For the Android Cordova Lib, we will hardcode the minSdkVersion and not allow changes.+ defaultConfig {+ minSdkVersion 22+ }+sourceSets {main {manifest.srcFile 'AndroidManifest.xml'@@ -94,9 +105,9 @@ install {}}scm {- connection 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git'- developerConnection 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git'- url 'https://git-wip-us.apache.org/repos/asf?p=cordova-android'+ connection 'scm:git:https://github.com/apache/cordova-android.git'+ developerConnection 'scm:git:[email protected]:apache/cordova-android.git'+ url 'https://github.com/apache/cordova-android'}}@@ -122,16 +133,16 @@ bintray {name = 'cordova-android'userOrg = 'cordova'licenses = ['Apache-2.0']- vcsUrl = 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git'+ vcsUrl = 'https://github.com/apache/cordova-android'websiteUrl = 'https://cordova.apache.org'- issueTrackerUrl = 'https://issues.apache.org/jira/browse/CB'+ issueTrackerUrl = 'https://github.com/apache/cordova-android/issues'publicDownloadNumbers = truelicenses = ['Apache-2.0']labels = ['android', 'cordova', 'phonegap']version {- name = '7.1.4'+ name = '9.0.0'released = new Date()- vcsTag = '7.1.4'+ vcsTag = '9.0.0'}}}diff --git a/cordova/platforms/android/CordovaLib/cordova.gradle b/cordova/platforms/android/CordovaLib/cordova.gradleindex 6c6819a17..36750b68f 100644--- a/cordova/platforms/android/CordovaLib/cordova.gradle+++ b/cordova/platforms/android/CordovaLib/cordova.gradle@@ -19,6 +19,7 @@import java.util.regex.Patternimport groovy.swing.SwingBuilder+import com.g00fy2.versioncompare.VersionString doEnsureValueExists(filePath, props, key) {if (props.get(key) == null) {@@ -39,62 +40,52 @@ String doGetProjectTarget() {return doEnsureValueExists('project.properties', props, 'target')}-String[] getAvailableBuildTools() {- def buildToolsDir = new File(getAndroidSdkDir(), "build-tools")- buildToolsDir.list()- .findAll { it ==~ /[0-9.]+/ }- .sort { a, b -> compareVersions(b, a) }+Boolean isVersionValid(version) {+ return !(new Version(version)).isEqual('0.0.0')}-String doFindLatestInstalledBuildTools(String minBuildToolsVersion) {- def availableBuildToolsVersions+String doFindLatestInstalledBuildTools(String minBuildToolsVersionString) {+ def buildToolsDirContentstry {- availableBuildToolsVersions = getAvailableBuildTools()+ def buildToolsDir = new File(getAndroidSdkDir(), "build-tools")+ buildToolsDirContents = buildToolsDir.list()} catch (e) {println "An exception occurred while trying to find the Android build tools."throw e}- if (availableBuildToolsVersions.length > 0) {- def highestBuildToolsVersion = availableBuildToolsVersions[0]- if (compareVersions(highestBuildToolsVersion, minBuildToolsVersion) < 0) {- throw new RuntimeException(- "No usable Android build tools found. Highest installed version is " +- highestBuildToolsVersion + "; minimum version required is " +- minBuildToolsVersion + ".")- }- highestBuildToolsVersion- } else {- throw new RuntimeException(- "No installed build tools found. Install the Android build tools version " +- minBuildToolsVersion + " or higher.")++ def highestBuildToolsVersion = buildToolsDirContents+ .collect { new Version(it) }+ // Invalid inputs will be handled as 0.0.0+ .findAll { it.isHigherThan('0.0.0') }+ .max()++ if (highestBuildToolsVersion == null) {+ throw new RuntimeException("""+ No installed build tools found. Install the Android build tools+ version ${minBuildToolsVersionString} or higher.+ """.replaceAll(/\s+/, ' ').trim())}-}-// Return the first non-zero result of subtracting version list elements-// pairwise. If they are all identical, return the difference in length of-// the two lists.-int compareVersionList(Collection aParts, Collection bParts) {- def pairs = ([aParts, bParts]).transpose()- pairs.findResult(aParts.size()-bParts.size()) {it[0] - it[1] != 0 ? it[0] - it[1] : null}-}+ if (highestBuildToolsVersion.isLowerThan(minBuildToolsVersionString)) {+ throw new RuntimeException("""+ No usable Android build tools found. Highest installed version is+ ${highestBuildToolsVersion.getOriginalString()}; minimum version+ required is ${minBuildToolsVersionString}.+ """.replaceAll(/\s+/, ' ').trim())+ }-// Compare two version strings, such as "19.0.0" and "18.1.1.0". If all matched-// elements are identical, the longer version is the largest by this method.-// Examples:-// "19.0.0" > "19"-// "19.0.1" > "19.0.0"-// "19.1.0" > "19.0.1"-// "19" > "18.999.999"-int compareVersions(String a, String b) {- def aParts = a.tokenize('.').collect {it.toInteger()}- def bParts = b.tokenize('.').collect {it.toInteger()}- compareVersionList(aParts, bParts)+ highestBuildToolsVersion.getOriginalString()}String getAndroidSdkDir() {def rootDir = project.rootDirdef androidSdkDir = null- String envVar = System.getenv("ANDROID_HOME")+ String envVar = System.getenv("ANDROID_SDK_ROOT")+ if (envVar == null) {+ envVar = System.getenv("ANDROID_HOME")+ }+def localProperties = new File(rootDir, 'local.properties')String systemProperty = System.getProperty("android.home")if (envVar != null) {@@ -203,3 +194,12 @@ ext {cdvHelpers.getConfigPreference = { name, defaultValue -> doGetConfigPreference(name, defaultValue) }}+buildscript {+ repositories {+ jcenter()+ }++ dependencies {+ classpath 'com.g00fy2:versioncompare:1.3.4@jar'+ }+}diff --git a/cordova/platforms/android/CordovaLib/project.properties b/cordova/platforms/android/CordovaLib/project.propertiesindex 0a372ee40..d05191746 100644--- a/cordova/platforms/android/CordovaLib/project.properties+++ b/cordova/platforms/android/CordovaLib/project.properties@@ -1,16 +1,11 @@-# This file is automatically generated by Android Tools.-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!-#-# This file must be checked in Version Control Systems.-#-# To customize properties used by the Ant build system use,-# "ant.properties", and override values to adapt the script to your-# project structure.+# This file was originally created by the Android Tools, but is now+# used by cordova-android to manage the project configuration.# Indicates whether an apk should be generated for each density.split.density=false+# Project target.-target=android-27+target=android-29apk-configurations=renderscript.opt.level=O0android.library=truediff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/BuildHelper.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/BuildHelper.javaindex 6d9daa471..02d9ea003 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/BuildHelper.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/BuildHelper.java@@ -51,7 +51,7 @@ public class BuildHelper {{try{- Class<?> clazz = Class.forName(ctx.getPackageName() + ".BuildConfig");+ Class<?> clazz = Class.forName(ctx.getClass().getPackage().getName() + ".BuildConfig");Field field = clazz.getField(key);return field.get(null);} catch (ClassNotFoundException e) {@@ -62,9 +62,12 @@ public class BuildHelper {} catch (IllegalAccessException e) {LOG.d(TAG, "Illegal Access Exception: Let's print a stack trace.");e.printStackTrace();+ } catch (NullPointerException e) {+ LOG.d(TAG, "Null Pointer Exception: Let's print a stack trace.");+ e.printStackTrace();}return null;}-}\ No newline at end of file+}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.javaindex dbbb48f69..f2f5619e6 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaActivity.java@@ -268,9 +268,11 @@ public class CordovaActivity extends Activity {if (this.appView == null) {return;}- // Force window to have focus, so application always- // receive user input. Workaround for some devices (Samsung Galaxy Note 3 at least)- this.getWindow().getDecorView().requestFocus();+ if (! this.getWindow().getDecorView().hasFocus()) {+ // Force window to have focus, so application always+ // receive user input. Workaround for some devices (Samsung Galaxy Note 3 at least)+ this.getWindow().getDecorView().requestFocus();+ }this.appView.handleResume(this.keepRunning);}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.javaindex 28c407f3d..7416cd193 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaBridge.java@@ -127,7 +127,7 @@ public class CordovaBridge {}public String promptOnJsPrompt(String origin, String message, String defaultValue) {- if (defaultValue != null && defaultValue.length() > 3 && defaultValue.startsWith("gap:")) {+ if (defaultValue != null && defaultValue.startsWith("gap:")) {JSONArray array;try {array = new JSONArray(defaultValue.substring(4));diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.javaindex ccda0272a..ad7c588a8 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaClientCertRequest.java@@ -36,7 +36,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {public CordovaClientCertRequest(ClientCertRequest request) {this.request = request;}-+/*** Cancel this request*/@@ -45,7 +45,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {{request.cancel();}-+/** Returns the host name of the server requesting the certificate.*/@@ -54,7 +54,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {{return request.getHost();}-+/** Returns the acceptable types of asymmetric keys (can be null).*/@@ -63,7 +63,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {{return request.getKeyTypes();}-+/** Returns the port number of the server requesting the certificate.*/@@ -72,7 +72,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {{return request.getPort();}-+/** Returns the acceptable certificate issuers for the certificate matching the private key (can be null).*/@@ -81,7 +81,7 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {{return request.getPrincipals();}-+/** Ignore the request for now. Do not remember user's choice.*/@@ -90,12 +90,12 @@ public class CordovaClientCertRequest implements ICordovaClientCertRequest {{request.ignore();}-+/** Proceed with the specified private key and client certificate chain. Remember the user's positive choice and use it for future requests.- *+ ** @param privateKey The privateKey- * @param chain The certificate chain+ * @param chain The certificate chain*/@SuppressLint("NewApi")public void proceed(PrivateKey privateKey, X509Certificate[] chain)diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaHttpAuthHandler.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaHttpAuthHandler.javaindex 724381e2c..a2692f8c7 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaHttpAuthHandler.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaHttpAuthHandler.java@@ -31,17 +31,17 @@ public class CordovaHttpAuthHandler implements ICordovaHttpAuthHandler {public CordovaHttpAuthHandler(HttpAuthHandler handler) {this.handler = handler;}-+/*** Instructs the WebView to cancel the authentication request.*/public void cancel () {this.handler.cancel();}-+/*** Instructs the WebView to proceed with the authentication with the given credentials.- *+ ** @param username* @param password*/diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.javaindex ff9068346..7661b7421 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaInterface.java@@ -73,7 +73,7 @@ public interface CordovaInterface {* @return Object or null*/public Object onMessage(String id, Object data);-+/*** Returns a shared thread pool that can be used for background tasks.*/diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaPreferences.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaPreferences.javaindex 4dbc93e64..96c219c9e 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaPreferences.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaPreferences.java@@ -47,11 +47,11 @@ public class CordovaPreferences {public void set(String name, int value) {set(name, "" + value);}-+public void set(String name, double value) {set(name, "" + value);}-+public Map<String, String> getAll() {return prefs;}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.javaindex 3c438e21b..8350ec278 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaResourceApi.java@@ -77,7 +77,7 @@ public class CordovaResourceApi {public static final String PLUGIN_URI_SCHEME = "cdvplugin";private static final String[] LOCAL_FILE_PROJECTION = { "_data" };-+public static Thread jsThread;private final AssetManager assetManager;@@ -91,7 +91,7 @@ public class CordovaResourceApi {this.assetManager = context.getAssets();this.pluginManager = pluginManager;}-+public void setThreadCheckingEnabled(boolean value) {threadCheckingEnabled = value;}@@ -99,8 +99,8 @@ public class CordovaResourceApi {public boolean isThreadCheckingEnabled() {return threadCheckingEnabled;}--++public static int getUriType(Uri uri) {assertNonRelative(uri);String scheme = uri.getScheme();@@ -130,7 +130,7 @@ public class CordovaResourceApi {}return URI_TYPE_UNKNOWN;}-+public Uri remapUri(Uri uri) {assertNonRelative(uri);Uri pluginUri = pluginManager.remapUri(uri);@@ -140,7 +140,7 @@ public class CordovaResourceApi {public String remapPath(String path) {return remapUri(Uri.fromFile(new File(path))).getPath();}-+/*** Returns a File that points to the resource, or null if the resource* is not on the local filesystem.@@ -170,7 +170,7 @@ public class CordovaResourceApi {}return null;}-+public String getMimeType(Uri uri) {switch (getUriType(uri)) {case URI_TYPE_FILE:@@ -197,11 +197,11 @@ public class CordovaResourceApi {}}}-+return null;}--++//This already existsprivate String getMimeTypeFromPath(String path) {String extension = path;@@ -219,7 +219,7 @@ public class CordovaResourceApi {}return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);}-+/*** Opens a stream to the given URI, also providing the MIME type & length.* @return Never returns null.@@ -342,7 +342,7 @@ public class CordovaResourceApi {assertBackgroundThread();return (HttpURLConnection)new URL(uri.toString()).openConnection();}-+// Copies the input to the output in the most efficient manner possible.// Closes both streams.public void copyResource(OpenForReadResult input, OutputStream outputStream) throws IOException {@@ -364,16 +364,16 @@ public class CordovaResourceApi {} else {final int BUFFER_SIZE = 8192;byte[] buffer = new byte[BUFFER_SIZE];-+for (;;) {int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);-+if (bytesRead <= 0) {break;}outputStream.write(buffer, 0, bytesRead);}- }+ }} finally {input.inputStream.close();if (outputStream != null) {@@ -390,7 +390,7 @@ public class CordovaResourceApi {public void copyResource(Uri sourceUri, Uri dstUri) throws IOException {copyResource(openForRead(sourceUri), openOutputStream(dstUri));}-+private void assertBackgroundThread() {if (threadCheckingEnabled) {Thread curThread = Thread.currentThread();@@ -402,7 +402,7 @@ public class CordovaResourceApi {}}}-+private String getDataUriMimeType(Uri uri) {String uriAsString = uri.getSchemeSpecificPart();int commaPos = uriAsString.indexOf(',');@@ -447,20 +447,20 @@ public class CordovaResourceApi {InputStream inputStream = new ByteArrayInputStream(data);return new OpenForReadResult(uri, inputStream, contentType, data.length, null);}-+private static void assertNonRelative(Uri uri) {if (!uri.isAbsolute()) {throw new IllegalArgumentException("Relative URIs are not supported.");}}-+public static final class OpenForReadResult {public final Uri uri;public final InputStream inputStream;public final String mimeType;public final long length;public final AssetFileDescriptor assetFd;-+public OpenForReadResult(Uri uri, InputStream inputStream, String mimeType, long length, AssetFileDescriptor assetFd) {this.uri = uri;this.inputStream = inputStream;diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.javaindex f4cab35f0..7ee8d2470 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebView.java@@ -31,7 +31,7 @@ import android.webkit.WebChromeClient.CustomViewCallback;* are not expected to implement it.*/public interface CordovaWebView {- public static final String CORDOVA_VERSION = "7.1.4";+ public static final String CORDOVA_VERSION = "9.0.0";void init(CordovaInterface cordova, List<PluginEntry> pluginEntries, CordovaPreferences preferences);diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.javaindex fb99c3443..a77502d6e 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CordovaWebViewImpl.java@@ -216,8 +216,10 @@ public class CordovaWebViewImpl implements CordovaWebView {// TODO: What about params?// Load new URLloadUrlIntoView(url, true);+ return;} else {LOG.w(TAG, "showWebPage: Refusing to load URL into webview since it is not in the <allow-navigation> whitelist. URL=" + url);+ return;}}if (!pluginManager.shouldOpenExternalUrl(url)) {@@ -242,6 +244,21 @@ public class CordovaWebViewImpl implements CordovaWebView {}}+ private static class WrapperView extends FrameLayout {++ private final CordovaWebViewEngine engine;++ public WrapperView(Context context, CordovaWebViewEngine engine) {+ super(context);+ this.engine = engine;+ }++ @Override+ public boolean dispatchKeyEvent(KeyEvent event) {+ return engine.getView().dispatchKeyEvent(event);+ }+ }+@Override@Deprecatedpublic void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {@@ -253,13 +270,16 @@ public class CordovaWebViewImpl implements CordovaWebView {return;}+ WrapperView wrapperView = new WrapperView(getContext(), engine);+ wrapperView.addView(view);+// Store the view and its callback for later (to kill it properly)- mCustomView = view;+ mCustomView = wrapperView;mCustomViewCallback = callback;// Add the custom view to its container.ViewGroup parent = (ViewGroup) engine.getView().getParent();- parent.addView(view, new FrameLayout.LayoutParams(+ parent.addView(wrapperView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,Gravity.CENTER));diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.javaindex e384f8d74..6ebdecb3a 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/CoreAndroid.java@@ -43,6 +43,7 @@ public class CoreAndroid extends CordovaPlugin {private BroadcastReceiver telephonyReceiver;private CallbackContext messageChannel;private PluginResult pendingResume;+ private PluginResult pendingPause;private final Object messageChannelLock = new Object();/**@@ -113,6 +114,10 @@ public class CoreAndroid extends CordovaPlugin {else if (action.equals("messageChannel")) {synchronized(messageChannelLock) {messageChannel = callbackContext;+ if (pendingPause != null) {+ sendEventMessage(pendingPause);+ pendingPause = null;+ }if (pendingResume != null) {sendEventMessage(pendingResume);pendingResume = null;@@ -139,7 +144,7 @@ public class CoreAndroid extends CordovaPlugin {public void clearCache() {cordova.getActivity().runOnUiThread(new Runnable() {public void run() {- webView.clearCache(true);+ webView.clearCache();}});}@@ -321,7 +326,19 @@ public class CoreAndroid extends CordovaPlugin {} catch (JSONException e) {LOG.e(TAG, "Failed to create event message", e);}- sendEventMessage(new PluginResult(PluginResult.Status.OK, obj));+ PluginResult result = new PluginResult(PluginResult.Status.OK, obj);++ if (messageChannel == null) {+ LOG.i(TAG, "Request to send event before messageChannel initialised: " + action);+ if ("pause".equals(action)) {+ pendingPause = result;+ } else if ("resume".equals(action)) {+ // When starting normally onPause then onResume is called+ pendingPause = null;+ }+ } else {+ sendEventMessage(result);+ }}private void sendEventMessage(PluginResult payload) {@@ -372,7 +389,7 @@ public class CoreAndroid extends CordovaPlugin {{try{- Class<?> clazz = Class.forName(ctx.getPackageName() + ".BuildConfig");+ Class<?> clazz = Class.forName(ctx.getClass().getPackage().getName() + ".BuildConfig");Field field = clazz.getField(key);return field.get(null);} catch (ClassNotFoundException e) {@@ -383,6 +400,9 @@ public class CoreAndroid extends CordovaPlugin {} catch (IllegalAccessException e) {LOG.d(TAG, "Illegal Access Exception: Let's print a stack trace.");e.printStackTrace();+ } catch (NullPointerException e) {+ LOG.d(TAG, "Null Pointer Exception: Let's print a stack trace.");+ e.printStackTrace();}return null;diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaClientCertRequest.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaClientCertRequest.javaindex 455d2f9d3..e68225b44 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaClientCertRequest.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaClientCertRequest.java@@ -30,37 +30,37 @@ public interface ICordovaClientCertRequest {* Cancel this request*/public void cancel();-+/** Returns the host name of the server requesting the certificate.*/public String getHost();-+/** Returns the acceptable types of asymmetric keys (can be null).*/public String[] getKeyTypes();-+/** Returns the port number of the server requesting the certificate.*/public int getPort();-+/** Returns the acceptable certificate issuers for the certificate matching the private key (can be null).*/public Principal[] getPrincipals();-+/** Ignore the request for now. Do not remember user's choice.*/public void ignore();-+/** Proceed with the specified private key and client certificate chain. Remember the user's positive choice and use it for future requests.- *+ ** @param privateKey The privateKey- * @param chain The certificate chain+ * @param chain The certificate chain*/public void proceed(PrivateKey privateKey, X509Certificate[] chain);-}\ No newline at end of file+}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaHttpAuthHandler.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaHttpAuthHandler.javaindex c55818ac6..bc443a2b2 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaHttpAuthHandler.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/ICordovaHttpAuthHandler.java@@ -27,12 +27,12 @@ package org.apache.cordova;* Instructs the WebView to cancel the authentication request.*/public void cancel ();-+/*** Instructs the WebView to proceed with the authentication with the given credentials.- *+ ** @param username The user name* @param password The password*/public void proceed (String username, String password);-}\ No newline at end of file+}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.javaindex d17b1c43a..311ba4446 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/NativeToJsMessageQueue.java@@ -36,10 +36,11 @@ public class NativeToJsMessageQueue {// exec() is asynchronous. Set this to true when running bridge benchmarks.static final boolean DISABLE_EXEC_CHAINING = false;- // Arbitrarily chosen upper limit for how much data to send to JS in one shot.- // This currently only chops up on message boundaries. It may be useful- // to allow it to break up messages.- private static int MAX_PAYLOAD_SIZE = 50 * 1024 * 10240;+ // A hopefully reasonable upper limit of how much combined payload data+ // to send to the JavaScript in one shot.+ // This currently only chops up on message boundaries.+ // It may be useful to split and reassemble response messages someday.+ private static int COMBINED_RESPONSE_CUTOFF = 16 * 1024 * 1024;/*** When true, the active listener is not fired upon enqueue. When set to false,@@ -124,7 +125,10 @@ public class NativeToJsMessageQueue {/*** Combines and returns queued messages combined into a single string.- * Combines as many messages as possible, while staying under MAX_PAYLOAD_SIZE.+ *+ * Combines as many messages as possible, without exceeding+ * COMBINED_RESPONSE_CUTOFF in case of multiple response messages.+ ** Returns null if the queue is empty.*/public String popAndEncode(boolean fromOnlineEvent) {@@ -140,7 +144,10 @@ public class NativeToJsMessageQueue {int numMessagesToSend = 0;for (JsMessage message : queue) {int messageSize = calculatePackedMessageLength(message);- if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE && MAX_PAYLOAD_SIZE > 0) {+ if (numMessagesToSend > 0 &&+ COMBINED_RESPONSE_CUTOFF > 0 &&+ totalPayloadLen + messageSize > COMBINED_RESPONSE_CUTOFF+ ) {break;}totalPayloadLen += messageSize;@@ -175,7 +182,10 @@ public class NativeToJsMessageQueue {int numMessagesToSend = 0;for (JsMessage message : queue) {int messageSize = message.calculateEncodedLength() + 50; // overestimate.- if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE && MAX_PAYLOAD_SIZE > 0) {+ if (numMessagesToSend > 0 &&+ COMBINED_RESPONSE_CUTOFF > 0 &&+ totalPayloadLen + messageSize > COMBINED_RESPONSE_CUTOFF+ ) {break;}totalPayloadLen += messageSize;diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/PluginResult.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/PluginResult.javaindex 2b3ac72ed..5db60b3b7 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/PluginResult.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/PluginResult.java@@ -82,7 +82,7 @@ public class PluginResult {this.messageType = binaryString ? MESSAGE_TYPE_BINARYSTRING : MESSAGE_TYPE_ARRAYBUFFER;this.encodedMessage = Base64.encodeToString(data, Base64.NO_WRAP);}-+// The keepCallback and status of multipartMessages are ignored.public PluginResult(Status status, List<PluginResult> multipartMessages) {this.status = status.ordinal();diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.javaindex acf795fa6..f8128bc20 100644--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemCookieManager.java@@ -31,18 +31,12 @@ class SystemCookieManager implements ICordovaCookieManager {protected final WebView webView;private final CookieManager cookieManager;- //Added because lint can't see the conditional RIGHT ABOVE this- @TargetApi(Build.VERSION_CODES.LOLLIPOP)public SystemCookieManager(WebView webview) {webView = webview;cookieManager = CookieManager.getInstance();- //REALLY? Nobody has seen this UNTIL NOW?cookieManager.setAcceptFileSchemeCookies(true);-- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {- cookieManager.setAcceptThirdPartyCookies(webView, true);- }+ cookieManager.setAcceptThirdPartyCookies(webView, true);}public void setCookiesEnabled(boolean accept) {@@ -57,13 +51,12 @@ class SystemCookieManager implements ICordovaCookieManager {return cookieManager.getCookie(url);}+ @SuppressWarnings("deprecation")public void clearCookies() {- cookieManager.removeAllCookie();+ cookieManager.removeAllCookies(null);}public void flush() {- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {- cookieManager.flush();- }+ cookieManager.flush();}};diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.javaindex a27fc6af4..03816ddec 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebChromeClient.java@@ -142,6 +142,7 @@ public class SystemWebChromeClient extends WebChromeClient {* Handle database quota exceeded notification.*/@Override+ @SuppressWarnings("deprecation")public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater){@@ -149,14 +150,6 @@ public class SystemWebChromeClient extends WebChromeClient {quotaUpdater.updateQuota(MAX_QUOTA);}- @Override- public boolean onConsoleMessage(ConsoleMessage consoleMessage)- {- if (consoleMessage.message() != null)- LOG.d(LOG_TAG, "%s: Line %d : %s" , consoleMessage.sourceId() , consoleMessage.lineNumber(), consoleMessage.message());- return super.onConsoleMessage(consoleMessage);- }-@Override/*** Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.@@ -175,16 +168,17 @@ public class SystemWebChromeClient extends WebChromeClient {{geolocation.requestPermissions(0);}-}// API level 7 is required for this, see if we could lower this using something else@Override+ @SuppressWarnings("deprecation")public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {parentEngine.getCordovaWebView().showCustomView(view, callback);}@Override+ @SuppressWarnings("deprecation")public void onHideCustomView() {parentEngine.getCordovaWebView().hideCustomView();}@@ -196,7 +190,6 @@ public class SystemWebChromeClient extends WebChromeClient {* @return View The progress view.*/public View getVideoLoadingProgressView() {-if (mVideoProgressView == null) {// Create a new Loading view programmatically.@@ -215,45 +208,46 @@ public class SystemWebChromeClient extends WebChromeClient {mVideoProgressView = layout;}- return mVideoProgressView;- }-- // <input type=file> support:- // openFileChooser() is for pre KitKat and in KitKat mr1 (it's known broken in KitKat).- // For Lollipop, we use onShowFileChooser().- public void openFileChooser(ValueCallback<Uri> uploadMsg) {- this.openFileChooser(uploadMsg, "*/*");- }-- public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {- this.openFileChooser(uploadMsg, acceptType, null);+ return mVideoProgressView;}- public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType, String capture)- {- Intent intent = new Intent(Intent.ACTION_GET_CONTENT);- intent.addCategory(Intent.CATEGORY_OPENABLE);- intent.setType("*/*");- parentEngine.cordova.startActivityForResult(new CordovaPlugin() {- @Override- public void onActivityResult(int requestCode, int resultCode, Intent intent) {- Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();- LOG.d(LOG_TAG, "Receive file chooser URL: " + result);- uploadMsg.onReceiveValue(result);- }- }, intent, FILECHOOSER_RESULTCODE);- }-- @TargetApi(Build.VERSION_CODES.LOLLIPOP)@Overridepublic boolean onShowFileChooser(WebView webView, final ValueCallback<Uri[]> filePathsCallback, final WebChromeClient.FileChooserParams fileChooserParams) {+ // Check if multiple-select is specified+ Boolean selectMultiple = false;+ if (fileChooserParams.getMode() == WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE) {+ selectMultiple = true;+ }Intent intent = fileChooserParams.createIntent();+ intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, selectMultiple);++ // Uses Intent.EXTRA_MIME_TYPES to pass multiple mime types.+ String[] acceptTypes = fileChooserParams.getAcceptTypes();+ if (acceptTypes.length > 1) {+ intent.setType("*/*"); // Accept all, filter mime types by Intent.EXTRA_MIME_TYPES.+ intent.putExtra(Intent.EXTRA_MIME_TYPES, acceptTypes);+ }try {parentEngine.cordova.startActivityForResult(new CordovaPlugin() {@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent intent) {- Uri[] result = WebChromeClient.FileChooserParams.parseResult(resultCode, intent);- LOG.d(LOG_TAG, "Receive file chooser URL: " + result);+ Uri[] result = null;+ if (resultCode == Activity.RESULT_OK && intent != null) {+ if (intent.getClipData() != null) {+ // handle multiple-selected files+ final int numSelectedFiles = intent.getClipData().getItemCount();+ result = new Uri[numSelectedFiles];+ for (int i = 0; i < numSelectedFiles; i++) {+ result[i] = intent.getClipData().getItemAt(i).getUri();+ LOG.d(LOG_TAG, "Receive file chooser URL: " + result[i]);+ }+ }+ else if (intent.getData() != null) {+ // handle single-selected file+ result = WebChromeClient.FileChooserParams.parseResult(resultCode, intent);+ LOG.d(LOG_TAG, "Receive file chooser URL: " + result);+ }+ }filePathsCallback.onReceiveValue(result);}}, intent, FILECHOOSER_RESULTCODE);@@ -264,7 +258,6 @@ public class SystemWebChromeClient extends WebChromeClient {return true;}- @TargetApi(Build.VERSION_CODES.LOLLIPOP)@Overridepublic void onPermissionRequest(final PermissionRequest request) {LOG.d(LOG_TAG, "onPermissionRequest: " + Arrays.toString(request.getResources()));diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.javaindex 0b6a577ea..af9e51f11 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewClient.java@@ -48,7 +48,7 @@ import java.util.Hashtable;/*** This class is the WebViewClient that implements callbacks for our web view.* The kind of callbacks that happen here are regarding the rendering of the- * document instead of the chrome surrounding it, such as onPageStarted(),+ * document instead of the chrome surrounding it, such as onPageStarted(),* shouldOverrideUrlLoading(), etc. Related to but different than* CordovaChromeClient.*/@@ -74,7 +74,8 @@ public class SystemWebViewClient extends WebViewClient {* @param url The url to be loaded.* @return true to override, false for default behavior*/- @Override+ @Override+ @SuppressWarnings("deprecation")public boolean shouldOverrideUrlLoading(WebView view, String url) {return parentEngine.client.onNavigationAttempt(url);}@@ -103,7 +104,7 @@ public class SystemWebViewClient extends WebViewClient {// By default handle 401 like we'd normally do!super.onReceivedHttpAuthRequest(view, handler, host, realm);}-+/*** On received client cert request.* The method forwards the request to any running plugins before using the default implementation.@@ -112,7 +113,6 @@ public class SystemWebViewClient extends WebViewClient {* @param request*/@Override- @TargetApi(Build.VERSION_CODES.LOLLIPOP)public void onReceivedClientCertRequest (WebView view, ClientCertRequest request){@@ -186,6 +186,7 @@ public class SystemWebViewClient extends WebViewClient {* @param failingUrl The url that failed to load.*/@Override+ @SuppressWarnings("deprecation")public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {// Ignore error due to stopLoading().if (!isCurrentlyLoading) {@@ -316,6 +317,7 @@ public class SystemWebViewClient extends WebViewClient {}@Override+ @SuppressWarnings("deprecation")public WebResourceResponse shouldInterceptRequest(WebView view, String url) {try {// Check the against the whitelist and lock out access to the WebView directory@@ -331,7 +333,7 @@ public class SystemWebViewClient extends WebViewClient {// Allow plugins to intercept WebView requests.Uri remappedUri = resourceApi.remapUri(origUri);- if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) {+ if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsContentUrlFix(origUri)) {CordovaResourceApi.OpenForReadResult result = resourceApi.openForRead(remappedUri, true);return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);}@@ -346,7 +348,7 @@ public class SystemWebViewClient extends WebViewClient {}}- private static boolean needsKitKatContentUrlFix(Uri uri) {+ private static boolean needsContentUrlFix(Uri uri) {return "content".equals(uri.getScheme());}diff --git a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.javaindex 1cbd7f8bb..3201c7440 100755--- a/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java+++ b/cordova/platforms/android/CordovaLib/src/org/apache/cordova/engine/SystemWebViewEngine.java@@ -113,7 +113,7 @@ public class SystemWebViewEngine implements CordovaWebViewEngine {//sometimes this can be called after calling webview.destroy() on destroy()//thus resulting in a NullPointerExceptionif(webView!=null) {- webView.setNetworkAvailable(value);+ webView.setNetworkAvailable(value);}}@Overridediff --git a/cordova/platforms/android/android.json b/cordova/platforms/android/android.jsonindex 112de0364..d725bf491 100644--- a/cordova/platforms/android/android.json+++ b/cordova/platforms/android/android.json@@ -37,15 +37,11 @@"count": 1},{- "xml": "<feature name=\"Whitelist\"><param name=\"android-package\" value=\"org.apache.cordova.whitelist.WhitelistPlugin\" /><param name=\"onload\" value=\"true\" /></feature>",- "count": 1- },- {- "xml": "<feature name=\"SocialSharing\"><param name=\"android-package\" value=\"nl.xservices.plugins.SocialSharing\" /></feature>",+ "xml": "<feature name=\"FileOpener2\"><param name=\"android-package\" value=\"io.github.pwlin.cordova.plugins.fileopener2.FileOpener2\" /></feature>","count": 1},{- "xml": "<feature name=\"FileOpener2\"><param name=\"android-package\" value=\"io.github.pwlin.cordova.plugins.fileopener2.FileOpener2\" /></feature>",+ "xml": "<feature name=\"Whitelist\"><param name=\"android-package\" value=\"org.apache.cordova.whitelist.WhitelistPlugin\" /><param name=\"onload\" value=\"true\" /></feature>","count": 1},{@@ -53,13 +49,7 @@"count": 1},{- "xml": "<feature name=\"FileTransfer\"><param name=\"android-package\" value=\"org.apache.cordova.filetransfer.FileTransfer\" /></feature>",- "count": 1- }- ],- "/widget": [- {- "xml": "<feature name=\"Zip\"><param name=\"android-package\" value=\"org.apache.cordova.Zip\" /></feature>",+ "xml": "<feature name=\"SocialSharing\"><param name=\"android-package\" value=\"nl.xservices.plugins.SocialSharing\" /></feature>","count": 1}]@@ -139,33 +129,24 @@"cordova-plugin-file": {"PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-whitelist": {- "PACKAGE_NAME": "org.tagspaces.mobile"- },- "es6-promise-plugin": {- "PACKAGE_NAME": "org.tagspaces.mobile"- },- "cordova-plugin-x-socialsharing": {- "ANDROID_SUPPORT_V4_VERSION": "24.1.1+",- "PACKAGE_NAME": "org.tagspaces.mobile"- },"cordova-plugin-file-opener2": {"ANDROID_SUPPORT_V4_VERSION": "27.+","PACKAGE_NAME": "org.tagspaces.mobile"},- "com.whebcraft.cordova.plugin.downloader": {+ "cordova-plugin-whitelist": {"PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-file-transfer": {+ "com.whebcraft.cordova.plugin.downloader": {"PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-downloader": {+ "es6-promise-plugin": {"PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-zip": {+ "cordova-plugin-x-socialsharing": {+ "ANDROID_SUPPORT_V4_VERSION": "24.1.1+","PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-wkwebview-engine": {+ "cordova-plugin-ios-xhr": {"PACKAGE_NAME": "org.tagspaces.mobile"}},@@ -393,20 +374,6 @@],"runs": true},- {- "id": "es6-promise-plugin.Promise",- "file": "plugins/es6-promise-plugin/www/promise.js",- "pluginId": "es6-promise-plugin",- "runs": true- },- {- "id": "cordova-plugin-x-socialsharing.SocialSharing",- "file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",- "pluginId": "cordova-plugin-x-socialsharing",- "clobbers": [- "window.plugins.socialsharing"- ]- },{"id": "cordova-plugin-file-opener2.FileOpener2","file": "plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js",@@ -424,35 +391,17 @@]},{- "id": "cordova-plugin-file-transfer.FileTransferError",- "file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",- "pluginId": "cordova-plugin-file-transfer",- "clobbers": [- "window.FileTransferError"- ]- },- {- "id": "cordova-plugin-file-transfer.FileTransfer",- "file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",- "pluginId": "cordova-plugin-file-transfer",- "clobbers": [- "window.FileTransfer"- ]- },- {- "id": "cordova-plugin-downloader.download",- "file": "plugins/cordova-plugin-downloader/www/download.js",- "pluginId": "cordova-plugin-downloader",- "clobbers": [- "download"- ]+ "id": "es6-promise-plugin.Promise",+ "file": "plugins/es6-promise-plugin/www/promise.js",+ "pluginId": "es6-promise-plugin",+ "runs": true},{- "id": "cordova-plugin-zip.Zip",- "file": "plugins/cordova-plugin-zip/zip.js",- "pluginId": "cordova-plugin-zip",+ "id": "cordova-plugin-x-socialsharing.SocialSharing",+ "file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",+ "pluginId": "cordova-plugin-x-socialsharing","clobbers": [- "zip"+ "window.plugins.socialsharing"]}],@@ -461,14 +410,11 @@"cordova-plugin-background-mode": "0.7.3","cordova-plugin-camera": "4.1.0","cordova-plugin-file": "6.0.2",+ "cordova-plugin-file-opener2": "3.0.4","cordova-plugin-whitelist": "1.3.4",+ "com.whebcraft.cordova.plugin.downloader": "0.1.0","es6-promise-plugin": "4.2.2","cordova-plugin-x-socialsharing": "5.6.8",- "cordova-plugin-file-opener2": "3.0.3",- "com.whebcraft.cordova.plugin.downloader": "0.1.0",- "cordova-plugin-file-transfer": "1.7.1",- "cordova-plugin-downloader": "0.0.4",- "cordova-plugin-zip": "3.1.0",- "cordova-plugin-wkwebview-engine": "1.2.1"+ "cordova-plugin-ios-xhr": "1.0.0"}}diff --git a/cordova/platforms/android/app/build.gradle b/cordova/platforms/android/app/build.gradleindex e316cfc9c..a452429f5 100644--- a/cordova/platforms/android/app/build.gradle+++ b/cordova/platforms/android/app/build.gradle@@ -19,36 +19,84 @@apply plugin: 'com.android.application'+if (cdvHelpers.getConfigPreference('GradlePluginKotlinEnabled', 'false').toBoolean()) {+ apply plugin: 'kotlin-android'+ apply plugin: 'kotlin-android-extensions'+}+buildscript {+ apply from: '../CordovaLib/cordova.gradle'++ if(cdvHelpers.getConfigPreference('GradlePluginKotlinEnabled', 'false').toBoolean()) {+ String defaultGradlePluginKotlinVersion = kotlin_version++ /**+ * Fetches the user's defined Kotlin Version from config.xml.+ * If the version is not set or invalid, it will default to the ${defaultGradlePluginKotlinVersion}+ */+ String gradlePluginKotlinVersion = cdvHelpers.getConfigPreference('GradlePluginKotlinVersion', defaultGradlePluginKotlinVersion)+ if(!cdvHelpers.isVersionValid(gradlePluginKotlinVersion)) {+ println("The defined Kotlin version (${gradlePluginKotlinVersion}) does not appear to be a valid version. Falling back to version: ${defaultGradlePluginKotlinVersion}.")+ gradlePluginKotlinVersion = defaultGradlePluginKotlinVersion+ }++ // Change the version to be used.+ ext.kotlin_version = gradlePluginKotlinVersion+ }+repositories {mavenCentral()- maven {- url "https://maven.google.com"- }+ google()jcenter()}dependencies {- classpath 'com.android.tools.build:gradle:3.0.1'+ apply from: '../CordovaLib/cordova.gradle'++ classpath 'com.android.tools.build:gradle:4.0.0'++ if (cdvHelpers.getConfigPreference('GradlePluginKotlinEnabled', 'false').toBoolean()) {+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"+ }++ if(cdvHelpers.getConfigPreference('GradlePluginGoogleServicesEnabled', 'false').toBoolean()) {+ String defaultGradlePluginGoogleServicesVersion = '4.2.0'++ /**+ * Fetches the user's defined Google Services Plugin Version from config.xml.+ * If the version is not set or invalid, it will default to the ${defaultGradlePluginGoogleServicesVersion}+ */+ String gradlePluginGoogleServicesVersion = cdvHelpers.getConfigPreference('GradlePluginGoogleServicesVersion', defaultGradlePluginGoogleServicesVersion)+ if(!cdvHelpers.isVersionValid(gradlePluginGoogleServicesVersion)) {+ println("The defined Google Services plugin version (${gradlePluginGoogleServicesVersion}) does not appear to be a valid version. Falling back to version: ${defaultGradlePluginGoogleServicesVersion}.")+ gradlePluginGoogleServicesVersion = defaultGradlePluginGoogleServicesVersion+ }++ // Create the Google Services classpath and set it.+ String gradlePluginGoogleServicesClassPath = "com.google.gms:google-services:${gradlePluginGoogleServicesVersion}"+ println "Adding classpath: ${gradlePluginGoogleServicesClassPath}"+ classpath gradlePluginGoogleServicesClassPath+ }}}// Allow plugins to declare Maven dependencies via build-extras.gradle.allprojects {repositories {- mavenCentral();+ mavenCentral()jcenter()}}task wrapper(type: Wrapper) {- gradleVersion = '4.1.0'+ gradleVersion = '6.5'}// Configuration properties. Set these via environment variables, build-extras.gradle, or gradle.properties.// Refer to: http://www.gradle.org/docs/current/userguide/tutorial_this_and_that.htmlext {apply from: '../CordovaLib/cordova.gradle'+// The value for android.compileSdkVersion.if (!project.hasProperty('cdvCompileSdkVersion')) {cdvCompileSdkVersion = null;@@ -65,6 +113,14 @@ ext {if (!project.hasProperty('cdvMinSdkVersion')) {cdvMinSdkVersion = null}+ // Sets the maxSdkVersion to the given value.+ if (!project.hasProperty('cdvMaxSdkVersion')) {+ cdvMaxSdkVersion = null+ }+ // The value for android.targetSdkVersion.+ if (!project.hasProperty('cdvTargetSdkVersion')) {+ cdvTargetSdkVersion = null;+ }// Whether to build architecture-specific APKs.if (!project.hasProperty('cdvBuildMultipleApks')) {cdvBuildMultipleApks = null@@ -104,10 +160,12 @@ if (hasBuildExtras2) {}// Set property defaults after extension .gradle files.-if (ext.cdvCompileSdkVersion == null) {- ext.cdvCompileSdkVersion = privateHelpers.getProjectTarget()- //ext.cdvCompileSdkVersion = project.ext.defaultCompileSdkVersion-}+ext.cdvCompileSdkVersion = cdvCompileSdkVersion == null ? (+ defaultCompileSdkVersion == null+ ? privateHelpers.getProjectTarget()+ : defaultCompileSdkVersion+) : Integer.parseInt('' + cdvCompileSdkVersion);+if (ext.cdvBuildToolsVersion == null) {ext.cdvBuildToolsVersion = privateHelpers.findLatestInstalledBuildTools()//ext.cdvBuildToolsVersion = project.ext.defaultBuildToolsVersion@@ -122,7 +180,14 @@ if (ext.cdvReleaseSigningPropertiesFile == null && file('../release-signing.prop// Cast to appropriate types.ext.cdvBuildMultipleApks = cdvBuildMultipleApks == null ? false : cdvBuildMultipleApks.toBoolean();ext.cdvVersionCodeForceAbiDigit = cdvVersionCodeForceAbiDigit == null ? false : cdvVersionCodeForceAbiDigit.toBoolean();++// minSdkVersion, maxSdkVersion and targetSdkVersionext.cdvMinSdkVersion = cdvMinSdkVersion == null ? defaultMinSdkVersion : Integer.parseInt('' + cdvMinSdkVersion)+if (cdvMaxSdkVersion != null) {+ ext.cdvMaxSdkVersion = Integer.parseInt('' + cdvMaxSdkVersion)+}+ext.cdvTargetSdkVersion = cdvTargetSdkVersion == null ? defaultTargetSdkVersion : Integer.parseInt('' + cdvTargetSdkVersion)+ext.cdvVersionCode = cdvVersionCode == null ? null : Integer.parseInt('' + cdvVersionCode)def computeBuildTargetName(debugBuild) {@@ -145,24 +210,27 @@ cdvBuildRelease.dependsOn {return computeBuildTargetName(false)}-task cdvPrintProps << {- println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)- println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)- println('cdvVersionCode=' + cdvVersionCode)- println('cdvVersionCodeForceAbiDigit=' + cdvVersionCodeForceAbiDigit)- println('cdvMinSdkVersion=' + cdvMinSdkVersion)- println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)- println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)- println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)- println('cdvBuildArch=' + cdvBuildArch)- println('computedVersionCode=' + android.defaultConfig.versionCode)- android.productFlavors.each { flavor ->- println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)+task cdvPrintProps {+ doLast {+ println('cdvCompileSdkVersion=' + cdvCompileSdkVersion)+ println('cdvBuildToolsVersion=' + cdvBuildToolsVersion)+ println('cdvVersionCode=' + cdvVersionCode)+ println('cdvVersionCodeForceAbiDigit=' + cdvVersionCodeForceAbiDigit)+ println('cdvMinSdkVersion=' + cdvMinSdkVersion)+ println('cdvMaxSdkVersion=' + cdvMaxSdkVersion)+ println('cdvTargetSdkVersion=' + cdvTargetSdkVersion)+ println('cdvBuildMultipleApks=' + cdvBuildMultipleApks)+ println('cdvReleaseSigningPropertiesFile=' + cdvReleaseSigningPropertiesFile)+ println('cdvDebugSigningPropertiesFile=' + cdvDebugSigningPropertiesFile)+ println('cdvBuildArch=' + cdvBuildArch)+ println('computedVersionCode=' + android.defaultConfig.versionCode)+ android.productFlavors.each { flavor ->+ println('computed' + flavor.name.capitalize() + 'VersionCode=' + flavor.versionCode)+ }}}android {-defaultConfig {versionCode cdvVersionCode ?: new BigInteger("" + privateHelpers.extractIntFromManifest("versionCode"))applicationId privateHelpers.extractStringFromManifest("package")@@ -170,6 +238,14 @@ android {if (cdvMinSdkVersion != null) {minSdkVersion cdvMinSdkVersion}++ if (cdvMaxSdkVersion != null) {+ maxSdkVersion cdvMaxSdkVersion+ }++ if(cdvTargetSdkVersion != null) {+ targetSdkVersion cdvTargetSdkVersion+ }}lintOptions {@@ -249,9 +325,14 @@ android {}addSigningProps(cdvReleaseSigningPropertiesFile, signingConfigs.release)}+if (cdvDebugSigningPropertiesFile) {addSigningProps(cdvDebugSigningPropertiesFile, signingConfigs.debug)}++ sourceSets {+ main.java.srcDirs += 'src/main/kotlin'+ }}/*@@ -263,9 +344,15 @@ android {dependencies {implementation fileTree(dir: 'libs', include: '*.jar')++ if (cdvHelpers.getConfigPreference('GradlePluginKotlinEnabled', 'false').toBoolean()) {+ implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"+ }+// SUB-PROJECT DEPENDENCIES STARTimplementation(project(path: ":CordovaLib"))- compile "com.android.support:support-v4:27.+"+ implementation "com.android.support:support-v4:27.+"+ implementation "com.android.support:support-v4:24.1.1+"// SUB-PROJECT DEPENDENCIES END}@@ -328,3 +415,7 @@ for (def func : cdvPluginPostBuildExtras) {if (hasProperty('postBuildExtras')) {postBuildExtras()}++if (cdvHelpers.getConfigPreference('GradlePluginGoogleServicesEnabled', 'false').toBoolean()) {+ apply plugin: 'com.google.gms.google-services'+}diff --git a/cordova/platforms/android/app/src/main/AndroidManifest.xml b/cordova/platforms/android/app/src/main/AndroidManifest.xmlindex fbf688356..29c2538c2 100644--- a/cordova/platforms/android/app/src/main/AndroidManifest.xml+++ b/cordova/platforms/android/app/src/main/AndroidManifest.xml@@ -2,8 +2,8 @@<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="org.tagspaces.mobile" xmlns:android="http://schemas.android.com/apk/res/android"><supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" /><uses-permission android:name="android.permission.INTERNET" />- <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">- <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">+ <application android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true">+ <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize"><intent-filter android:label="@string/launcher_name"><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />@@ -13,6 +13,9 @@<provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="org.apache.cordova.camera.FileProvider"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/camera_provider_paths" /></provider>+ <provider android:authorities="${applicationId}.fileOpener2.provider" android:exported="false" android:grantUriPermissions="true" android:name="io.github.pwlin.cordova.plugins.fileopener2.FileProvider">+ <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/opener_paths" />+ </provider><receiver android:enabled="true" android:name="nl.xservices.plugins.ShareChooserPendingIntent"><intent-filter><action android:name="android.intent.action.SEND" />@@ -21,11 +24,7 @@<provider android:authorities="${applicationId}.sharing.provider" android:exported="false" android:grantUriPermissions="true" android:name="nl.xservices.plugins.FileProvider"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/sharing_paths" /></provider>- <provider android:authorities="${applicationId}.fileOpener2.provider" android:exported="false" android:grantUriPermissions="true" android:name="io.github.pwlin.cordova.plugins.fileopener2.FileProvider">- <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/opener_paths" />- </provider></application>- <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="27" /><uses-permission android:name="android.permission.WAKE_LOCK" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/Zip.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/Zip.javadeleted file mode 100644index 4b5de862d..000000000--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/Zip.java+++ /dev/null@@ -1,206 +0,0 @@-package org.apache.cordova;--import java.io.BufferedInputStream;-import java.io.File;-import java.io.FileOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.io.FileNotFoundException;-import java.util.zip.ZipEntry;-import java.util.zip.ZipInputStream;---import android.net.Uri;-import org.apache.cordova.CallbackContext;-import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.CordovaResourceApi.OpenForReadResult;-import org.apache.cordova.PluginResult;-import org.json.JSONException;-import org.json.JSONObject;--import android.util.Log;--public class Zip extends CordovaPlugin {-- private static final String LOG_TAG = "Zip";-- @Override- public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {- if ("unzip".equals(action)) {- unzip(args, callbackContext);- return true;- }- return false;- }-- private void unzip(final CordovaArgs args, final CallbackContext callbackContext) {- this.cordova.getThreadPool().execute(new Runnable() {- public void run() {- unzipSync(args, callbackContext);- }- });- }-- // Can't use DataInputStream because it has the wrong endian-ness.- private static int readInt(InputStream is) throws IOException {- int a = is.read();- int b = is.read();- int c = is.read();- int d = is.read();- return a | b << 8 | c << 16 | d << 24;- }-- private void unzipSync(CordovaArgs args, CallbackContext callbackContext) {- InputStream inputStream = null;- try {- String zipFileName = args.getString(0);- String outputDirectory = args.getString(1);-- // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile://- // Accept a path or a URI for the source zip.- Uri zipUri = getUriForArg(zipFileName);- Uri outputUri = getUriForArg(outputDirectory);-- CordovaResourceApi resourceApi = webView.getResourceApi();-- File tempFile = resourceApi.mapUriToFile(zipUri);- if (tempFile == null || !tempFile.exists()) {- String errorMessage = "Zip file does not exist";- callbackContext.error(errorMessage);- Log.e(LOG_TAG, errorMessage);- return;- }-- File outputDir = resourceApi.mapUriToFile(outputUri);- outputDirectory = outputDir.getAbsolutePath();- outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator;- if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())){- String errorMessage = "Could not create output directory";- callbackContext.error(errorMessage);- Log.e(LOG_TAG, errorMessage);- return;- }-- OpenForReadResult zipFile = resourceApi.openForRead(zipUri);- ProgressEvent progress = new ProgressEvent();- progress.setTotal(zipFile.length);-- inputStream = new BufferedInputStream(zipFile.inputStream);- inputStream.mark(10);- int magic = readInt(inputStream);-- if (magic != 875721283) { // CRX identifier- inputStream.reset();- } else {- // CRX files contain a header. This header consists of:- // * 4 bytes of magic number- // * 4 bytes of CRX format version,- // * 4 bytes of public key length- // * 4 bytes of signature length- // * the public key- // * the signature- // and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream.- readInt(inputStream); // version == 2.- int pubkeyLength = readInt(inputStream);- int signatureLength = readInt(inputStream);-- inputStream.skip(pubkeyLength + signatureLength);- progress.setLoaded(16 + pubkeyLength + signatureLength);- }-- // The inputstream is now pointing at the start of the actual zip file content.- ZipInputStream zis = new ZipInputStream(inputStream);- inputStream = zis;-- ZipEntry ze;- byte[] buffer = new byte[32 * 1024];- boolean anyEntries = false;-- while ((ze = zis.getNextEntry()) != null)- {- anyEntries = true;- String compressedName = ze.getName();-- if (ze.isDirectory()) {- File dir = new File(outputDirectory + compressedName);- dir.mkdirs();- } else {- File file = new File(outputDirectory + compressedName);- file.getParentFile().mkdirs();- if(file.exists() || file.createNewFile()){- Log.w("Zip", "extracting: " + file.getPath());- FileOutputStream fout = new FileOutputStream(file);- int count;- while ((count = zis.read(buffer)) != -1)- {- fout.write(buffer, 0, count);- }- fout.close();- }-- }- progress.addLoaded(ze.getCompressedSize());- updateProgress(callbackContext, progress);- zis.closeEntry();- }-- // final progress = 100%- progress.setLoaded(progress.getTotal());- updateProgress(callbackContext, progress);-- if (anyEntries)- callbackContext.success();- else- callbackContext.error("Bad zip file");- } catch (Exception e) {- String errorMessage = "An error occurred while unzipping.";- callbackContext.error(errorMessage);- Log.e(LOG_TAG, errorMessage, e);- } finally {- if (inputStream != null) {- try {- inputStream.close();- } catch (IOException e) {- }- }- }- }-- private void updateProgress(CallbackContext callbackContext, ProgressEvent progress) throws JSONException {- PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());- pluginResult.setKeepCallback(true);- callbackContext.sendPluginResult(pluginResult);- }-- private Uri getUriForArg(String arg) {- CordovaResourceApi resourceApi = webView.getResourceApi();- Uri tmpTarget = Uri.parse(arg);- return resourceApi.remapUri(- tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(arg)));- }-- private static class ProgressEvent {- private long loaded;- private long total;- public long getLoaded() {- return loaded;- }- public void setLoaded(long loaded) {- this.loaded = loaded;- }- public void addLoaded(long add) {- this.loaded += add;- }- public long getTotal() {- return total;- }- public void setTotal(long total) {- this.total = total;- }- public JSONObject toJSONObject() throws JSONException {- return new JSONObject(- "{loaded:" + loaded +- ",total:" + total + "}");- }- }-}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileProgressResult.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileProgressResult.javadeleted file mode 100644index 76a7b13a7..000000000--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileProgressResult.java+++ /dev/null@@ -1,63 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/-package org.apache.cordova.filetransfer;--import org.json.JSONException;-import org.json.JSONObject;--/**- * Encapsulates in-progress status of uploading or downloading a file to a remote server.- */-public class FileProgressResult {-- private boolean lengthComputable = false; // declares whether total is known- private long loaded = 0; // bytes sent so far- private long total = 0; // bytes total, if known-- public boolean getLengthComputable() {- return lengthComputable;- }-- public void setLengthComputable(boolean computable) {- this.lengthComputable = computable;- }-- public long getLoaded() {- return loaded;- }-- public void setLoaded(long bytes) {- this.loaded = bytes;- }-- public long getTotal() {- return total;- }-- public void setTotal(long bytes) {- this.total = bytes;- }-- public JSONObject toJSONObject() throws JSONException {- return new JSONObject(- "{loaded:" + loaded +- ",total:" + total +- ",lengthComputable:" + (lengthComputable ? "true" : "false") + "}");- }-}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileTransfer.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileTransfer.javadeleted file mode 100644index 5a3c5d623..000000000--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileTransfer.java+++ /dev/null@@ -1,932 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/-package org.apache.cordova.filetransfer;--import java.io.BufferedReader;-import java.io.ByteArrayOutputStream;-import java.io.Closeable;-import java.io.File;-import java.io.FileNotFoundException;-import java.io.FilterInputStream;-import java.io.IOException;-import java.io.InputStream;-import java.io.InputStreamReader;-import java.io.OutputStream;-import java.lang.reflect.InvocationTargetException;-import java.lang.reflect.Field;-import java.lang.reflect.Method;-import java.net.HttpURLConnection;-import java.net.URLConnection;-import java.util.HashMap;-import java.util.Iterator;-import java.util.zip.GZIPInputStream;-import java.util.zip.Inflater;--import org.apache.cordova.CallbackContext;-import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.CordovaResourceApi;-import org.apache.cordova.CordovaResourceApi.OpenForReadResult;-import org.apache.cordova.LOG;-import org.apache.cordova.PluginManager;-import org.apache.cordova.PluginResult;-import org.apache.cordova.Whitelist;-import org.apache.cordova.file.FileUtils;-import org.json.JSONArray;-import org.json.JSONException;-import org.json.JSONObject;--import android.net.Uri;-import android.os.Build;-import android.webkit.CookieManager;--public class FileTransfer extends CordovaPlugin {-- private static final String LOG_TAG = "FileTransfer";- private static final String LINE_START = "--";- private static final String LINE_END = "\r\n";- private static final String BOUNDARY = "+++++";-- public static int FILE_NOT_FOUND_ERR = 1;- public static int INVALID_URL_ERR = 2;- public static int CONNECTION_ERR = 3;- public static int ABORTED_ERR = 4;- public static int NOT_MODIFIED_ERR = 5;-- private static HashMap<String, RequestContext> activeRequests = new HashMap<String, RequestContext>();- private static final int MAX_BUFFER_SIZE = 16 * 1024;-- private static final class RequestContext {- String source;- String target;- File targetFile;- CallbackContext callbackContext;- HttpURLConnection connection;- boolean aborted;- RequestContext(String source, String target, CallbackContext callbackContext) {- this.source = source;- this.target = target;- this.callbackContext = callbackContext;- }- void sendPluginResult(PluginResult pluginResult) {- synchronized (this) {- if (!aborted) {- callbackContext.sendPluginResult(pluginResult);- }- }- }- }-- /**- * Adds an interface method to an InputStream to return the number of bytes- * read from the raw stream. This is used to track total progress against- * the HTTP Content-Length header value from the server.- */- private static abstract class TrackingInputStream extends FilterInputStream {- public TrackingInputStream(final InputStream in) {- super(in);- }- public abstract long getTotalRawBytesRead();- }-- private static class ExposedGZIPInputStream extends GZIPInputStream {- public ExposedGZIPInputStream(final InputStream in) throws IOException {- super(in);- }- public Inflater getInflater() {- return inf;- }- }-- /**- * Provides raw bytes-read tracking for a GZIP input stream. Reports the- * total number of compressed bytes read from the input, rather than the- * number of uncompressed bytes.- */- private static class TrackingGZIPInputStream extends TrackingInputStream {- private ExposedGZIPInputStream gzin;- public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException {- super(gzin);- this.gzin = gzin;- }- public long getTotalRawBytesRead() {- return gzin.getInflater().getBytesRead();- }- }-- /**- * Provides simple total-bytes-read tracking for an existing InputStream- */- private static class SimpleTrackingInputStream extends TrackingInputStream {- private long bytesRead = 0;- public SimpleTrackingInputStream(InputStream stream) {- super(stream);- }-- private int updateBytesRead(int newBytesRead) {- if (newBytesRead != -1) {- bytesRead += newBytesRead;- }- return newBytesRead;- }-- @Override- public int read() throws IOException {- return updateBytesRead(super.read());- }-- // Note: FilterInputStream delegates read(byte[] bytes) to the below method,- // so we don't override it or else double count (CB-5631).- @Override- public int read(byte[] bytes, int offset, int count) throws IOException {- return updateBytesRead(super.read(bytes, offset, count));- }-- public long getTotalRawBytesRead() {- return bytesRead;- }- }-- @Override- public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {- if (action.equals("upload") || action.equals("download")) {- String source = args.getString(0);- String target = args.getString(1);-- if (action.equals("upload")) {- upload(source, target, args, callbackContext);- } else {- download(source, target, args, callbackContext);- }- return true;- } else if (action.equals("abort")) {- String objectId = args.getString(0);- abort(objectId);- callbackContext.success();- return true;- }- return false;- }-- private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {- try {- for (Iterator<?> iter = headers.keys(); iter.hasNext(); ) {- /* RFC 2616 says that non-ASCII characters and control- * characters are not allowed in header names or values.- * Additionally, spaces are not allowed in header names.- * RFC 2046 Quoted-printable encoding may be used to encode- * arbitrary characters, but we donon- not do that encoding here.- */- String headerKey = iter.next().toString();- String cleanHeaderKey = headerKey.replaceAll("\\n","")- .replaceAll("\\s+","")- .replaceAll(":", "")- .replaceAll("[^\\x20-\\x7E]+", "");-- JSONArray headerValues = headers.optJSONArray(headerKey);- if (headerValues == null) {- headerValues = new JSONArray();-- /* RFC 2616 also says that any amount of consecutive linear- * whitespace within a header value can be replaced with a- * single space character, without affecting the meaning of- * that value.- */-- String headerValue = headers.getString(headerKey);- String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n"," ").replaceAll("[^\\x20-\\x7E]+", " ");- headerValues.put(finalValue);- }-- //Use the clean header key, not the one that we passed in- connection.setRequestProperty(cleanHeaderKey, headerValues.getString(0));- for (int i = 1; i < headerValues.length(); ++i) {- connection.addRequestProperty(headerKey, headerValues.getString(i));- }- }- } catch (JSONException e1) {- // No headers to be manipulated!- }- }-- private String getCookies(final String target) {- boolean gotCookie = false;- String cookie = null;- Class webViewClass = webView.getClass();- try {- Method gcmMethod = webViewClass.getMethod("getCookieManager");- Class iccmClass = gcmMethod.getReturnType();- Method gcMethod = iccmClass.getMethod("getCookie", String.class);-- cookie = (String)gcMethod.invoke(- iccmClass.cast(- gcmMethod.invoke(webView)- ), target);-- gotCookie = true;- } catch (NoSuchMethodException e) {- } catch (IllegalAccessException e) {- } catch (InvocationTargetException e) {- } catch (ClassCastException e) {- }-- if (!gotCookie && CookieManager.getInstance() != null) {- cookie = CookieManager.getInstance().getCookie(target);- }-- return cookie;- }-- /**- * Uploads the specified file to the server URL provided using an HTTP multipart request.- * @param source Full path of the file on the file system- * @param target URL of the server to receive the file- * @param args JSON Array of args- * @param callbackContext callback id for optional progress reports- *- * args[2] fileKey Name of file request parameter- * args[3] fileName File name to be used on server- * args[4] mimeType Describes file content type- * args[5] params key:value pairs of user-defined parameters- * @return FileUploadResult containing result of upload request- */- private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {- LOG.d(LOG_TAG, "upload " + source + " to " + target);-- // Setup the options- final String fileKey = getArgument(args, 2, "file");- final String fileName = getArgument(args, 3, "image.jpg");- final String mimeType = getArgument(args, 4, "image/jpeg");- final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);- // Always use chunked mode unless set to false as per API- final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);- // Look for headers on the params map for backwards compatibility with older Cordova versions.- final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8);- final String objectId = args.getString(9);- final String httpMethod = getArgument(args, 10, "POST");-- final CordovaResourceApi resourceApi = webView.getResourceApi();-- LOG.d(LOG_TAG, "fileKey: " + fileKey);- LOG.d(LOG_TAG, "fileName: " + fileName);- LOG.d(LOG_TAG, "mimeType: " + mimeType);- LOG.d(LOG_TAG, "params: " + params);- LOG.d(LOG_TAG, "chunkedMode: " + chunkedMode);- LOG.d(LOG_TAG, "headers: " + headers);- LOG.d(LOG_TAG, "objectId: " + objectId);- LOG.d(LOG_TAG, "httpMethod: " + httpMethod);-- final Uri targetUri = resourceApi.remapUri(Uri.parse(target));-- int uriType = CordovaResourceApi.getUriType(targetUri);- final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;- if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {- JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);- LOG.e(LOG_TAG, "Unsupported URI: " + targetUri);- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));- return;- }-- final RequestContext context = new RequestContext(source, target, callbackContext);- synchronized (activeRequests) {- activeRequests.put(objectId, context);- }-- cordova.getThreadPool().execute(new Runnable() {- public void run() {- if (context.aborted) {- return;- }-- // We should call remapUri on background thread otherwise it throws- // IllegalStateException when trying to remap 'cdvfile://localhost/content/...' URIs- // via ContentFilesystem (see https://issues.apache.org/jira/browse/CB-9022)- Uri tmpSrc = Uri.parse(source);- final Uri sourceUri = resourceApi.remapUri(- tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));-- HttpURLConnection conn = null;- int totalBytes = 0;- int fixedLength = -1;- try {- // Create return object- FileUploadResult result = new FileUploadResult();- FileProgressResult progress = new FileProgressResult();-- //------------------ CLIENT REQUEST- // Open a HTTP connection to the URL based on protocol- conn = resourceApi.createHttpConnection(targetUri);-- // Allow Inputs- conn.setDoInput(true);-- // Allow Outputs- conn.setDoOutput(true);-- // Don't use a cached copy.- conn.setUseCaches(false);-- // Use a post method.- conn.setRequestMethod(httpMethod);-- // if we specified a Content-Type header, don't do multipart form upload- boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");- if (multipartFormUpload) {- conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);- }-- // Set the cookies on the response- String cookie = getCookies(target);-- if (cookie != null) {- conn.setRequestProperty("Cookie", cookie);- }-- // Handle the other headers- if (headers != null) {- addHeadersToRequest(conn, headers);- }-- /*- * Store the non-file portions of the multipart data as a string, so that we can add it- * to the contentSize, since it is part of the body of the HTTP request.- */- StringBuilder beforeData = new StringBuilder();- try {- for (Iterator<?> iter = params.keys(); iter.hasNext();) {- Object key = iter.next();- if(!String.valueOf(key).equals("headers"))- {- beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);- beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"');- beforeData.append(LINE_END).append(LINE_END);- beforeData.append(params.getString(key.toString()));- beforeData.append(LINE_END);- }- }- } catch (JSONException e) {- LOG.e(LOG_TAG, e.getMessage(), e);- }-- beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);- beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");- beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);- beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);- byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");- byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8");--- // Get a input stream of the file on the phone- OpenForReadResult readResult = resourceApi.openForRead(sourceUri);-- int stringLength = beforeDataBytes.length + tailParamsBytes.length;- if (readResult.length >= 0) {- fixedLength = (int)readResult.length;- if (multipartFormUpload)- fixedLength += stringLength;- progress.setLengthComputable(true);- progress.setTotal(fixedLength);- }- LOG.d(LOG_TAG, "Content Length: " + fixedLength);- // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.- // http://code.google.com/p/android/issues/detail?id=3164- // It also causes OOM if HTTPS is used, even on newer devices.- boolean useChunkedMode = chunkedMode || (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO);- useChunkedMode = useChunkedMode || (fixedLength == -1);-- if (useChunkedMode) {- conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);- // Although setChunkedStreamingMode sets this header, setting it explicitly here works- // around an OutOfMemoryException when using https.- conn.setRequestProperty("Transfer-Encoding", "chunked");- } else {- conn.setFixedLengthStreamingMode(fixedLength);-- if (useHttps) {- LOG.w(LOG_TAG, "setFixedLengthStreamingMode could cause OutOfMemoryException - switch to chunkedMode=true to avoid it if this is an issue.");- }- }-- conn.connect();-- OutputStream sendStream = null;- try {- sendStream = conn.getOutputStream();- synchronized (context) {- if (context.aborted) {- return;- }- context.connection = conn;- }-- if (multipartFormUpload) {- //We don't want to change encoding, we just want this to write for all Unicode.- sendStream.write(beforeDataBytes);- totalBytes += beforeDataBytes.length;- }-- // create a buffer of maximum size- int bytesAvailable = readResult.inputStream.available();- int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);- byte[] buffer = new byte[bufferSize];-- // read file and write it into form...- int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);-- long prevBytesRead = 0;- while (bytesRead > 0) {- totalBytes += bytesRead;- result.setBytesSent(totalBytes);- sendStream.write(buffer, 0, bytesRead);- if (totalBytes > prevBytesRead + 102400) {- prevBytesRead = totalBytes;- LOG.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");- }- bytesAvailable = readResult.inputStream.available();- bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);- bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);-- // Send a progress event.- progress.setLoaded(totalBytes);- PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());- progressResult.setKeepCallback(true);- context.sendPluginResult(progressResult);- }-- if (multipartFormUpload) {- // send multipart form data necessary after file data...- sendStream.write(tailParamsBytes);- totalBytes += tailParamsBytes.length;- }- sendStream.flush();- } finally {- safeClose(readResult.inputStream);- safeClose(sendStream);- }- synchronized (context) {- context.connection = null;- }- LOG.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);-- //------------------ read the SERVER RESPONSE- String responseString;- int responseCode = conn.getResponseCode();- LOG.d(LOG_TAG, "response code: " + responseCode);- LOG.d(LOG_TAG, "response headers: " + conn.getHeaderFields());- TrackingInputStream inStream = null;- try {- inStream = getInputStream(conn);- synchronized (context) {- if (context.aborted) {- return;- }- context.connection = conn;- }-- ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength()));- byte[] buffer = new byte[1024];- int bytesRead = 0;- // write bytes to file- while ((bytesRead = inStream.read(buffer)) > 0) {- out.write(buffer, 0, bytesRead);- }- responseString = out.toString("UTF-8");- } finally {- synchronized (context) {- context.connection = null;- }- safeClose(inStream);- }-- LOG.d(LOG_TAG, "got response from server");- LOG.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));-- // send request and retrieve response- result.setResponseCode(responseCode);- result.setResponse(responseString);-- context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));- } catch (FileNotFoundException e) {- JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e);- LOG.e(LOG_TAG, error.toString(), e);- context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));- } catch (IOException e) {- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e);- LOG.e(LOG_TAG, error.toString(), e);- LOG.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");- context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));- } catch (JSONException e) {- LOG.e(LOG_TAG, e.getMessage(), e);- context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));- } catch (Throwable t) {- // Shouldn't happen, but will- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t);- LOG.e(LOG_TAG, error.toString(), t);- context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));- } finally {- synchronized (activeRequests) {- activeRequests.remove(objectId);- }- }- }- });- }-- private static void safeClose(Closeable stream) {- if (stream != null) {- try {- stream.close();- } catch (IOException e) {- }- }- }-- private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {- String encoding = conn.getContentEncoding();- if (encoding != null && encoding.equalsIgnoreCase("gzip")) {- return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));- }- return new SimpleTrackingInputStream(conn.getInputStream());- }-- private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection, Throwable throwable) {-- int httpStatus = 0;- StringBuilder bodyBuilder = new StringBuilder();- String body = null;- if (connection != null) {- try {- if (connection instanceof HttpURLConnection) {- httpStatus = ((HttpURLConnection)connection).getResponseCode();- InputStream err = ((HttpURLConnection) connection).getErrorStream();- if(err != null)- {- BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8"));- try {- String line = reader.readLine();- while(line != null) {- bodyBuilder.append(line);- line = reader.readLine();- if(line != null) {- bodyBuilder.append('\n');- }- }- body = bodyBuilder.toString();- } finally {- reader.close();- }- }- }- // IOException can leave connection object in a bad state, so catch all exceptions.- } catch (Throwable e) {- LOG.w(LOG_TAG, "Error getting HTTP status code from connection.", e);- }- }-- return createFileTransferError(errorCode, source, target, body, httpStatus, throwable);- }-- /**- * Create an error object based on the passed in errorCode- * @param errorCode the error- * @return JSONObject containing the error- */- private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) {- JSONObject error = null;- try {- error = new JSONObject();- error.put("code", errorCode);- error.put("source", source);- error.put("target", target);- if(body != null)- {- error.put("body", body);- }- if (httpStatus != null) {- error.put("http_status", httpStatus);- }- if (throwable != null) {- String msg = throwable.getMessage();- if (msg == null || "".equals(msg)) {- msg = throwable.toString();- }- error.put("exception", msg);- }- } catch (JSONException e) {- LOG.e(LOG_TAG, e.getMessage(), e);- }- return error;- }-- /**- * Convenience method to read a parameter from the list of JSON args.- * @param args the args passed to the Plugin- * @param position the position to retrieve the arg from- * @param defaultString the default to be used if the arg does not exist- * @return String with the retrieved value- */- private static String getArgument(JSONArray args, int position, String defaultString) {- String arg = defaultString;- if (args.length() > position) {- arg = args.optString(position);- if (arg == null || "null".equals(arg)) {- arg = defaultString;- }- }- return arg;- }-- /**- * Downloads a file form a given URL and saves it to the specified directory.- *- * @param source URL of the server to receive the file- * @param target Full path of the file on the file system- */- private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {- LOG.d(LOG_TAG, "download " + source + " to " + target);-- final CordovaResourceApi resourceApi = webView.getResourceApi();-- final String objectId = args.getString(3);- final JSONObject headers = args.optJSONObject(4);-- final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));- int uriType = CordovaResourceApi.getUriType(sourceUri);- final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;- final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;- if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {- JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);- LOG.e(LOG_TAG, "Unsupported URI: " + sourceUri);- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));- return;- }-- /* This code exists for compatibility between 3.x and 4.x versions of Cordova.- * Previously the CordovaWebView class had a method, getWhitelist, which would- * return a Whitelist object. Since the fixed whitelist is removed in Cordova 4.x,- * the correct call now is to shouldAllowRequest from the plugin manager.- */- Boolean shouldAllowRequest = null;- if (isLocalTransfer) {- shouldAllowRequest = true;- }- if (shouldAllowRequest == null) {- try {- Method gwl = webView.getClass().getMethod("getWhitelist");- Whitelist whitelist = (Whitelist)gwl.invoke(webView);- shouldAllowRequest = whitelist.isUrlWhiteListed(source);- } catch (NoSuchMethodException e) {- } catch (IllegalAccessException e) {- } catch (InvocationTargetException e) {- }- }- if (shouldAllowRequest == null) {- try {- Method gpm = webView.getClass().getMethod("getPluginManager");- PluginManager pm = (PluginManager)gpm.invoke(webView);- Method san = pm.getClass().getMethod("shouldAllowRequest", String.class);- shouldAllowRequest = (Boolean)san.invoke(pm, source);- } catch (NoSuchMethodException e) {- } catch (IllegalAccessException e) {- } catch (InvocationTargetException e) {- }- }-- if (!Boolean.TRUE.equals(shouldAllowRequest)) {- LOG.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null);- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));- return;- }--- final RequestContext context = new RequestContext(source, target, callbackContext);- synchronized (activeRequests) {- activeRequests.put(objectId, context);- }-- cordova.getThreadPool().execute(new Runnable() {- public void run() {- if (context.aborted) {- return;- }-- // Accept a path or a URI for the source.- Uri tmpTarget = Uri.parse(target);- Uri targetUri = resourceApi.remapUri(- tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));- HttpURLConnection connection = null;- File file = null;- PluginResult result = null;- TrackingInputStream inputStream = null;- boolean cached = false;-- OutputStream outputStream = null;- try {- OpenForReadResult readResult = null;-- file = resourceApi.mapUriToFile(targetUri);- context.targetFile = file;-- LOG.d(LOG_TAG, "Download file:" + sourceUri);-- FileProgressResult progress = new FileProgressResult();-- if (isLocalTransfer) {- readResult = resourceApi.openForRead(sourceUri);- if (readResult.length != -1) {- progress.setLengthComputable(true);- progress.setTotal(readResult.length);- }- inputStream = new SimpleTrackingInputStream(readResult.inputStream);- } else {- // connect to server- // Open a HTTP connection to the URL based on protocol- connection = resourceApi.createHttpConnection(sourceUri);- connection.setRequestMethod("GET");-- // TODO: Make OkHttp use this CookieManager by default.- String cookie = getCookies(sourceUri.toString());-- if(cookie != null)- {- connection.setRequestProperty("cookie", cookie);- }-- // This must be explicitly set for gzip progress tracking to work.- connection.setRequestProperty("Accept-Encoding", "gzip");-- // Handle the other headers- if (headers != null) {- addHeadersToRequest(connection, headers);- }-- connection.connect();- if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {- cached = true;- connection.disconnect();- LOG.d(LOG_TAG, "Resource not modified: " + source);- JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null);- result = new PluginResult(PluginResult.Status.ERROR, error);- } else {- if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) {- // Only trust content-length header if we understand- // the encoding -- identity or gzip- if (connection.getContentLength() != -1) {- progress.setLengthComputable(true);- progress.setTotal(connection.getContentLength());- }- }- inputStream = getInputStream(connection);- }- }-- if (!cached) {- try {- synchronized (context) {- if (context.aborted) {- return;- }- context.connection = connection;- }-- // write bytes to file- byte[] buffer = new byte[MAX_BUFFER_SIZE];- int bytesRead = 0;- outputStream = resourceApi.openOutputStream(targetUri);- while ((bytesRead = inputStream.read(buffer)) > 0) {- outputStream.write(buffer, 0, bytesRead);- // Send a progress event.- progress.setLoaded(inputStream.getTotalRawBytesRead());- PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());- progressResult.setKeepCallback(true);- context.sendPluginResult(progressResult);- }- } finally {- synchronized (context) {- context.connection = null;- }- safeClose(inputStream);- safeClose(outputStream);- }-- LOG.d(LOG_TAG, "Saved file: " + target);--- // create FileEntry object- Class webViewClass = webView.getClass();- PluginManager pm = null;- try {- Method gpm = webViewClass.getMethod("getPluginManager");- pm = (PluginManager) gpm.invoke(webView);- } catch (NoSuchMethodException e) {- } catch (IllegalAccessException e) {- } catch (InvocationTargetException e) {- }- if (pm == null) {- try {- Field pmf = webViewClass.getField("pluginManager");- pm = (PluginManager)pmf.get(webView);- } catch (NoSuchFieldException e) {- } catch (IllegalAccessException e) {- }- }- file = resourceApi.mapUriToFile(targetUri);- context.targetFile = file;- FileUtils filePlugin = (FileUtils) pm.getPlugin("File");- if (filePlugin != null) {- JSONObject fileEntry = filePlugin.getEntryForFile(file);- if (fileEntry != null) {- result = new PluginResult(PluginResult.Status.OK, fileEntry);- } else {- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null);- LOG.e(LOG_TAG, "File plugin cannot represent download path");- result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);- }- } else {- LOG.e(LOG_TAG, "File plugin not found; cannot save downloaded file");- result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file");- }- }- } catch (FileNotFoundException e) {- JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);- LOG.e(LOG_TAG, error.toString(), e);- result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);- } catch (IOException e) {- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);- LOG.e(LOG_TAG, error.toString(), e);- result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);- } catch (JSONException e) {- LOG.e(LOG_TAG, e.getMessage(), e);- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);- } catch (Throwable e) {- JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);- LOG.e(LOG_TAG, error.toString(), e);- result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);- } finally {- synchronized (activeRequests) {- activeRequests.remove(objectId);- }-- if (result == null) {- result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null));- }- // Remove incomplete download.- if (!cached && result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {- file.delete();- }- context.sendPluginResult(result);- }- }- });- }-- /**- * Abort an ongoing upload or download.- */- private void abort(String objectId) {- final RequestContext context;- synchronized (activeRequests) {- context = activeRequests.remove(objectId);- }- if (context != null) {- // Closing the streams can block, so execute on a background thread.- cordova.getThreadPool().execute(new Runnable() {- public void run() {- synchronized (context) {- File file = context.targetFile;- if (file != null) {- file.delete();- }- // Trigger the abort callback immediately to minimize latency between it and abort() being called.- JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1, null);- context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));- context.aborted = true;- if (context.connection != null) {- try {- context.connection.disconnect();- } catch (Exception e) {- LOG.e(LOG_TAG, "CB-8431 Catch workaround for fatal exception", e);- }- }- }- }- });- }- }-}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileUploadResult.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileUploadResult.javadeleted file mode 100644index c24ea78ae..000000000--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/filetransfer/FileUploadResult.java+++ /dev/null@@ -1,73 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/-package org.apache.cordova.filetransfer;--import org.json.JSONException;-import org.json.JSONObject;--/**- * Encapsulates the result and/or status of uploading a file to a remote server.- */-public class FileUploadResult {-- private long bytesSent = 0; // bytes sent- private int responseCode = -1; // HTTP response code- private String response = null; // HTTP response- private String objectId = null; // FileTransfer object id-- public long getBytesSent() {- return bytesSent;- }-- public void setBytesSent(long bytes) {- this.bytesSent = bytes;- }-- public int getResponseCode() {- return responseCode;- }-- public void setResponseCode(int responseCode) {- this.responseCode = responseCode;- }-- public String getResponse() {- return response;- }-- public void setResponse(String response) {- this.response = response;- }-- public String getObjectId() {- return objectId;- }-- public void setObjectId(String objectId) {- this.objectId = objectId;- }-- public JSONObject toJSONObject() throws JSONException {- return new JSONObject(- "{bytesSent:" + bytesSent +- ",responseCode:" + responseCode +- ",response:" + JSONObject.quote(response) +- ",objectId:" + JSONObject.quote(objectId) + "}");- }-}diff --git a/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.pngindex 2d564f49c..160086390 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-land-hdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.pngindex c7eae7ede..f7ad3cfad 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-land-ldpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.pngindex 3bf1ec2e9..b6243130f 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-land-mdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.pngindex 987a92462..9720f415c 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-land-xhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.pngindex ef9fc7400..80d6b4709 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-land-xxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.pngindex 8f9a458e1..84c5a2ba8 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-land-xxxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.pngindex 5875561d3..b2f60af64 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-port-hdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.pngindex 725420620..4b2abbb1a 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-port-ldpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.pngindex 9034b68fd..1f1ae9d45 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-port-mdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.pngindex 95dc8d849..690c57eb2 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-port-xhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.pngindex 9b6bfe4a8..214f0a011 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-port-xxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.png b/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.pngindex ec655cde1..c4ef7723b 100644Binary files a/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.png and b/cordova/platforms/android/app/src/main/res/drawable-port-xxxhdpi/screen.png differdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-hdpi/ic_launcher.pngsimilarity index 100%rename from cordova/platforms/android/app/src/main/res/mipmap-hdpi/icon.pngrename to cordova/platforms/android/app/src/main/res/mipmap-hdpi/ic_launcher.pngdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-mdpi/ic_launcher.pngsimilarity index 100%rename from cordova/platforms/android/app/src/main/res/mipmap-mdpi/icon.pngrename to cordova/platforms/android/app/src/main/res/mipmap-mdpi/ic_launcher.pngdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xhdpi/ic_launcher.pngsimilarity index 100%rename from cordova/platforms/android/app/src/main/res/mipmap-xhdpi/icon.pngrename to cordova/platforms/android/app/src/main/res/mipmap-xhdpi/ic_launcher.pngdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngsimilarity index 100%rename from cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/icon.pngrename to cordova/platforms/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngdiff --git a/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.png b/cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngsimilarity index 100%rename from cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/icon.pngrename to cordova/platforms/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngdiff --git a/cordova/platforms/android/app/src/main/res/xml/config.xml b/cordova/platforms/android/app/src/main/res/xml/config.xmlindex d00f6f706..b4e4eafd5 100644--- a/cordova/platforms/android/app/src/main/res/xml/config.xml+++ b/cordova/platforms/android/app/src/main/res/xml/config.xml@@ -17,24 +17,18 @@<param name="onload" value="true" /></feature><allow-navigation href="cdvfile:*" />+ <feature name="FileOpener2">+ <param name="android-package" value="io.github.pwlin.cordova.plugins.fileopener2.FileOpener2" />+ </feature><feature name="Whitelist"><param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" /><param name="onload" value="true" /></feature>- <feature name="SocialSharing">- <param name="android-package" value="nl.xservices.plugins.SocialSharing" />- </feature>- <feature name="FileOpener2">- <param name="android-package" value="io.github.pwlin.cordova.plugins.fileopener2.FileOpener2" />- </feature><feature name="Downloader"><param name="android-package" value="com.whebcraft.android.plugin.Downloader" /></feature>- <feature name="FileTransfer">- <param name="android-package" value="org.apache.cordova.filetransfer.FileTransfer" />- </feature>- <feature name="Zip">- <param name="android-package" value="org.apache.cordova.Zip" />+ <feature name="SocialSharing">+ <param name="android-package" value="nl.xservices.plugins.SocialSharing" /></feature><name>TagSpaces Beta</name><description>diff --git a/cordova/platforms/android/build.gradle b/cordova/platforms/android/build.gradleindex 569004f45..089660c28 100644--- a/cordova/platforms/android/build.gradle+++ b/cordova/platforms/android/build.gradle@@ -19,33 +19,31 @@// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {+ ext.kotlin_version = '1.3.50'repositories {- maven {- url "https://maven.google.com"- }+ google()jcenter()}dependencies {-+ classpath 'com.android.tools.build:gradle:4.0.0'+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"// NOTE: Do not place your application dependencies here; they belong// in the individual module build.gradle files- classpath 'com.android.tools.build:gradle:3.0.1'}}allprojects {repositories {- maven {- url "https://maven.google.com"- }+ google()jcenter()}+//This replaces project.properties w.r.t. build settingsproject.ext {- defaultBuildToolsVersion="27.0.1" //String- defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4- defaultTargetSdkVersion=27 //Integer - We ALWAYS target the latest by default- defaultCompileSdkVersion=27 //Integer - We ALWAYS compile with the latest by default+ defaultBuildToolsVersion="29.0.2" //String+ defaultMinSdkVersion=22 //Integer - Minimum requirement is Android 5.1+ defaultTargetSdkVersion=29 //Integer - We ALWAYS target the latest by default+ defaultCompileSdkVersion=29 //Integer - We ALWAYS compile with the latest by default}}diff --git a/cordova/platforms/android/cordova/Api.js b/cordova/platforms/android/cordova/Api.jsindex ae4d17bdd..91690a63e 100644--- a/cordova/platforms/android/cordova/Api.js+++ b/cordova/platforms/android/cordova/Api.js@@ -17,15 +17,24 @@under the License.*/+/**+ * @todo update coho to update this line.+ * @todo use `package.json` instead but first+ * figure out how this fit in with the platform-centered workflow structure.+ * This workflow would not have the `package.json` file.+ */+// Coho updates this line+const VERSION = '9.0.0';+var path = require('path');-var Q = require('q');var AndroidProject = require('./lib/AndroidProject');-var AndroidStudio = require('./lib/AndroidStudio');var PluginManager = require('cordova-common').PluginManager;var CordovaLogger = require('cordova-common').CordovaLogger;var selfEvents = require('cordova-common').events;+var ConfigParser = require('cordova-common').ConfigParser;+const prepare = require('./lib/prepare').prepare;var PLATFORM = 'android';@@ -52,360 +61,324 @@ function setupEvents (externalEventEmitter) {* The PlatformApi instance also should define the following field:** * platform: String that defines a platform name.+ * @class Api*/-function Api (platform, platformRootDir, events) {- this.platform = PLATFORM;- this.root = path.resolve(__dirname, '..');- this.builder = 'gradle';-- setupEvents(events);-- var self = this;-- this.locations = {- root: self.root,- www: path.join(self.root, 'assets/www'),- res: path.join(self.root, 'res'),- platformWww: path.join(self.root, 'platform_www'),- configXml: path.join(self.root, 'res/xml/config.xml'),- defaultConfigXml: path.join(self.root, 'cordova/defaults.xml'),- strings: path.join(self.root, 'res/values/strings.xml'),- manifest: path.join(self.root, 'AndroidManifest.xml'),- build: path.join(self.root, 'build'),- javaSrc: path.join(self.root, 'src'),- // NOTE: Due to platformApi spec we need to return relative paths here- cordovaJs: 'bin/templates/project/assets/www/cordova.js',- cordovaJsSrc: 'cordova-js-src'- };-- // XXX Override some locations for Android Studio projects- if (AndroidStudio.isAndroidStudioProject(self.root) === true) {- selfEvents.emit('log', 'Android Studio project detected');- this.builder = 'studio';- this.android_studio = true;- this.locations.configXml = path.join(self.root, 'app/src/main/res/xml/config.xml');- this.locations.strings = path.join(self.root, 'app/src/main/res/values/strings.xml');- this.locations.manifest = path.join(self.root, 'app/src/main/AndroidManifest.xml');- // We could have Java Source, we could have other languages- this.locations.javaSrc = path.join(self.root, 'app/src/main/java/');- this.locations.www = path.join(self.root, 'app/src/main/assets/www');- this.locations.res = path.join(self.root, 'app/src/main/res');+class Api {+ constructor (platform, platformRootDir, events) {+ this.platform = PLATFORM;+ this.root = path.resolve(__dirname, '..');++ setupEvents(events);++ const appMain = path.join(this.root, 'app', 'src', 'main');+ const appRes = path.join(appMain, 'res');++ this.locations = {+ root: this.root,+ www: path.join(appMain, 'assets', 'www'),+ res: appRes,+ platformWww: path.join(this.root, 'platform_www'),+ configXml: path.join(appRes, 'xml', 'config.xml'),+ defaultConfigXml: path.join(this.root, 'cordova', 'defaults.xml'),+ strings: path.join(appRes, 'values', 'strings.xml'),+ manifest: path.join(appMain, 'AndroidManifest.xml'),+ build: path.join(this.root, 'build'),+ javaSrc: path.join(appMain, 'java')+ };}-}-/**- * Installs platform to specified directory and creates a platform project.- *- * @param {String} destination Destination directory, where insatll platform to- * @param {ConfigParser} [config] ConfgiParser instance, used to retrieve- * project creation options, such as package id and project name.- * @param {Object} [options] An options object. The most common options are:- * @param {String} [options.customTemplate] A path to custom template, that- * should override the default one from platform.- * @param {Boolean} [options.link] Flag that indicates that platform's- * sources will be linked to installed platform instead of copying.- * @param {EventEmitter} [events] An EventEmitter instance that will be used for- * logging purposes. If no EventEmitter provided, all events will be logged to- * console- *- * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi- * instance or rejected with CordovaError.- */-Api.createPlatform = function (destination, config, options, events) {- events = setupEvents(events);- var result;- try {- result = require('../../lib/create').create(destination, config, options, events).then(function (destination) {- var PlatformApi = require(path.resolve(destination, 'cordova/Api'));- return new PlatformApi(PLATFORM, destination, events);- });- } catch (e) {- events.emit('error', 'createPlatform is not callable from the android project API.');- throw (e);+ /**+ * Gets a CordovaPlatform object, that represents the platform structure.+ *+ * @return {CordovaPlatform} A structure that contains the description of+ * platform's file structure and other properties of platform.+ */+ getPlatformInfo () {+ var result = {};+ result.locations = this.locations;+ result.root = this.root;+ result.name = this.platform;+ result.version = Api.version();+ result.projectConfig = this._config;++ return result;}- return result;-};-/**- * Updates already installed platform.- *- * @param {String} destination Destination directory, where platform installed- * @param {Object} [options] An options object. The most common options are:- * @param {String} [options.customTemplate] A path to custom template, that- * should override the default one from platform.- * @param {Boolean} [options.link] Flag that indicates that platform's- * sources will be linked to installed platform instead of copying.- * @param {EventEmitter} [events] An EventEmitter instance that will be used for- * logging purposes. If no EventEmitter provided, all events will be logged to- * console- *- * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi- * instance or rejected with CordovaError.- */-Api.updatePlatform = function (destination, options, events) {- events = setupEvents(events);- var result;- try {- result = require('../../lib/create').update(destination, options, events).then(function (destination) {- var PlatformApi = require(path.resolve(destination, 'cordova/Api'));- return new PlatformApi('android', destination, events);- });- } catch (e) {- events.emit('error', 'updatePlatform is not callable from the android project API, you will need to do this manually.');- throw (e);+ /**+ * Updates installed platform with provided www assets and new app+ * configuration. This method is required for CLI workflow and will be called+ * each time before build, so the changes, made to app configuration and www+ * code, will be applied to platform.+ *+ * @param {CordovaProject} cordovaProject A CordovaProject instance, that defines a+ * project structure and configuration, that should be applied to platform+ * (contains project's www location and ConfigParser instance for project's+ * config).+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError instance.+ */+ prepare (cordovaProject, prepareOptions) {+ cordovaProject.projectConfig = new ConfigParser(cordovaProject.locations.rootConfigXml || cordovaProject.projectConfig.path);++ return prepare.call(this, cordovaProject, prepareOptions);}- return result;-};--/**- * Gets a CordovaPlatform object, that represents the platform structure.- *- * @return {CordovaPlatform} A structure that contains the description of- * platform's file structure and other properties of platform.- */-Api.prototype.getPlatformInfo = function () {- var result = {};- result.locations = this.locations;- result.root = this.root;- result.name = this.platform;- result.version = require('./version');- result.projectConfig = this._config;- return result;-};--/**- * Updates installed platform with provided www assets and new app- * configuration. This method is required for CLI workflow and will be called- * each time before build, so the changes, made to app configuration and www- * code, will be applied to platform.- *- * @param {CordovaProject} cordovaProject A CordovaProject instance, that defines a- * project structure and configuration, that should be applied to platform- * (contains project's www location and ConfigParser instance for project's- * config).- *- * @return {Promise} Return a promise either fulfilled, or rejected with- * CordovaError instance.- */-Api.prototype.prepare = function (cordovaProject, prepareOptions) {- return require('./lib/prepare').prepare.call(this, cordovaProject, prepareOptions);-};--/**- * Installs a new plugin into platform. This method only copies non-www files- * (sources, libs, etc.) to platform. It also doesn't resolves the- * dependencies of plugin. Both of handling of www files, such as assets and- * js-files and resolving dependencies are the responsibility of caller.- *- * @param {PluginInfo} plugin A PluginInfo instance that represents plugin- * that will be installed.- * @param {Object} installOptions An options object. Possible options below:- * @param {Boolean} installOptions.link: Flag that specifies that plugin- * sources will be symlinked to app's directory instead of copying (if- * possible).- * @param {Object} installOptions.variables An object that represents- * variables that will be used to install plugin. See more details on plugin- * variables in documentation:- * https://cordova.apache.org/docs/en/4.0.0/plugin_ref_spec.md.html- *- * @return {Promise} Return a promise either fulfilled, or rejected with- * CordovaError instance.- */-Api.prototype.addPlugin = function (plugin, installOptions) {- var project = AndroidProject.getProjectFile(this.root);- var self = this;-- installOptions = installOptions || {};- installOptions.variables = installOptions.variables || {};- // Add PACKAGE_NAME variable into vars- if (!installOptions.variables.PACKAGE_NAME) {- installOptions.variables.PACKAGE_NAME = project.getPackageName();- }+ /**+ * Installs a new plugin into platform. This method only copies non-www files+ * (sources, libs, etc.) to platform. It also doesn't resolves the+ * dependencies of plugin. Both of handling of www files, such as assets and+ * js-files and resolving dependencies are the responsibility of caller.+ *+ * @param {PluginInfo} plugin A PluginInfo instance that represents plugin+ * that will be installed.+ * @param {Object} installOptions An options object. Possible options below:+ * @param {Boolean} installOptions.link: Flag that specifies that plugin+ * sources will be symlinked to app's directory instead of copying (if+ * possible).+ * @param {Object} installOptions.variables An object that represents+ * variables that will be used to install plugin. See more details on plugin+ * variables in documentation:+ * https://cordova.apache.org/docs/en/4.0.0/plugin_ref_spec.md.html+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError instance.+ */+ addPlugin (plugin, installOptions) {+ var project = AndroidProject.getProjectFile(this.root);+ var self = this;++ installOptions = installOptions || {};+ installOptions.variables = installOptions.variables || {};+ // Add PACKAGE_NAME variable into vars+ if (!installOptions.variables.PACKAGE_NAME) {+ installOptions.variables.PACKAGE_NAME = project.getPackageName();+ }- if (this.android_studio === true) {- installOptions.android_studio = true;+ return Promise.resolve().then(function () {+ return PluginManager.get(self.platform, self.locations, project).addPlugin(plugin, installOptions);+ }).then(function () {+ if (plugin.getFrameworks(this.platform).length === 0) return;+ selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');+ // This should pick the correct builder, not just get gradle+ require('./lib/builders/builders').getBuilder().prepBuildFiles();+ }.bind(this))+ // CB-11022 Return truthy value to prevent running prepare after+ .then(() => true);}- return Q().then(function () {- // CB-11964: Do a clean when installing the plugin code to get around- // the Gradle bug introduced by the Android Gradle Plugin Version 2.2- // TODO: Delete when the next version of Android Gradle plugin comes out- // Since clean doesn't just clean the build, it also wipes out www, we need- // to pass additional options.-- // Do some basic argument parsing- var opts = {};-- // Skip cleaning prepared files when not invoking via cordova CLI.- opts.noPrepare = true;-- if (!AndroidStudio.isAndroidStudioProject(self.root) && !project.isClean()) {- return self.clean(opts);+ /**+ * Removes an installed plugin from platform.+ *+ * Since method accepts PluginInfo instance as input parameter instead of plugin+ * id, caller shoud take care of managing/storing PluginInfo instances for+ * future uninstalls.+ *+ * @param {PluginInfo} plugin A PluginInfo instance that represents plugin+ * that will be installed.+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError instance.+ */+ removePlugin (plugin, uninstallOptions) {+ var project = AndroidProject.getProjectFile(this.root);++ if (uninstallOptions && uninstallOptions.usePlatformWww === true) {+ uninstallOptions.usePlatformWww = false;}- }).then(function () {- return PluginManager.get(self.platform, self.locations, project).addPlugin(plugin, installOptions);- }).then(function () {- if (plugin.getFrameworks(this.platform).length === 0) return;- selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');- // This should pick the correct builder, not just get gradle- require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();- }.bind(this))- // CB-11022 Return truthy value to prevent running prepare after- .thenResolve(true);-};-/**- * Removes an installed plugin from platform.- *- * Since method accepts PluginInfo instance as input parameter instead of plugin- * id, caller shoud take care of managing/storing PluginInfo instances for- * future uninstalls.- *- * @param {PluginInfo} plugin A PluginInfo instance that represents plugin- * that will be installed.- *- * @return {Promise} Return a promise either fulfilled, or rejected with- * CordovaError instance.- */-Api.prototype.removePlugin = function (plugin, uninstallOptions) {- var project = AndroidProject.getProjectFile(this.root);+ return PluginManager.get(this.platform, this.locations, project)+ .removePlugin(plugin, uninstallOptions)+ .then(function () {+ if (plugin.getFrameworks(this.platform).length === 0) return;- if (uninstallOptions && uninstallOptions.usePlatformWww === true && this.android_studio === true) {- uninstallOptions.usePlatformWww = false;- uninstallOptions.android_studio = true;+ selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');+ require('./lib/builders/builders').getBuilder().prepBuildFiles();+ }.bind(this))+ // CB-11022 Return truthy value to prevent running prepare after+ .then(() => true);}- return PluginManager.get(this.platform, this.locations, project)- .removePlugin(plugin, uninstallOptions)- .then(function () {- if (plugin.getFrameworks(this.platform).length === 0) return;-- selfEvents.emit('verbose', 'Updating build files since android plugin contained <framework>');- require('./lib/builders/builders').getBuilder(this.builder).prepBuildFiles();- }.bind(this))- // CB-11022 Return truthy value to prevent running prepare after- .thenResolve(true);-};--/**- * Builds an application package for current platform.- *- * @param {Object} buildOptions A build options. This object's structure is- * highly depends on platform's specific. The most common options are:- * @param {Boolean} buildOptions.debug Indicates that packages should be- * built with debug configuration. This is set to true by default unless the- * 'release' option is not specified.- * @param {Boolean} buildOptions.release Indicates that packages should be- * built with release configuration. If not set to true, debug configuration- * will be used.- * @param {Boolean} buildOptions.device Specifies that built app is intended- * to run on device- * @param {Boolean} buildOptions.emulator: Specifies that built app is- * intended to run on emulator- * @param {String} buildOptions.target Specifies the device id that will be- * used to run built application.- * @param {Boolean} buildOptions.nobuild Indicates that this should be a- * dry-run call, so no build artifacts will be produced.- * @param {String[]} buildOptions.archs Specifies chip architectures which- * app packages should be built for. List of valid architectures is depends on- * platform.- * @param {String} buildOptions.buildConfig The path to build configuration- * file. The format of this file is depends on platform.- * @param {String[]} buildOptions.argv Raw array of command-line arguments,- * passed to `build` command. The purpose of this property is to pass a- * platform-specific arguments, and eventually let platform define own- * arguments processing logic.- *- * @return {Promise<Object[]>} A promise either fulfilled with an array of build- * artifacts (application packages) if package was built successfully,- * or rejected with CordovaError. The resultant build artifact objects is not- * strictly typed and may conatin arbitrary set of fields as in sample below.- *- * {- * architecture: 'x86',- * buildType: 'debug',- * path: '/path/to/build',- * type: 'app'- * }- *- * The return value in most cases will contain only one item but in some cases- * there could be multiple items in output array, e.g. when multiple- * arhcitectures is specified.- */-Api.prototype.build = function (buildOptions) {- var self = this;- if (this.android_studio) {- buildOptions.studio = true;- }- return require('./lib/check_reqs').run().then(function () {- return require('./lib/build').run.call(self, buildOptions);- }).then(function (buildResults) {- // Cast build result to array of build artifacts- return buildResults.apkPaths.map(function (apkPath) {- return {- buildType: buildResults.buildType,- buildMethod: buildResults.buildMethod,- path: apkPath,- type: 'apk'- };+ /**+ * Builds an application package for current platform.+ *+ * @param {Object} buildOptions A build options. This object's structure is+ * highly depends on platform's specific. The most common options are:+ * @param {Boolean} buildOptions.debug Indicates that packages should be+ * built with debug configuration. This is set to true by default unless the+ * 'release' option is not specified.+ * @param {Boolean} buildOptions.release Indicates that packages should be+ * built with release configuration. If not set to true, debug configuration+ * will be used.+ * @param {Boolean} buildOptions.device Specifies that built app is intended+ * to run on device+ * @param {Boolean} buildOptions.emulator: Specifies that built app is+ * intended to run on emulator+ * @param {String} buildOptions.target Specifies the device id that will be+ * used to run built application.+ * @param {Boolean} buildOptions.nobuild Indicates that this should be a+ * dry-run call, so no build artifacts will be produced.+ * @param {String[]} buildOptions.archs Specifies chip architectures which+ * app packages should be built for. List of valid architectures is depends on+ * platform.+ * @param {String} buildOptions.buildConfig The path to build configuration+ * file. The format of this file is depends on platform.+ * @param {String[]} buildOptions.argv Raw array of command-line arguments,+ * passed to `build` command. The purpose of this property is to pass a+ * platform-specific arguments, and eventually let platform define own+ * arguments processing logic.+ *+ * @return {Promise<Object[]>} A promise either fulfilled with an array of build+ * artifacts (application packages) if package was built successfully,+ * or rejected with CordovaError. The resultant build artifact objects is not+ * strictly typed and may conatin arbitrary set of fields as in sample below.+ *+ * {+ * architecture: 'x86',+ * buildType: 'debug',+ * path: '/path/to/build',+ * type: 'app'+ * }+ *+ * The return value in most cases will contain only one item but in some cases+ * there could be multiple items in output array, e.g. when multiple+ * arhcitectures is specified.+ */+ build (buildOptions) {+ var self = this;++ return require('./lib/check_reqs').run().then(function () {+ return require('./lib/build').run.call(self, buildOptions);+ }).then(function (buildResults) {+ // Cast build result to array of build artifacts+ return buildResults.paths.map(function (apkPath) {+ return {+ buildType: buildResults.buildType,+ buildMethod: buildResults.buildMethod,+ path: apkPath,+ type: path.extname(apkPath).replace(/\./g, '')+ };+ });});- });-};+ }-/**- * Builds an application package for current platform and runs it on- * specified/default device. If no 'device'/'emulator'/'target' options are- * specified, then tries to run app on default device if connected, otherwise- * runs the app on emulator.- *- * @param {Object} runOptions An options object. The structure is the same- * as for build options.- *- * @return {Promise} A promise either fulfilled if package was built and ran- * successfully, or rejected with CordovaError.- */-Api.prototype.run = function (runOptions) {- var self = this;- return require('./lib/check_reqs').run().then(function () {- return require('./lib/run').run.call(self, runOptions);- });-};+ /**+ * Builds an application package for current platform and runs it on+ * specified/default device. If no 'device'/'emulator'/'target' options are+ * specified, then tries to run app on default device if connected, otherwise+ * runs the app on emulator.+ *+ * @param {Object} runOptions An options object. The structure is the same+ * as for build options.+ *+ * @return {Promise} A promise either fulfilled if package was built and ran+ * successfully, or rejected with CordovaError.+ */+ run (runOptions) {+ var self = this;+ return require('./lib/check_reqs').run().then(function () {+ return require('./lib/run').run.call(self, runOptions);+ });+ }-/**- * Cleans out the build artifacts from platform's directory, and also- * cleans out the platform www directory if called without options specified.- *- * @return {Promise} Return a promise either fulfilled, or rejected with- * CordovaError.- */-Api.prototype.clean = function (cleanOptions) {- var self = this;- if (this.android_studio) {+ /**+ * Cleans out the build artifacts from platform's directory, and also+ * cleans out the platform www directory if called without options specified.+ *+ * @return {Promise} Return a promise either fulfilled, or rejected with+ * CordovaError.+ */+ clean (cleanOptions) {+ var self = this;// This will lint, checking for null won'tif (typeof cleanOptions === 'undefined') {cleanOptions = {};}- cleanOptions.studio = true;++ return require('./lib/check_reqs').run().then(function () {+ return require('./lib/build').runClean.call(self, cleanOptions);+ }).then(function () {+ return require('./lib/prepare').clean.call(self, cleanOptions);+ });}- return require('./lib/check_reqs').run().then(function () {- return require('./lib/build').runClean.call(self, cleanOptions);- }).then(function () {- return require('./lib/prepare').clean.call(self, cleanOptions);- });-};+ /**+ * Performs a requirements check for current platform. Each platform defines its+ * own set of requirements, which should be resolved before platform can be+ * built successfully.+ *+ * @return {Promise<Requirement[]>} Promise, resolved with set of Requirement+ * objects for current platform.+ */+ requirements () {+ return require('./lib/check_reqs').check_all();+ }-/**- * Performs a requirements check for current platform. Each platform defines its- * own set of requirements, which should be resolved before platform can be- * built successfully.- *- * @return {Promise<Requirement[]>} Promise, resolved with set of Requirement- * objects for current platform.- */-Api.prototype.requirements = function () {- return require('./lib/check_reqs').check_all();-};+ /**+ * Installs platform to specified directory and creates a platform project.+ *+ * @param {String} destination Destination directory, where insatll platform to+ * @param {ConfigParser} [config] ConfgiParser instance, used to retrieve+ * project creation options, such as package id and project name.+ * @param {Object} [options] An options object. The most common options are:+ * @param {String} [options.customTemplate] A path to custom template, that+ * should override the default one from platform.+ * @param {Boolean} [options.link] Flag that indicates that platform's+ * sources will be linked to installed platform instead of copying.+ * @param {EventEmitter} [events] An EventEmitter instance that will be used for+ * logging purposes. If no EventEmitter provided, all events will be logged to+ * console+ *+ * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi+ * instance or rejected with CordovaError.+ */+ static createPlatform (destination, config, options, events) {+ events = setupEvents(events);+ var result;+ try {+ result = require('../../lib/create').create(destination, config, options, events).then(function (destination) {+ return new Api(PLATFORM, destination, events);+ });+ } catch (e) {+ events.emit('error', 'createPlatform is not callable from the android project API.');+ throw (e);+ }+ return result;+ }++ /**+ * Updates already installed platform.+ *+ * @param {String} destination Destination directory, where platform installed+ * @param {Object} [options] An options object. The most common options are:+ * @param {String} [options.customTemplate] A path to custom template, that+ * should override the default one from platform.+ * @param {Boolean} [options.link] Flag that indicates that platform's+ * sources will be linked to installed platform instead of copying.+ * @param {EventEmitter} [events] An EventEmitter instance that will be used for+ * logging purposes. If no EventEmitter provided, all events will be logged to+ * console+ *+ * @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi+ * instance or rejected with CordovaError.+ */+ static updatePlatform (destination, options, events) {+ events = setupEvents(events);+ var result;+ try {+ result = require('../../lib/create').update(destination, options, events).then(function (destination) {+ return new Api(PLATFORM, destination, events);+ });+ } catch (e) {+ events.emit('error', 'updatePlatform is not callable from the android project API, you will need to do this manually.');+ throw (e);+ }+ return result;+ }++ static version () {+ return VERSION;+ }+}module.exports = Api;diff --git a/cordova/platforms/android/cordova/android_sdk_version b/cordova/platforms/android/cordova/android_sdk_versionindex 34ed28fea..c4aa8b865 100755--- a/cordova/platforms/android/cordova/android_sdk_version+++ b/cordova/platforms/android/cordova/android_sdk_version@@ -21,9 +21,7 @@var android_sdk = require('./lib/android_sdk');-android_sdk.print_newest_available_sdk_target().done(null, function(err) {+android_sdk.print_newest_available_sdk_target().catch(err => {console.error(err);process.exit(2);});--diff --git a/cordova/platforms/android/cordova/android_sdk_version.bat b/cordova/platforms/android/cordova/android_sdk_version.batindex a6bc10435..65173a8f8 100644--- a/cordova/platforms/android/cordova/android_sdk_version.bat+++ b/cordova/platforms/android/cordova/android_sdk_version.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYdiff --git a/cordova/platforms/android/cordova/build b/cordova/platforms/android/cordova/buildindex 222e84a06..b4e160ebe 100755--- a/cordova/platforms/android/cordova/build+++ b/cordova/platforms/android/cordova/build@@ -19,24 +19,25 @@under the License.*/-var args = process.argv;+var args = process.argv;var Api = require('./Api');var nopt = require('nopt');var path = require('path');// Support basic help commands-if(['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0)+if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(args[2]) >= 0) {require('./lib/build').help();+}// Do some basic argument parsingvar buildOpts = nopt({- 'verbose' : Boolean,- 'silent' : Boolean,- 'debug' : Boolean,- 'release' : Boolean,- 'nobuild': Boolean,- 'buildConfig' : path-}, { 'd' : '--verbose' });+ verbose: Boolean,+ silent: Boolean,+ debug: Boolean,+ release: Boolean,+ nobuild: Boolean,+ buildConfig: path+}, { d: '--verbose' });// Make buildOptions compatible with PlatformApi build method specbuildOpts.argv = buildOpts.argv.original;@@ -44,7 +45,7 @@ buildOpts.argv = buildOpts.argv.original;require('./loggingHelper').adjustLoggerLevel(buildOpts);new Api().build(buildOpts)-.catch(function(err) {- console.error(err.stack);- process.exit(2);-});+ .catch(function (err) {+ console.error(err.stack);+ process.exit(2);+ });diff --git a/cordova/platforms/android/cordova/check_reqs b/cordova/platforms/android/cordova/check_reqsindex 372a3830a..faed86f10 100755--- a/cordova/platforms/android/cordova/check_reqs+++ b/cordova/platforms/android/cordova/check_reqs@@ -21,10 +21,11 @@var check_reqs = require('./lib/check_reqs');-check_reqs.run().done(- function success() {+check_reqs.run().then(+ function success () {console.log('Looks like your environment fully supports cordova-android development!');- }, function fail(err) {+ },+ function fail (err) {console.log(err);process.exit(2);}diff --git a/cordova/platforms/android/cordova/check_reqs.bat b/cordova/platforms/android/cordova/check_reqs.batindex 846dfa1f4..84d66ad20 100644--- a/cordova/platforms/android/cordova/check_reqs.bat+++ b/cordova/platforms/android/cordova/check_reqs.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYdiff --git a/cordova/platforms/android/cordova/clean b/cordova/platforms/android/cordova/cleanindex 22065cc54..5173d14b2 100755--- a/cordova/platforms/android/cordova/clean+++ b/cordova/platforms/android/cordova/clean@@ -20,11 +20,11 @@*/var Api = require('./Api');-var path = require('path');+var path = require('path');var nopt = require('nopt');// Support basic help commands-if(['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {+if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {console.log('Usage: ' + path.relative(process.cwd(), process.argv[1]));console.log('Cleans the project directory.');process.exit(0);@@ -32,9 +32,9 @@ if(['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=// Do some basic argument parsingvar opts = nopt({- 'verbose' : Boolean,- 'silent' : Boolean-}, { 'd' : '--verbose' });+ verbose: Boolean,+ silent: Boolean+}, { d: '--verbose' });// Make buildOptions compatible with PlatformApi clean method specopts.argv = opts.argv.original;@@ -45,7 +45,7 @@ opts.noPrepare = true;require('./loggingHelper').adjustLoggerLevel(opts);new Api().clean(opts)-.catch(function(err) {- console.error(err.stack);- process.exit(2);-});+ .catch(function (err) {+ console.error(err.stack);+ process.exit(2);+ });diff --git a/cordova/platforms/android/cordova/lib/Adb.js b/cordova/platforms/android/cordova/lib/Adb.jsindex 038c67c09..042a0c2a3 100644--- a/cordova/platforms/android/cordova/lib/Adb.js+++ b/cordova/platforms/android/cordova/lib/Adb.js@@ -17,10 +17,9 @@under the License.*/-var Q = require('q');var os = require('os');+var execa = require('execa');var events = require('cordova-common').events;-var spawn = require('cordova-common').superspawn.spawn;var CordovaError = require('cordova-common').CordovaError;var Adb = {};@@ -44,7 +43,7 @@ function isEmulator (line) {* devices/emulators*/Adb.devices = function (opts) {- return spawn('adb', ['devices'], {cwd: os.tmpdir()}).then(function (output) {+ return execa('adb', ['devices'], { cwd: os.tmpdir() }).then(({ stdout: output }) => {return output.split('\n').filter(function (line) {// Filter out either real devices or emulators, depending on optionsreturn (line && opts && opts.emulators) ? isEmulator(line) : isDevice(line);@@ -58,7 +57,7 @@ Adb.install = function (target, packagePath, opts) {events.emit('verbose', 'Installing apk ' + packagePath + ' on target ' + target + '...');var args = ['-s', target, 'install'];if (opts && opts.replace) args.push('-r');- return spawn('adb', args.concat(packagePath), {cwd: os.tmpdir()}).then(function (output) {+ return execa('adb', args.concat(packagePath), { cwd: os.tmpdir() }).then(({ stdout: output }) => {// 'adb install' seems to always returns no error, even if installation fails// so we catching output to detect installation failureif (output.match(/Failure/)) {@@ -70,31 +69,30 @@ Adb.install = function (target, packagePath, opts) {'\nEither uninstall an app or increment the versionCode.';}- return Q.reject(new CordovaError('Failed to install apk to device: ' + output));+ return Promise.reject(new CordovaError('Failed to install apk to device: ' + output));}});};Adb.uninstall = function (target, packageId) {events.emit('verbose', 'Uninstalling package ' + packageId + ' from target ' + target + '...');- return spawn('adb', ['-s', target, 'uninstall', packageId], {cwd: os.tmpdir()});+ return execa('adb', ['-s', target, 'uninstall', packageId], { cwd: os.tmpdir() }).then(({ stdout }) => stdout);};Adb.shell = function (target, shellCommand) {events.emit('verbose', 'Running adb shell command "' + shellCommand + '" on target ' + target + '...');var args = ['-s', target, 'shell'];shellCommand = shellCommand.split(/\s+/);- return spawn('adb', args.concat(shellCommand), {cwd: os.tmpdir()}).catch(function (output) {- return Q.reject(new CordovaError('Failed to execute shell command "' +- shellCommand + '"" on device: ' + output));- });+ return execa('adb', args.concat(shellCommand), { cwd: os.tmpdir() })+ .then(({ stdout }) => stdout)+ .catch(error => Promise.reject(new CordovaError(`Failed to execute shell command "${shellCommand}" on device: ${error}`)));};Adb.start = function (target, activityName) {events.emit('verbose', 'Starting application "' + activityName + '" on target ' + target + '...');- return Adb.shell(target, 'am start -W -a android.intent.action.MAIN -n' + activityName).catch(function (output) {- return Q.reject(new CordovaError('Failed to start application "' +- activityName + '"" on device: ' + output));+ return Adb.shell(target, 'am start -W -a android.intent.action.MAIN -n' + activityName).catch((error) => {+ return Promise.reject(new CordovaError('Failed to start application "' ++ activityName + '"" on device: ' + error));});};diff --git a/cordova/platforms/android/cordova/lib/AndroidManifest.js b/cordova/platforms/android/cordova/lib/AndroidManifest.jsindex 5b7077ae5..be4fecc08 100644--- a/cordova/platforms/android/cordova/lib/AndroidManifest.js+++ b/cordova/platforms/android/cordova/lib/AndroidManifest.js@@ -18,143 +18,111 @@*/var fs = require('fs');-var et = require('elementtree');var xml = require('cordova-common').xmlHelpers;var DEFAULT_ORIENTATION = 'default';/** Wraps an AndroidManifest file */-function AndroidManifest (path) {- this.path = path;- this.doc = xml.parseElementtreeSync(path);- if (this.doc.getroot().tag !== 'manifest') {- throw new Error('AndroidManifest at ' + path + ' has incorrect root node name (expected "manifest")');- }-}--AndroidManifest.prototype.getVersionName = function () {- return this.doc.getroot().attrib['android:versionName'];-};--AndroidManifest.prototype.setVersionName = function (versionName) {- this.doc.getroot().attrib['android:versionName'] = versionName;- return this;-};--AndroidManifest.prototype.getVersionCode = function () {- return this.doc.getroot().attrib['android:versionCode'];-};--AndroidManifest.prototype.setVersionCode = function (versionCode) {- this.doc.getroot().attrib['android:versionCode'] = versionCode;- return this;-};--AndroidManifest.prototype.getPackageId = function () {- /* jshint -W069 */- return this.doc.getroot().attrib['package'];- /* jshint +W069 */-};--AndroidManifest.prototype.setPackageId = function (pkgId) {- /* jshint -W069 */- this.doc.getroot().attrib['package'] = pkgId;- /* jshint +W069 */- return this;-};--AndroidManifest.prototype.getActivity = function () {- var activity = this.doc.getroot().find('./application/activity');- return {- getName: function () {- return activity.attrib['android:name'];- },- setName: function (name) {- if (!name) {- delete activity.attrib['android:name'];- } else {- activity.attrib['android:name'] = name;- }- return this;- },- getOrientation: function () {- return activity.attrib['android:screenOrientation'];- },- setOrientation: function (orientation) {- if (!orientation || orientation.toLowerCase() === DEFAULT_ORIENTATION) {- delete activity.attrib['android:screenOrientation'];- } else {- activity.attrib['android:screenOrientation'] = orientation;- }- return this;- },- getLaunchMode: function () {- return activity.attrib['android:launchMode'];- },- setLaunchMode: function (launchMode) {- if (!launchMode) {- delete activity.attrib['android:launchMode'];- } else {- activity.attrib['android:launchMode'] = launchMode;- }- return this;+class AndroidManifest {+ constructor (path) {+ this.path = path;+ this.doc = xml.parseElementtreeSync(path);+ if (this.doc.getroot().tag !== 'manifest') {+ throw new Error('AndroidManifest at ' + path + ' has incorrect root node name (expected "manifest")');}- };-};+ }-['minSdkVersion', 'maxSdkVersion', 'targetSdkVersion'].forEach(function (sdkPrefName) {- // Copy variable reference to avoid closure issues- var prefName = sdkPrefName;+ getVersionName () {+ return this.doc.getroot().attrib['android:versionName'];+ }- AndroidManifest.prototype['get' + capitalize(prefName)] = function () {- var usesSdk = this.doc.getroot().find('./uses-sdk');- return usesSdk && usesSdk.attrib['android:' + prefName];- };+ setVersionName (versionName) {+ this.doc.getroot().attrib['android:versionName'] = versionName;+ return this;+ }- AndroidManifest.prototype['set' + capitalize(prefName)] = function (prefValue) {- var usesSdk = this.doc.getroot().find('./uses-sdk');+ getVersionCode () {+ return this.doc.getroot().attrib['android:versionCode'];+ }- if (!usesSdk && prefValue) { // if there is no required uses-sdk element, we should create it first- usesSdk = new et.Element('uses-sdk');- this.doc.getroot().append(usesSdk);- }+ setVersionCode (versionCode) {+ this.doc.getroot().attrib['android:versionCode'] = versionCode;+ return this;+ }- if (prefValue) {- usesSdk.attrib['android:' + prefName] = prefValue;- }+ getPackageId () {+ return this.doc.getroot().attrib.package;+ }+ setPackageId (pkgId) {+ this.doc.getroot().attrib.package = pkgId;return this;- };-});--AndroidManifest.prototype.getDebuggable = function () {- return this.doc.getroot().find('./application').attrib['android:debuggable'] === 'true';-};--AndroidManifest.prototype.setDebuggable = function (value) {- var application = this.doc.getroot().find('./application');- if (value) {- application.attrib['android:debuggable'] = 'true';- } else {- // The default value is "false", so we can remove attribute at all.- delete application.attrib['android:debuggable'];}- return this;-};-/**- * Writes manifest to disk syncronously. If filename is specified, then manifest- * will be written to that file- *- * @param {String} [destPath] File to write manifest to. If omitted,- * manifest will be written to file it has been read from.- */-AndroidManifest.prototype.write = function (destPath) {- fs.writeFileSync(destPath || this.path, this.doc.write({indent: 4}), 'utf-8');-};+ getActivity () {+ var activity = this.doc.getroot().find('./application/activity');+ return {+ getName: function () {+ return activity.attrib['android:name'];+ },+ setName: function (name) {+ if (!name) {+ delete activity.attrib['android:name'];+ } else {+ activity.attrib['android:name'] = name;+ }+ return this;+ },+ getOrientation: function () {+ return activity.attrib['android:screenOrientation'];+ },+ setOrientation: function (orientation) {+ if (!orientation || orientation.toLowerCase() === DEFAULT_ORIENTATION) {+ delete activity.attrib['android:screenOrientation'];+ } else {+ activity.attrib['android:screenOrientation'] = orientation;+ }+ return this;+ },+ getLaunchMode: function () {+ return activity.attrib['android:launchMode'];+ },+ setLaunchMode: function (launchMode) {+ if (!launchMode) {+ delete activity.attrib['android:launchMode'];+ } else {+ activity.attrib['android:launchMode'] = launchMode;+ }+ return this;+ }+ };+ }-module.exports = AndroidManifest;+ getDebuggable () {+ return this.doc.getroot().find('./application').attrib['android:debuggable'] === 'true';+ }-function capitalize (str) {- return str.charAt(0).toUpperCase() + str.slice(1);+ setDebuggable (value) {+ var application = this.doc.getroot().find('./application');+ if (value) {+ application.attrib['android:debuggable'] = 'true';+ } else {+ // The default value is "false", so we can remove attribute at all.+ delete application.attrib['android:debuggable'];+ }+ return this;+ }++ /**+ * Writes manifest to disk syncronously. If filename is specified, then manifest+ * will be written to that file+ *+ * @param {String} [destPath] File to write manifest to. If omitted,+ * manifest will be written to file it has been read from.+ */+ write (destPath) {+ fs.writeFileSync(destPath || this.path, this.doc.write({ indent: 4 }), 'utf-8');+ }}++module.exports = AndroidManifest;diff --git a/cordova/platforms/android/cordova/lib/AndroidProject.js b/cordova/platforms/android/cordova/lib/AndroidProject.jsindex bf55cad1c..5d1c3c32d 100644--- a/cordova/platforms/android/cordova/lib/AndroidProject.js+++ b/cordova/platforms/android/cordova/lib/AndroidProject.js@@ -21,7 +21,6 @@ var fs = require('fs');var path = require('path');var properties_parser = require('properties-parser');var AndroidManifest = require('./AndroidManifest');-var AndroidStudio = require('./AndroidStudio');var pluginHandlers = require('./pluginHandlers');var projectFileCache = {};@@ -56,154 +55,148 @@ function getRelativeLibraryPath (parentDir, subDir) {return (path.sep === '\\') ? libraryPath.replace(/\\/g, '/') : libraryPath;}-function AndroidProject (projectDir) {- this._propertiesEditors = {};- this._subProjectDirs = {};- this._dirty = false;- this.projectDir = projectDir;- this.platformWww = path.join(this.projectDir, 'platform_www');- this.www = path.join(this.projectDir, 'assets/www');- if (AndroidStudio.isAndroidStudioProject(projectDir) === true) {+class AndroidProject {+ constructor (projectDir) {+ this._propertiesEditors = {};+ this._subProjectDirs = {};+ this._dirty = false;+ this.projectDir = projectDir;+ this.platformWww = path.join(this.projectDir, 'platform_www');this.www = path.join(this.projectDir, 'app/src/main/assets/www');}-}-AndroidProject.getProjectFile = function (projectDir) {- if (!projectFileCache[projectDir]) {- projectFileCache[projectDir] = new AndroidProject(projectDir);+ /**+ * Reads the package name out of the Android Manifest file+ *+ * @param {String} projectDir The absolute path to the directory containing the project+ * @return {String} The name of the package+ */+ getPackageName () {+ var manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');+ return new AndroidManifest(manifestPath).getPackageId();}- return projectFileCache[projectDir];-};--AndroidProject.purgeCache = function (projectDir) {- if (projectDir) {- delete projectFileCache[projectDir];- } else {- projectFileCache = {};+ getCustomSubprojectRelativeDir (plugin_id, src) {+ // All custom subprojects are prefixed with the last portion of the package id.+ // This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name.+ var packageName = this.getPackageName();+ var lastDotIndex = packageName.lastIndexOf('.');+ var prefix = packageName.substring(lastDotIndex + 1);+ var subRelativeDir = path.join(plugin_id, prefix + '-' + path.basename(src));+ return subRelativeDir;}-};-/**- * Reads the package name out of the Android Manifest file- *- * @param {String} projectDir The absolute path to the directory containing the project- *- * @return {String} The name of the package- */-AndroidProject.prototype.getPackageName = function () {- var manifestPath = path.join(this.projectDir, 'AndroidManifest.xml');- if (AndroidStudio.isAndroidStudioProject(this.projectDir) === true) {- manifestPath = path.join(this.projectDir, 'app/src/main/AndroidManifest.xml');- }- return new AndroidManifest(manifestPath).getPackageId();-};--AndroidProject.prototype.getCustomSubprojectRelativeDir = function (plugin_id, src) {- // All custom subprojects are prefixed with the last portion of the package id.- // This is to avoid collisions when opening multiple projects in Eclipse that have subprojects with the same name.- var packageName = this.getPackageName();- var lastDotIndex = packageName.lastIndexOf('.');- var prefix = packageName.substring(lastDotIndex + 1);- var subRelativeDir = path.join(plugin_id, prefix + '-' + path.basename(src));- return subRelativeDir;-};--AndroidProject.prototype.addSubProject = function (parentDir, subDir) {- var parentProjectFile = path.resolve(parentDir, 'project.properties');- var subProjectFile = path.resolve(subDir, 'project.properties');- var parentProperties = this._getPropertiesFile(parentProjectFile);- // TODO: Setting the target needs to happen only for pre-3.7.0 projects- if (fs.existsSync(subProjectFile)) {- var subProperties = this._getPropertiesFile(subProjectFile);- subProperties.set('target', parentProperties.get('target'));- subProperties.dirty = true;- this._subProjectDirs[subDir] = true;- }- addToPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));-- this._dirty = true;-};--AndroidProject.prototype.removeSubProject = function (parentDir, subDir) {- var parentProjectFile = path.resolve(parentDir, 'project.properties');- var parentProperties = this._getPropertiesFile(parentProjectFile);- removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));- delete this._subProjectDirs[subDir];- this._dirty = true;-};--AndroidProject.prototype.addGradleReference = function (parentDir, subDir) {- var parentProjectFile = path.resolve(parentDir, 'project.properties');- var parentProperties = this._getPropertiesFile(parentProjectFile);- addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));- this._dirty = true;-};--AndroidProject.prototype.removeGradleReference = function (parentDir, subDir) {- var parentProjectFile = path.resolve(parentDir, 'project.properties');- var parentProperties = this._getPropertiesFile(parentProjectFile);- removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));- this._dirty = true;-};--AndroidProject.prototype.addSystemLibrary = function (parentDir, value) {- var parentProjectFile = path.resolve(parentDir, 'project.properties');- var parentProperties = this._getPropertiesFile(parentProjectFile);- addToPropertyList(parentProperties, 'cordova.system.library', value);- this._dirty = true;-};--AndroidProject.prototype.removeSystemLibrary = function (parentDir, value) {- var parentProjectFile = path.resolve(parentDir, 'project.properties');- var parentProperties = this._getPropertiesFile(parentProjectFile);- removeFromPropertyList(parentProperties, 'cordova.system.library', value);- this._dirty = true;-};--AndroidProject.prototype.write = function () {- if (!this._dirty) {- return;- }- this._dirty = false;-- for (var filename in this._propertiesEditors) {- var editor = this._propertiesEditors[filename];- if (editor.dirty) {- fs.writeFileSync(filename, editor.toString());- editor.dirty = false;+ addSubProject (parentDir, subDir) {+ var parentProjectFile = path.resolve(parentDir, 'project.properties');+ var subProjectFile = path.resolve(subDir, 'project.properties');+ var parentProperties = this._getPropertiesFile(parentProjectFile);+ // TODO: Setting the target needs to happen only for pre-3.7.0 projects+ if (fs.existsSync(subProjectFile)) {+ var subProperties = this._getPropertiesFile(subProjectFile);+ subProperties.set('target', parentProperties.get('target'));+ subProperties.dirty = true;+ this._subProjectDirs[subDir] = true;}+ addToPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));++ this._dirty = true;}-};-AndroidProject.prototype._getPropertiesFile = function (filename) {- if (!this._propertiesEditors[filename]) {- if (fs.existsSync(filename)) {- this._propertiesEditors[filename] = properties_parser.createEditor(filename);- } else {- this._propertiesEditors[filename] = properties_parser.createEditor();+ removeSubProject (parentDir, subDir) {+ var parentProjectFile = path.resolve(parentDir, 'project.properties');+ var parentProperties = this._getPropertiesFile(parentProjectFile);+ removeFromPropertyList(parentProperties, 'android.library.reference', getRelativeLibraryPath(parentDir, subDir));+ delete this._subProjectDirs[subDir];+ this._dirty = true;+ }++ addGradleReference (parentDir, subDir) {+ var parentProjectFile = path.resolve(parentDir, 'project.properties');+ var parentProperties = this._getPropertiesFile(parentProjectFile);+ addToPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));+ this._dirty = true;+ }++ removeGradleReference (parentDir, subDir) {+ var parentProjectFile = path.resolve(parentDir, 'project.properties');+ var parentProperties = this._getPropertiesFile(parentProjectFile);+ removeFromPropertyList(parentProperties, 'cordova.gradle.include', getRelativeLibraryPath(parentDir, subDir));+ this._dirty = true;+ }++ addSystemLibrary (parentDir, value) {+ var parentProjectFile = path.resolve(parentDir, 'project.properties');+ var parentProperties = this._getPropertiesFile(parentProjectFile);+ addToPropertyList(parentProperties, 'cordova.system.library', value);+ this._dirty = true;+ }++ removeSystemLibrary (parentDir, value) {+ var parentProjectFile = path.resolve(parentDir, 'project.properties');+ var parentProperties = this._getPropertiesFile(parentProjectFile);+ removeFromPropertyList(parentProperties, 'cordova.system.library', value);+ this._dirty = true;+ }++ write () {+ if (!this._dirty) {+ return;}+ this._dirty = false;++ for (var filename in this._propertiesEditors) {+ var editor = this._propertiesEditors[filename];+ if (editor.dirty) {+ fs.writeFileSync(filename, editor.toString());+ editor.dirty = false;+ }+ }+ }++ getInstaller (type) {+ return pluginHandlers.getInstaller(type);+ }++ getUninstaller (type) {+ return pluginHandlers.getUninstaller(type);+ }++ /*+ * This checks if an Android project is clean or has old build artifacts+ */+ isClean () {+ var build_path = path.join(this.projectDir, 'build');+ // If the build directory doesn't exist, it's clean+ return !(fs.existsSync(build_path));}- return this._propertiesEditors[filename];-};+ _getPropertiesFile (filename) {+ if (!this._propertiesEditors[filename]) {+ if (fs.existsSync(filename)) {+ this._propertiesEditors[filename] = properties_parser.createEditor(filename);+ } else {+ this._propertiesEditors[filename] = properties_parser.createEditor();+ }+ }-AndroidProject.prototype.getInstaller = function (type) {- return pluginHandlers.getInstaller(type);-};+ return this._propertiesEditors[filename];+ }-AndroidProject.prototype.getUninstaller = function (type) {- return pluginHandlers.getUninstaller(type);-};+ static getProjectFile (projectDir) {+ if (!projectFileCache[projectDir]) {+ projectFileCache[projectDir] = new AndroidProject(projectDir);+ }-/*- * This checks if an Android project is clean or has old build artifacts- */+ return projectFileCache[projectDir];+ }-AndroidProject.prototype.isClean = function () {- var build_path = path.join(this.projectDir, 'build');- // If the build directory doesn't exist, it's clean- return !(fs.existsSync(build_path));-};+ static purgeCache (projectDir) {+ if (projectDir) {+ delete projectFileCache[projectDir];+ } else {+ projectFileCache = {};+ }+ }+}module.exports = AndroidProject;diff --git a/cordova/platforms/android/cordova/lib/AndroidStudio.js b/cordova/platforms/android/cordova/lib/AndroidStudio.jsdeleted file mode 100644index 68d4d8f6c..000000000--- a/cordova/platforms/android/cordova/lib/AndroidStudio.js+++ /dev/null@@ -1,11 +0,0 @@-/*- * This is a simple routine that checks if project is an Android Studio Project- *- * @param {String} root Root folder of the project- */--/* jshint esnext: false */--module.exports.isAndroidStudioProject = function isAndroidStudioProject (root) {- return true;-};diff --git a/cordova/platforms/android/cordova/lib/PackageType.js b/cordova/platforms/android/cordova/lib/PackageType.jsnew file mode 100644index 000000000..fd129f134--- /dev/null+++ b/cordova/platforms/android/cordova/lib/PackageType.js@@ -0,0 +1,25 @@+/**+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++const PackageType = {+ APK: 'apk',+ BUNDLE: 'bundle'+};++module.exports = PackageType;diff --git a/cordova/platforms/android/cordova/lib/android_sdk.js b/cordova/platforms/android/cordova/lib/android_sdk.jsindex 148f9f3db..963d7f1da 100755--- a/cordova/platforms/android/cordova/lib/android_sdk.js+++ b/cordova/platforms/android/cordova/lib/android_sdk.js@@ -17,8 +17,7 @@under the License.*/-var Q = require('q');-var superspawn = require('cordova-common').superspawn;+const execa = require('execa');var suffix_number_regex = /(\d+)$/;// Used for sorting Android targets, example strings to sort:@@ -30,17 +29,14 @@ var suffix_number_regex = /(\d+)$/;// the number at the end, the more recent the target, the closer to the// start of the array.function sort_by_largest_numerical_suffix (a, b) {- var suffix_a = a.match(suffix_number_regex);- var suffix_b = b.match(suffix_number_regex);- if (suffix_a && suffix_b) {- // If the two targets being compared have suffixes, return less than- // zero, or greater than zero, based on which suffix is larger.- return (parseInt(suffix_a[1]) > parseInt(suffix_b[1]) ? -1 : 1);- } else {- // If no suffix numbers were detected, leave the order as-is between- // elements a and b.- return 0;- }+ let suffix_a = a.match(suffix_number_regex);+ let suffix_b = b.match(suffix_number_regex);+ // If no number is detected (eg: preview version like android-R),+ // designate a suffix of 0 so it gets moved to the end+ suffix_a = suffix_a || ['0', '0'];+ suffix_b = suffix_b || ['0', '0'];+ // Return < zero, or > zero, based on which suffix is larger.+ return (parseInt(suffix_a[1]) > parseInt(suffix_b[1]) ? -1 : 1);}module.exports.print_newest_available_sdk_target = function () {@@ -50,6 +46,8 @@ module.exports.print_newest_available_sdk_target = function () {});};+// Versions should not be represented as float, so we disable quote-props here+/* eslint-disable quote-props */module.exports.version_string_to_api_level = {'4.0': 14,'4.0.3': 15,@@ -65,6 +63,7 @@ module.exports.version_string_to_api_level = {'7.1.1': 25,'8.0': 26};+/* eslint-enable quote-props */function parse_targets (output) {var target_out = output.split('\n');@@ -78,11 +77,11 @@ function parse_targets (output) {}module.exports.list_targets_with_android = function () {- return superspawn.spawn('android', ['list', 'target']).then(parse_targets);+ return execa('android', ['list', 'target']).then(result => parse_targets(result.stdout));};module.exports.list_targets_with_avdmanager = function () {- return superspawn.spawn('avdmanager', ['list', 'target']).then(parse_targets);+ return execa('avdmanager', ['list', 'target']).then(result => parse_targets(result.stdout));};module.exports.list_targets = function () {@@ -95,7 +94,7 @@ module.exports.list_targets = function () {} else throw err;}).then(function (targets) {if (targets.length === 0) {- return Q.reject(new Error('No android targets (SDKs) installed!'));+ return Promise.reject(new Error('No android targets (SDKs) installed!'));}return targets;});diff --git a/cordova/platforms/android/cordova/lib/build.js b/cordova/platforms/android/cordova/lib/build.jsindex e33cfae08..e199239db 100644--- a/cordova/platforms/android/cordova/lib/build.js+++ b/cordova/platforms/android/cordova/lib/build.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,7 +17,6 @@under the License.*/-var Q = require('q');var path = require('path');var fs = require('fs');var nopt = require('nopt');@@ -28,48 +25,40 @@ var Adb = require('./Adb');var builders = require('./builders/builders');var events = require('cordova-common').events;-var spawn = require('cordova-common').superspawn.spawn;+const execa = require('execa');var CordovaError = require('cordova-common').CordovaError;+var PackageType = require('./PackageType');+module.exports.parseBuildOptions = parseOpts;function parseOpts (options, resolvedTarget, projectRoot) {options = options || {};options.argv = nopt({- gradle: Boolean,- studio: Boolean,prepenv: Boolean,versionCode: String,minSdkVersion: String,+ maxSdkVersion: String,+ targetSdkVersion: String,gradleArg: [String, Array],keystore: path,alias: String,storePassword: String,password: String,- keystoreType: String+ keystoreType: String,+ packageType: String}, {}, options.argv, 0);// Android Studio Build method is the defaultvar ret = {buildType: options.release ? 'release' : 'debug',- buildMethod: process.env.ANDROID_BUILD || 'studio',prepEnv: options.argv.prepenv,arch: resolvedTarget && resolvedTarget.arch,extraArgs: []};- if (options.argv.gradle || options.argv.studio) {- ret.buildMethod = options.argv.studio ? 'studio' : 'gradle';- }-- // This comes from cordova/run- if (options.studio) ret.buildMethod = 'studio';- if (options.gradle) ret.buildMethod = 'gradle';-- if (options.nobuild) ret.buildMethod = 'none';-if (options.argv.versionCode) { ret.extraArgs.push('-PcdvVersionCode=' + options.argv.versionCode); }-if (options.argv.minSdkVersion) { ret.extraArgs.push('-PcdvMinSdkVersion=' + options.argv.minSdkVersion); }-+ if (options.argv.maxSdkVersion) { ret.extraArgs.push('-PcdvMaxSdkVersion=' + options.argv.maxSdkVersion); }+ if (options.argv.targetSdkVersion) { ret.extraArgs.push('-PcdvTargetSdkVersion=' + options.argv.targetSdkVersion); }if (options.argv.gradleArg) {ret.extraArgs = ret.extraArgs.concat(options.argv.gradleArg);}@@ -78,14 +67,14 @@ function parseOpts (options, resolvedTarget, projectRoot) {if (options.argv.keystore) { packageArgs.keystore = path.relative(projectRoot, path.resolve(options.argv.keystore)); }- ['alias', 'storePassword', 'password', 'keystoreType'].forEach(function (flagName) {+ ['alias', 'storePassword', 'password', 'keystoreType', 'packageType'].forEach(function (flagName) {if (options.argv[flagName]) { packageArgs[flagName] = options.argv[flagName]; }});var buildConfig = options.buildConfig;// If some values are not specified as command line arguments - use build config to supplement them.- // Command line arguemnts have precedence over build config.+ // Command line arguments have precedence over build config.if (buildConfig) {if (!fs.existsSync(buildConfig)) {throw new Error('Specified build config file does not exist: ' + buildConfig);@@ -103,7 +92,7 @@ function parseOpts (options, resolvedTarget, projectRoot) {events.emit('log', 'Reading the keystore from: ' + packageArgs.keystore);}- ['alias', 'storePassword', 'password', 'keystoreType'].forEach(function (key) {+ ['alias', 'storePassword', 'password', 'keystoreType', 'packageType'].forEach(function (key) {packageArgs[key] = packageArgs[key] || androidInfo[key];});}@@ -115,11 +104,38 @@ function parseOpts (options, resolvedTarget, projectRoot) {}if (!ret.packageInfo) {- if (Object.keys(packageArgs).length > 0) {+ // The following loop is to decide whether to print a warning about generating a signed archive+ // We only want to produce a warning if they are using a config property that is related to signing, but+ // missing the required properties for signing. We don't want to produce a warning if they are simply+ // using a build property that isn't related to signing, such as --packageType+ let shouldWarn = false;+ const signingKeys = ['keystore', 'alias', 'storePassword', 'password', 'keystoreType'];++ for (const key in packageArgs) {+ if (!shouldWarn && signingKeys.indexOf(key) > -1) {+ // If we enter this condition, we have a key used for signing a build,+ // but we are missing some required signing properties+ shouldWarn = true;+ }+ }++ if (shouldWarn) {events.emit('warn', '\'keystore\' and \'alias\' need to be specified to generate a signed archive.');}}+ if (packageArgs.packageType) {+ const VALID_PACKAGE_TYPES = [PackageType.APK, PackageType.BUNDLE];+ if (VALID_PACKAGE_TYPES.indexOf(packageArgs.packageType) === -1) {+ events.emit('warn', '"' + packageArgs.packageType + '" is an invalid packageType. Valid values are: ' + VALID_PACKAGE_TYPES.join(', ') + '\nDefaulting packageType to ' + PackageType.APK);+ ret.packageType = PackageType.APK;+ } else {+ ret.packageType = packageArgs.packageType;+ }+ } else {+ ret.packageType = PackageType.APK;+ }+return ret;}@@ -129,7 +145,8 @@ function parseOpts (options, resolvedTarget, projectRoot) {*/module.exports.runClean = function (options) {var opts = parseOpts(options, null, this.root);- var builder = builders.getBuilder(opts.buildMethod);+ var builder = builders.getBuilder();+return builder.prepEnv(opts).then(function () {return builder.clean(opts);});@@ -149,20 +166,26 @@ module.exports.runClean = function (options) {*/module.exports.run = function (options, optResolvedTarget) {var opts = parseOpts(options, optResolvedTarget, this.root);- console.log(opts.buildMethod);- var builder = builders.getBuilder(opts.buildMethod);+ var builder = builders.getBuilder();+return builder.prepEnv(opts).then(function () {if (opts.prepEnv) {events.emit('verbose', 'Build file successfully prepared.');return;}return builder.build(opts).then(function () {- var apkPaths = builder.findOutputApks(opts.buildType, opts.arch);- events.emit('log', 'Built the following apk(s): \n\t' + apkPaths.join('\n\t'));+ var paths;+ if (opts.packageType === PackageType.BUNDLE) {+ paths = builder.findOutputBundles(opts.buildType);+ events.emit('log', 'Built the following bundle(s): \n\t' + paths.join('\n\t'));+ } else {+ paths = builder.findOutputApks(opts.buildType, opts.arch);+ events.emit('log', 'Built the following apk(s): \n\t' + paths.join('\n\t'));+ }+return {- apkPaths: apkPaths,- buildType: opts.buildType,- buildMethod: opts.buildMethod+ paths: paths,+ buildType: opts.buildType};});});@@ -178,27 +201,37 @@ module.exports.detectArchitecture = function (target) {return /intel/i.exec(output) ? 'x86' : 'arm';});}+ function timeout (ms, err) {+ return new Promise((resolve, reject) => {+ setTimeout(() => reject(err), ms);+ });+ }// It sometimes happens (at least on OS X), that this command will hang forever.// To fix it, either unplug & replug device, or restart adb server.- return helper().timeout(1000, new CordovaError('Device communication timed out. Try unplugging & replugging the device.')).then(null, function (err) {+ return Promise.race([+ helper(),+ timeout(5000, new CordovaError(+ 'Device communication timed out. Try unplugging & replugging the device.'+ ))+ ]).catch(err => {if (/timed out/.exec('' + err)) {// adb kill-server doesn't seem to do the trick.// Could probably find a x-platform version of killall, but I'm not actually// sure that this scenario even happens on non-OSX machines.events.emit('verbose', 'adb timed out while detecting device/emulator architecture. Killing adb and trying again.');- return spawn('killall', ['adb']).then(function () {+ return execa('killall', ['adb']).then(function () {return helper().then(null, function () {// The double kill is sadly often necessary, at least on mac.events.emit('warn', 'adb timed out a second time while detecting device/emulator architecture. Killing adb and trying again.');- return spawn('killall', ['adb']).then(function () {+ return execa('killall', ['adb']).then(function () {return helper().then(null, function () {- return Q.reject(new CordovaError('adb timed out a third time while detecting device/emulator architecture. Try unplugging & replugging the device.'));+ return Promise.reject(new CordovaError('adb timed out a third time while detecting device/emulator architecture. Try unplugging & replugging the device.'));});});});}, function () {// For non-killall OS's.- return Q.reject(err);+ return Promise.reject(err);});}throw err;@@ -229,45 +262,23 @@ module.exports.findBestApkForArchitecture = function (buildResults, arch) {};function PackageInfo (keystore, alias, storePassword, password, keystoreType) {- this.keystore = {- 'name': 'key.store',- 'value': keystore- };- this.alias = {- 'name': 'key.alias',- 'value': alias- };- if (storePassword) {- this.storePassword = {- 'name': 'key.store.password',- 'value': storePassword- };- }- if (password) {- this.password = {- 'name': 'key.alias.password',- 'value': password- };- }- if (keystoreType) {- this.keystoreType = {- 'name': 'key.store.type',- 'value': keystoreType- };- }+ const createNameKeyObject = (name, value) => ({ name, value: value.replace(/\\/g, '\\\\') });++ this.data = [+ createNameKeyObject('key.store', keystore),+ createNameKeyObject('key.alias', alias)+ ];++ if (storePassword) this.data.push(createNameKeyObject('key.store.password', storePassword));+ if (password) this.data.push(createNameKeyObject('key.alias.password', password));+ if (keystoreType) this.data.push(createNameKeyObject('key.store.type', keystoreType));}PackageInfo.prototype = {- toProperties: function () {- var self = this;- var result = '';- Object.keys(self).forEach(function (key) {- result += self[key].name;- result += '=';- result += self[key].value.replace(/\\/g, '\\\\');- result += '\n';- });- return result;+ appendToProperties: function (propertiesParser) {+ for (const { name, value } of this.data) propertiesParser.set(name, value);++ propertiesParser.save();}};@@ -276,13 +287,14 @@ module.exports.help = function () {console.log('Flags:');console.log(' \'--debug\': will build project in debug mode (default)');console.log(' \'--release\': will build project for release');- console.log(' \'--ant\': will build project with ant');- console.log(' \'--gradle\': will build project with gradle (default)');console.log(' \'--nobuild\': will skip build process (useful when using run command)');console.log(' \'--prepenv\': don\'t build, but copy in build scripts where necessary');- console.log(' \'--versionCode=#\': Override versionCode for this build. Useful for uploading multiple APKs. Requires --gradle.');- console.log(' \'--minSdkVersion=#\': Override minSdkVersion for this build. Useful for uploading multiple APKs. Requires --gradle.');+ console.log(' \'--versionCode=#\': Override versionCode for this build. Useful for uploading multiple APKs.');+ console.log(' \'--minSdkVersion=#\': Override minSdkVersion for this build.');+ console.log(' \'--maxSdkVersion=#\': Override maxSdkVersion for this build. (Not Recommended)');+ console.log(' \'--targetSdkVersion=#\': Override targetSdkVersion for this build.');console.log(' \'--gradleArg=<gradle command line arg>\': Extra args to pass to the gradle command. Use one flag per arg. Ex. --gradleArg=-PcdvBuildMultipleApks=true');+ console.log(' \'--packageType=<apk|bundle>\': Builds an APK or a bundle');console.log('');console.log('Signed APK flags (overwrites debug/release-signing.proprties) :');console.log(' \'--keystore=<path to keystore>\': Key store used to build a signed archive. (Required)');diff --git a/cordova/platforms/android/cordova/lib/builders/GenericBuilder.js b/cordova/platforms/android/cordova/lib/builders/GenericBuilder.jsdeleted file mode 100644index 892aa38f4..000000000--- a/cordova/platforms/android/cordova/lib/builders/GenericBuilder.js+++ /dev/null@@ -1,124 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/-/* eslint no-self-assign: 0 */-/* eslint no-unused-vars: 0 */--var Q = require('q');-var fs = require('fs');-var path = require('path');-var shell = require('shelljs');-var events = require('cordova-common').events;--function GenericBuilder (projectDir) {- this.root = projectDir || path.resolve(__dirname, '../../..');- this.binDirs = {- studio: path.join(this.root, 'app', 'build', 'outputs', 'apk'),- gradle: path.join(this.root, 'build', 'outputs', 'apk')- };-}--GenericBuilder.prototype.prepEnv = function () {- return Q();-};--GenericBuilder.prototype.build = function () {- events.emit('log', 'Skipping build...');- return Q(null);-};--GenericBuilder.prototype.clean = function () {- return Q();-};--GenericBuilder.prototype.findOutputApks = function (build_type, arch) {- var self = this;- return Object.keys(this.binDirs).reduce(function (result, builderName) {- var binDir = self.binDirs[builderName];- return result.concat(findOutputApksHelper(binDir, build_type, builderName === 'ant' ? null : arch));- }, []).sort(apkSorter);-};--module.exports = GenericBuilder;--function apkSorter (fileA, fileB) {- // De-prioritize arch specific builds- var archSpecificRE = /-x86|-arm/;- if (archSpecificRE.exec(fileA)) {- return 1;- } else if (archSpecificRE.exec(fileB)) {- return -1;- }-- // De-prioritize unsigned builds- var unsignedRE = /-unsigned/;- if (unsignedRE.exec(fileA)) {- return 1;- } else if (unsignedRE.exec(fileB)) {- return -1;- }-- var timeDiff = fs.statSync(fileB).mtime - fs.statSync(fileA).mtime;- return timeDiff === 0 ? fileA.length - fileB.length : timeDiff;-}--function findOutputApksHelper (dir, build_type, arch) {- var shellSilent = shell.config.silent;- shell.config.silent = true;-- // list directory recursively- var ret = shell.ls('-R', dir).map(function (file) {- // ls does not include base directory- return path.join(dir, file);- }).filter(function (file) {- // find all APKs- return file.match(/\.apk?$/i);- }).filter(function (candidate) {- var apkName = path.basename(candidate);- // Need to choose between release and debug .apk.- if (build_type === 'debug') {- return /-debug/.exec(apkName) && !/-unaligned|-unsigned/.exec(apkName);- }- if (build_type === 'release') {- return /-release/.exec(apkName) && !/-unaligned/.exec(apkName);- }- return true;- }).sort(apkSorter);-- shellSilent = shellSilent;-- if (ret.length === 0) {- return ret;- }- // Assume arch-specific build if newest apk has -x86 or -arm.- var archSpecific = !!/-x86|-arm/.exec(path.basename(ret[0]));- // And show only arch-specific ones (or non-arch-specific)- ret = ret.filter(function (p) {- /* jshint -W018 */- return !!/-x86|-arm/.exec(path.basename(p)) === archSpecific;- /* jshint +W018 */- });-- if (archSpecific && ret.length > 1 && arch) {- ret = ret.filter(function (p) {- return path.basename(p).indexOf('-' + arch) !== -1;- });- }-- return ret;-}diff --git a/cordova/platforms/android/cordova/lib/builders/GradleBuilder.js b/cordova/platforms/android/cordova/lib/builders/GradleBuilder.jsdeleted file mode 100644index b955db18b..000000000--- a/cordova/platforms/android/cordova/lib/builders/GradleBuilder.js+++ /dev/null@@ -1,331 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/--var Q = require('q');-var fs = require('fs');-var util = require('util');-var path = require('path');-var shell = require('shelljs');-var superspawn = require('cordova-common').superspawn;-var CordovaError = require('cordova-common').CordovaError;-var events = require('cordova-common').events;-var check_reqs = require('../check_reqs');--var GenericBuilder = require('./GenericBuilder');--var MARKER = 'YOUR CHANGES WILL BE ERASED!';-var SIGNING_PROPERTIES = '-signing.properties';-var TEMPLATE =- '# This file is automatically generated.\n' +- '# Do not modify this file -- ' + MARKER + '\n';--function GradleBuilder (projectRoot) {- GenericBuilder.call(this, projectRoot);-- this.binDirs = { gradle: this.binDirs.gradle };-}--util.inherits(GradleBuilder, GenericBuilder);--GradleBuilder.prototype.getArgs = function (cmd, opts) {- if (cmd === 'release') {- cmd = 'cdvBuildRelease';- } else if (cmd === 'debug') {- cmd = 'cdvBuildDebug';- }- var args = [cmd, '-b', path.join(this.root, 'build.gradle')];- if (opts.arch) {- args.push('-PcdvBuildArch=' + opts.arch);- }-- // 10 seconds -> 6 seconds- args.push('-Dorg.gradle.daemon=true');- // to allow dex in process- args.push('-Dorg.gradle.jvmargs=-Xmx2048m');- // allow NDK to be used - required by Gradle 1.5 plugin- args.push('-Pandroid.useDeprecatedNdk=true');- args.push.apply(args, opts.extraArgs);- // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):- // args.push('-Dorg.gradle.parallel=true');- return args;-};--/*- * This returns a promise- */--GradleBuilder.prototype.runGradleWrapper = function (gradle_cmd, gradle_file) {- var gradlePath = path.join(this.root, 'gradlew');- gradle_file = path.join(this.root, (gradle_file || 'wrapper.gradle'));- if (fs.existsSync(gradlePath)) {- // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows- } else {- return superspawn.spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', gradle_file], { stdio: 'pipe' })- .progress(function (stdio) {- suppressJavaOptionsInfo(stdio);- });- }-};--/*- * We need to kill this in a fire.- */--GradleBuilder.prototype.readProjectProperties = function () {- function findAllUniq (data, r) {- var s = {};- var m;- while ((m = r.exec(data))) {- s[m[1]] = 1;- }- return Object.keys(s);- }-- var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');- return {- libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),- gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),- systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)- };-};--GradleBuilder.prototype.extractRealProjectNameFromManifest = function () {- var manifestPath = path.join(this.root, 'AndroidManifest.xml');- var manifestData = fs.readFileSync(manifestPath, 'utf8');- var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);- if (!m) {- throw new CordovaError('Could not find package name in ' + manifestPath);- }-- var packageName = m[1];- var lastDotIndex = packageName.lastIndexOf('.');- return packageName.substring(lastDotIndex + 1);-};--// Makes the project buildable, minus the gradle wrapper.-GradleBuilder.prototype.prepBuildFiles = function () {- // Update the version of build.gradle in each dependent library.- var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');- var propertiesObj = this.readProjectProperties();- var subProjects = propertiesObj.libs;-- // Check and copy the gradle file into the subproject.- // Called by the loop below this function def.- var checkAndCopy = function (subProject, root) {- var subProjectGradle = path.join(root, subProject, 'build.gradle');- // This is the future-proof way of checking if a file exists- // This must be synchronous to satisfy a Travis test- try {- fs.accessSync(subProjectGradle, fs.F_OK);- } catch (e) {- shell.cp('-f', pluginBuildGradle, subProjectGradle);- }- };-- // Some dependencies on Android don't use gradle, or don't have default- // gradle files. This copies a dummy gradle file into them- for (var i = 0; i < subProjects.length; ++i) {- if (subProjects[i] !== 'CordovaLib' && subProjects[i] !== 'app') {- checkAndCopy(subProjects[i], this.root);- }- }-- var name = this.extractRealProjectNameFromManifest();- // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149- var settingsGradlePaths = subProjects.map(function (p) {- var realDir = p.replace(/[/\\]/g, ':');- var libName = realDir.replace(name + '-', '');- var str = 'include ":' + libName + '"\n';- if (realDir.indexOf(name + '-') !== -1) { str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n'; }- return str;- });-- // Write the settings.gradle file.- fs.writeFileSync(path.join(this.root, 'settings.gradle'),- '// GENERATED FILE - DO NOT EDIT\n' +- 'include ":"\n' + settingsGradlePaths.join(''));- // Update dependencies within build.gradle.- var buildGradle = fs.readFileSync(path.join(this.root, 'build.gradle'), 'utf8');- var depsList = '';- var root = this.root;-- // Cordova Plugins can be written as library modules that would use Cordova as a- // dependency. Because we need to make sure that Cordova is compiled only once for- // dexing, we make sure to exclude CordovaLib from these modules- var insertExclude = function (p) {- var gradlePath = path.join(root, p, 'build.gradle');- var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');- if (projectGradleFile.indexOf('CordovaLib') !== -1) {- depsList += '{\n exclude module:("CordovaLib")\n }\n';- } else {- depsList += '\n';- }- };-- subProjects.forEach(function (p) {- events.emit('log', 'Subproject Path: ' + p);- var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');- depsList += ' implementation(project(path: "' + libName + '"))';- insertExclude(p);- });-- // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390- var SYSTEM_LIBRARY_MAPPINGS = [- [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],- [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']- ];- propertiesObj.systemLibs.forEach(function (p) {- var mavenRef;- // It's already in gradle form if it has two ':'s- if (/:.*:/.exec(p)) {- mavenRef = p;- } else {- for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {- var pair = SYSTEM_LIBRARY_MAPPINGS[i];- if (pair[0].exec(p)) {- mavenRef = p.replace(pair[0], pair[1]);- break;- }- }- if (!mavenRef) {- throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);- }- }- depsList += ' compile "' + mavenRef + '"\n';- });-- // This code is dangerous and actually writes gradle declarations directly into the build.gradle- // Try not to mess with this if possible- buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');- var includeList = '';- propertiesObj.gradleIncludes.forEach(function (includePath) {- includeList += 'apply from: "' + includePath + '"\n';- });- buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');- fs.writeFileSync(path.join(this.root, 'build.gradle'), buildGradle);-};--GradleBuilder.prototype.prepEnv = function (opts) {- var self = this;- return check_reqs.check_gradle().then(function (gradlePath) {- return self.runGradleWrapper(gradlePath);- }).then(function () {- return self.prepBuildFiles();- }).then(function () {- // We now copy the gradle out of the framework- // This is a dirty patch to get the build working- /*- var wrapperDir = path.join(self.root, 'CordovaLib');- if (process.platform == 'win32') {- shell.rm('-f', path.join(self.root, 'gradlew.bat'));- shell.cp(path.join(wrapperDir, 'gradlew.bat'), self.root);- } else {- shell.rm('-f', path.join(self.root, 'gradlew'));- shell.cp(path.join(wrapperDir, 'gradlew'), self.root);- }- shell.rm('-rf', path.join(self.root, 'gradle', 'wrapper'));- shell.mkdir('-p', path.join(self.root, 'gradle'));- shell.cp('-r', path.join(wrapperDir, 'gradle', 'wrapper'), path.join(self.root, 'gradle'));-*/- // If the gradle distribution URL is set, make sure it points to version we want.- // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.- // For some reason, using ^ and $ don't work. This does the job, though.- var distributionUrlRegex = /distributionUrl.*zip/;- /* jshint -W069 */- var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-4.1-all.zip';- /* jshint +W069 */- var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');- shell.chmod('u+w', gradleWrapperPropertiesPath);- shell.sed('-i', distributionUrlRegex, 'distributionUrl=' + distributionUrl, gradleWrapperPropertiesPath);-- var propertiesFile = opts.buildType + SIGNING_PROPERTIES;- var propertiesFilePath = path.join(self.root, propertiesFile);- if (opts.packageInfo) {- fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());- } else if (isAutoGenerated(propertiesFilePath)) {- shell.rm('-f', propertiesFilePath);- }- });-};--/*- * Builds the project with gradle.- * Returns a promise.- */-GradleBuilder.prototype.build = function (opts) {- var wrapper = path.join(this.root, 'gradlew');- var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);-- return superspawn.spawn(wrapper, args, { stdio: 'pipe' })- .progress(function (stdio) {- suppressJavaOptionsInfo(stdio);- }).catch(function (error) {- if (error.toString().indexOf('failed to find target with hash string') >= 0) {- return check_reqs.check_android_target(error).then(function () {- // If due to some odd reason - check_android_target succeeds- // we should still fail here.- return Q.reject(error);- });- }- return Q.reject(error);- });-};--GradleBuilder.prototype.clean = function (opts) {- var builder = this;- var wrapper = path.join(this.root, 'gradlew');- var args = builder.getArgs('clean', opts);- return Q().then(function () {- return superspawn.spawn(wrapper, args, { stdio: 'inherit' });- }).then(function () {- shell.rm('-rf', path.join(builder.root, 'out'));-- ['debug', 'release'].forEach(function (config) {- var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);- if (isAutoGenerated(propertiesFilePath)) {- shell.rm('-f', propertiesFilePath);- }- });- });-};--module.exports = GradleBuilder;--function suppressJavaOptionsInfo (stdio) {- if (stdio.stderr) {- /*- * Workaround for the issue with Java printing some unwanted information to- * stderr instead of stdout.- * This function suppresses 'Picked up _JAVA_OPTIONS' message from being- * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for- * explanation.- */- var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());- if (suppressThisLine) {- return;- }- process.stderr.write(stdio.stderr);- } else {- process.stdout.write(stdio.stdout);- }-}--function isAutoGenerated (file) {- return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;-}diff --git a/cordova/platforms/android/cordova/lib/builders/ProjectBuilder.js b/cordova/platforms/android/cordova/lib/builders/ProjectBuilder.jsnew file mode 100644index 000000000..fdf35be45--- /dev/null+++ b/cordova/platforms/android/cordova/lib/builders/ProjectBuilder.js@@ -0,0 +1,380 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++var fs = require('fs-extra');+var path = require('path');+const execa = require('execa');+var events = require('cordova-common').events;+var CordovaError = require('cordova-common').CordovaError;+var check_reqs = require('../check_reqs');+var PackageType = require('../PackageType');+const { createEditor } = require('properties-parser');++const MARKER = 'YOUR CHANGES WILL BE ERASED!';+const SIGNING_PROPERTIES = '-signing.properties';+const TEMPLATE =+ '# This file is automatically generated.\n' ++ '# Do not modify this file -- ' + MARKER + '\n';++const archSpecificRegex = /-x86|-arm/;+const unsignedBuildRegex = /-unsigned/;++const fileSorter = (filePathA, filePathB) => {+ const archSpecificA = archSpecificRegex.test(filePathA);+ const archSpecificB = archSpecificRegex.test(filePathB);++ // If they are not equal, then sort by specific archs after generic ones+ if (archSpecificA !== archSpecificB) {+ return archSpecificA < archSpecificB ? -1 : 1;+ }++ // Otherwise, move onto the next sort item, which is by sorting unsigned bulds after signed ones+ const unsignedA = unsignedBuildRegex.test(filePathA);+ const unsignedB = unsignedBuildRegex.test(filePathB);++ if (unsignedA !== unsignedB) {+ return unsignedA < unsignedB ? -1 : 1;+ }++ // Then, sort by modification time, latest first+ const modTimeA = fs.statSync(filePathA).mtime.getTime();+ const modTimeB = fs.statSync(filePathB).mtime.getTime();++ if (modTimeA !== modTimeB) {+ return modTimeA < modTimeB ? 1 : -1;+ }++ // Finally, if all above is the same, sort by file name length, ascending+ return filePathB.length < filePathA.length ? -1 : 1;+};++/**+ * If the provided directory does not exist or extension is missing, return an empty array.+ * If the director exists, loop the directories and collect list of files matching the extension.+ *+ * @param {String} dir Directory to scan+ * @param {String} extension+ */+function recursivelyFindFiles (dir, extension) {+ if (!fs.existsSync(dir) || !extension) return [];++ const files = fs.readdirSync(dir, { withFileTypes: true })+ .map(entry => {+ const item = path.resolve(dir, entry.name);++ if (entry.isDirectory()) return recursivelyFindFiles(item, extension);+ if (path.extname(entry.name) === `.${extension}`) return item;+ return false;+ });++ return Array.prototype.concat(...files)+ .filter(file => file !== false);+}++/**+ * @param {String} dir+ * @param {String} build_type+ * @param {String} arch+ * @param {String} extension+ */+function findOutputFilesHelper (dir, build_type, arch, extension) {+ let files = recursivelyFindFiles(path.resolve(dir, build_type), extension);++ if (files.length === 0) return files;++ // Assume arch-specific build if newest apk has -x86 or -arm.+ const archSpecific = !!/-x86|-arm/.exec(path.basename(files[0]));++ // And show only arch-specific ones (or non-arch-specific)+ files = files.filter(p => !!/-x86|-arm/.exec(path.basename(p)) === archSpecific);++ if (archSpecific && files.length > 1 && arch) {+ files = files.filter(p => path.basename(p).indexOf('-' + arch) !== -1);+ }++ return files;+}++class ProjectBuilder {+ constructor (rootDirectory) {+ this.root = rootDirectory || path.resolve(__dirname, '../../..');+ this.apkDir = path.join(this.root, 'app', 'build', 'outputs', 'apk');+ this.aabDir = path.join(this.root, 'app', 'build', 'outputs', 'bundle');+ }++ getArgs (cmd, opts) {+ let args;+ let buildCmd = cmd;+ if (opts.packageType === PackageType.BUNDLE) {+ if (cmd === 'release') {+ buildCmd = ':app:bundleRelease';+ } else if (cmd === 'debug') {+ buildCmd = ':app:bundleDebug';+ }++ args = [buildCmd, '-b', path.join(this.root, 'build.gradle')];+ } else {+ if (cmd === 'release') {+ buildCmd = 'cdvBuildRelease';+ } else if (cmd === 'debug') {+ buildCmd = 'cdvBuildDebug';+ }++ args = [buildCmd, '-b', path.join(this.root, 'build.gradle')];++ if (opts.arch) {+ args.push('-PcdvBuildArch=' + opts.arch);+ }+ }++ args.push.apply(args, opts.extraArgs);++ return args;+ }++ /*+ * This returns a promise+ */+ runGradleWrapper (gradle_cmd) {+ var gradlePath = path.join(this.root, 'gradlew');+ var wrapperGradle = path.join(this.root, 'wrapper.gradle');+ if (fs.existsSync(gradlePath)) {+ // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows+ } else {+ return execa(gradle_cmd, ['-p', this.root, 'wrapper', '-b', wrapperGradle], { stdio: 'inherit' });+ }+ }++ readProjectProperties () {+ function findAllUniq (data, r) {+ var s = {};+ var m;+ while ((m = r.exec(data))) {+ s[m[1]] = 1;+ }+ return Object.keys(s);+ }++ var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');+ return {+ libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),+ gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),+ systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)+ };+ }++ extractRealProjectNameFromManifest () {+ var manifestPath = path.join(this.root, 'app', 'src', 'main', 'AndroidManifest.xml');+ var manifestData = fs.readFileSync(manifestPath, 'utf8');+ var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);+ if (!m) {+ throw new CordovaError('Could not find package name in ' + manifestPath);+ }++ var packageName = m[1];+ var lastDotIndex = packageName.lastIndexOf('.');+ return packageName.substring(lastDotIndex + 1);+ }++ // Makes the project buildable, minus the gradle wrapper.+ prepBuildFiles () {+ // Update the version of build.gradle in each dependent library.+ var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');+ var propertiesObj = this.readProjectProperties();+ var subProjects = propertiesObj.libs;++ // Check and copy the gradle file into the subproject+ // Called by the loop before this function def++ var checkAndCopy = function (subProject, root) {+ var subProjectGradle = path.join(root, subProject, 'build.gradle');+ // This is the future-proof way of checking if a file exists+ // This must be synchronous to satisfy a Travis test+ try {+ fs.accessSync(subProjectGradle, fs.F_OK);+ } catch (e) {+ fs.copySync(pluginBuildGradle, subProjectGradle);+ }+ };++ for (var i = 0; i < subProjects.length; ++i) {+ if (subProjects[i] !== 'CordovaLib') {+ checkAndCopy(subProjects[i], this.root);+ }+ }+ var name = this.extractRealProjectNameFromManifest();+ // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149+ var settingsGradlePaths = subProjects.map(function (p) {+ var realDir = p.replace(/[/\\]/g, ':');+ var libName = realDir.replace(name + '-', '');+ var str = 'include ":' + libName + '"\n';+ if (realDir.indexOf(name + '-') !== -1) {+ str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n';+ }+ return str;+ });++ fs.writeFileSync(path.join(this.root, 'settings.gradle'),+ '// GENERATED FILE - DO NOT EDIT\n' ++ 'include ":"\n' + settingsGradlePaths.join(''));++ // Update dependencies within build.gradle.+ var buildGradle = fs.readFileSync(path.join(this.root, 'app', 'build.gradle'), 'utf8');+ var depsList = '';+ var root = this.root;+ var insertExclude = function (p) {+ var gradlePath = path.join(root, p, 'build.gradle');+ var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');+ if (projectGradleFile.indexOf('CordovaLib') !== -1) {+ depsList += '{\n exclude module:("CordovaLib")\n }\n';+ } else {+ depsList += '\n';+ }+ };+ subProjects.forEach(function (p) {+ events.emit('log', 'Subproject Path: ' + p);+ var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');+ if (libName !== 'app') {+ depsList += ' implementation(project(path: ":' + libName + '"))';+ insertExclude(p);+ }+ });+ // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390+ var SYSTEM_LIBRARY_MAPPINGS = [+ [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],+ [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']+ ];++ propertiesObj.systemLibs.forEach(function (p) {+ var mavenRef;+ // It's already in gradle form if it has two ':'s+ if (/:.*:/.exec(p)) {+ mavenRef = p;+ } else {+ for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {+ var pair = SYSTEM_LIBRARY_MAPPINGS[i];+ if (pair[0].exec(p)) {+ mavenRef = p.replace(pair[0], pair[1]);+ break;+ }+ }+ if (!mavenRef) {+ throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);+ }+ }+ depsList += ' implementation "' + mavenRef + '"\n';+ });++ buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');+ var includeList = '';++ propertiesObj.gradleIncludes.forEach(function (includePath) {+ includeList += 'apply from: "../' + includePath + '"\n';+ });+ buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');+ // This needs to be stored in the app gradle, not the root grade+ fs.writeFileSync(path.join(this.root, 'app', 'build.gradle'), buildGradle);+ }++ prepEnv (opts) {+ var self = this;+ return check_reqs.check_gradle()+ .then(function (gradlePath) {+ return self.runGradleWrapper(gradlePath);+ }).then(function () {+ return self.prepBuildFiles();+ }).then(() => {+ // update/set the distributionUrl in the gradle-wrapper.properties+ const gradleWrapperPropertiesPath = path.join(self.root, 'gradle/wrapper/gradle-wrapper.properties');+ const gradleWrapperProperties = createEditor(gradleWrapperPropertiesPath);+ const distributionUrl = process.env.CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL || 'https://services.gradle.org/distributions/gradle-6.5-all.zip';+ gradleWrapperProperties.set('distributionUrl', distributionUrl);+ gradleWrapperProperties.save();++ events.emit('verbose', `Gradle Distribution URL: ${distributionUrl}`);+ })+ .then(() => {+ const signingPropertiesPath = path.join(self.root, `${opts.buildType}${SIGNING_PROPERTIES}`);++ if (fs.existsSync(signingPropertiesPath)) fs.removeSync(signingPropertiesPath);+ if (opts.packageInfo) {+ fs.ensureFileSync(signingPropertiesPath);+ const signingProperties = createEditor(signingPropertiesPath);+ signingProperties.addHeadComment(TEMPLATE);+ opts.packageInfo.appendToProperties(signingProperties);+ }+ });+ }++ /*+ * Builds the project with gradle.+ * Returns a promise.+ */+ build (opts) {+ var wrapper = path.join(this.root, 'gradlew');+ var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);++ return execa(wrapper, args, { stdio: 'inherit' })+ .catch(function (error) {+ if (error.toString().indexOf('failed to find target with hash string') >= 0) {+ return check_reqs.check_android_target(error).then(function () {+ // If due to some odd reason - check_android_target succeeds+ // we should still fail here.+ throw error;+ });+ }+ throw error;+ });+ }++ clean (opts) {+ const wrapper = path.join(this.root, 'gradlew');+ const args = this.getArgs('clean', opts);+ return execa(wrapper, args, { stdio: 'inherit' })+ .then(() => {+ fs.removeSync(path.join(this.root, 'out'));++ ['debug', 'release'].map(config => path.join(this.root, `${config}${SIGNING_PROPERTIES}`))+ .forEach(file => {+ const hasFile = fs.existsSync(file);+ const hasMarker = hasFile && fs.readFileSync(file, 'utf8')+ .includes(MARKER);++ if (hasFile && hasMarker) fs.removeSync(file);+ });+ });+ }++ findOutputApks (build_type, arch) {+ return findOutputFilesHelper(this.apkDir, build_type, arch, 'apk').sort(fileSorter);+ }++ findOutputBundles (build_type) {+ return findOutputFilesHelper(this.aabDir, build_type, false, 'aab').sort(fileSorter);+ }++ fetchBuildResults (build_type, arch) {+ return {+ apkPaths: this.findOutputApks(build_type, arch),+ buildType: build_type+ };+ }+}++module.exports = ProjectBuilder;diff --git a/cordova/platforms/android/cordova/lib/builders/StudioBuilder.js b/cordova/platforms/android/cordova/lib/builders/StudioBuilder.jsdeleted file mode 100644index 1689e16c5..000000000--- a/cordova/platforms/android/cordova/lib/builders/StudioBuilder.js+++ /dev/null@@ -1,303 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/--var Q = require('q');-var fs = require('fs');-var util = require('util');-var path = require('path');-var shell = require('shelljs');-var spawn = require('cordova-common').superspawn.spawn;-var events = require('cordova-common').events;-var CordovaError = require('cordova-common').CordovaError;-var check_reqs = require('../check_reqs');--var GenericBuilder = require('./GenericBuilder');--var MARKER = 'YOUR CHANGES WILL BE ERASED!';-var SIGNING_PROPERTIES = '-signing.properties';-var TEMPLATE =- '# This file is automatically generated.\n' +- '# Do not modify this file -- ' + MARKER + '\n';--function StudioBuilder (projectRoot) {- GenericBuilder.call(this, projectRoot);-- this.binDirs = {gradle: this.binDirs.studio};-}--util.inherits(StudioBuilder, GenericBuilder);--StudioBuilder.prototype.getArgs = function (cmd, opts) {- if (cmd === 'release') {- cmd = 'cdvBuildRelease';- } else if (cmd === 'debug') {- cmd = 'cdvBuildDebug';- }- var args = [cmd, '-b', path.join(this.root, 'build.gradle')];- if (opts.arch) {- args.push('-PcdvBuildArch=' + opts.arch);- }-- // 10 seconds -> 6 seconds- args.push('-Dorg.gradle.daemon=true');- // to allow dex in process- args.push('-Dorg.gradle.jvmargs=-Xmx2048m');- // allow NDK to be used - required by Gradle 1.5 plugin- // args.push('-Pandroid.useDeprecatedNdk=true');- args.push.apply(args, opts.extraArgs);- // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):- // args.push('-Dorg.gradle.parallel=true');- return args;-};--/*- * This returns a promise- */--StudioBuilder.prototype.runGradleWrapper = function (gradle_cmd) {- var gradlePath = path.join(this.root, 'gradlew');- var wrapperGradle = path.join(this.root, 'wrapper.gradle');- if (fs.existsSync(gradlePath)) {- // Literally do nothing, for some reason this works, while !fs.existsSync didn't on Windows- } else {- return spawn(gradle_cmd, ['-p', this.root, 'wrapper', '-b', wrapperGradle], {stdio: 'inherit'});- }-};--StudioBuilder.prototype.readProjectProperties = function () {-- function findAllUniq (data, r) {- var s = {};- var m;- while ((m = r.exec(data))) {- s[m[1]] = 1;- }- return Object.keys(s);- }-- var data = fs.readFileSync(path.join(this.root, 'project.properties'), 'utf8');- return {- libs: findAllUniq(data, /^\s*android\.library\.reference\.\d+=(.*)(?:\s|$)/mg),- gradleIncludes: findAllUniq(data, /^\s*cordova\.gradle\.include\.\d+=(.*)(?:\s|$)/mg),- systemLibs: findAllUniq(data, /^\s*cordova\.system\.library\.\d+=(.*)(?:\s|$)/mg)- };-};--StudioBuilder.prototype.extractRealProjectNameFromManifest = function () {- var manifestPath = path.join(this.root, 'app', 'src', 'main', 'AndroidManifest.xml');- var manifestData = fs.readFileSync(manifestPath, 'utf8');- var m = /<manifest[\s\S]*?package\s*=\s*"(.*?)"/i.exec(manifestData);- if (!m) {- throw new CordovaError('Could not find package name in ' + manifestPath);- }-- var packageName = m[1];- var lastDotIndex = packageName.lastIndexOf('.');- return packageName.substring(lastDotIndex + 1);-};--// Makes the project buildable, minus the gradle wrapper.-StudioBuilder.prototype.prepBuildFiles = function () {- // Update the version of build.gradle in each dependent library.- var pluginBuildGradle = path.join(this.root, 'cordova', 'lib', 'plugin-build.gradle');- var propertiesObj = this.readProjectProperties();- var subProjects = propertiesObj.libs;-- // Check and copy the gradle file into the subproject- // Called by the loop before this function def-- var checkAndCopy = function (subProject, root) {- var subProjectGradle = path.join(root, subProject, 'build.gradle');- // This is the future-proof way of checking if a file exists- // This must be synchronous to satisfy a Travis test- try {- fs.accessSync(subProjectGradle, fs.F_OK);- } catch (e) {- shell.cp('-f', pluginBuildGradle, subProjectGradle);- }- };-- for (var i = 0; i < subProjects.length; ++i) {- if (subProjects[i] !== 'CordovaLib') {- checkAndCopy(subProjects[i], this.root);- }- }- var name = this.extractRealProjectNameFromManifest();- // Remove the proj.id/name- prefix from projects: https://issues.apache.org/jira/browse/CB-9149- var settingsGradlePaths = subProjects.map(function (p) {- var realDir = p.replace(/[/\\]/g, ':');- var libName = realDir.replace(name + '-', '');- var str = 'include ":' + libName + '"\n';- if (realDir.indexOf(name + '-') !== -1) {- str += 'project(":' + libName + '").projectDir = new File("' + p + '")\n';- }- return str;- });-- fs.writeFileSync(path.join(this.root, 'settings.gradle'),- '// GENERATED FILE - DO NOT EDIT\n' +- 'include ":"\n' + settingsGradlePaths.join(''));-- // Update dependencies within build.gradle.- var buildGradle = fs.readFileSync(path.join(this.root, 'app', 'build.gradle'), 'utf8');- var depsList = '';- var root = this.root;- var insertExclude = function (p) {- var gradlePath = path.join(root, p, 'build.gradle');- var projectGradleFile = fs.readFileSync(gradlePath, 'utf-8');- if (projectGradleFile.indexOf('CordovaLib') !== -1) {- depsList += '{\n exclude module:("CordovaLib")\n }\n';- } else {- depsList += '\n';- }- };- subProjects.forEach(function (p) {- events.emit('log', 'Subproject Path: ' + p);- var libName = p.replace(/[/\\]/g, ':').replace(name + '-', '');- if (libName !== 'app') {- depsList += ' implementation(project(path: ":' + libName + '"))';- insertExclude(p);- }- });- // For why we do this mapping: https://issues.apache.org/jira/browse/CB-8390- var SYSTEM_LIBRARY_MAPPINGS = [- [/^\/?extras\/android\/support\/(.*)$/, 'com.android.support:support-$1:+'],- [/^\/?google\/google_play_services\/libproject\/google-play-services_lib\/?$/, 'com.google.android.gms:play-services:+']- ];-- propertiesObj.systemLibs.forEach(function (p) {- var mavenRef;- // It's already in gradle form if it has two ':'s- if (/:.*:/.exec(p)) {- mavenRef = p;- } else {- for (var i = 0; i < SYSTEM_LIBRARY_MAPPINGS.length; ++i) {- var pair = SYSTEM_LIBRARY_MAPPINGS[i];- if (pair[0].exec(p)) {- mavenRef = p.replace(pair[0], pair[1]);- break;- }- }- if (!mavenRef) {- throw new CordovaError('Unsupported system library (does not work with gradle): ' + p);- }- }- depsList += ' compile "' + mavenRef + '"\n';- });-- buildGradle = buildGradle.replace(/(SUB-PROJECT DEPENDENCIES START)[\s\S]*(\/\/ SUB-PROJECT DEPENDENCIES END)/, '$1\n' + depsList + ' $2');- var includeList = '';-- propertiesObj.gradleIncludes.forEach(function (includePath) {- includeList += 'apply from: "../' + includePath + '"\n';- });- buildGradle = buildGradle.replace(/(PLUGIN GRADLE EXTENSIONS START)[\s\S]*(\/\/ PLUGIN GRADLE EXTENSIONS END)/, '$1\n' + includeList + '$2');- // This needs to be stored in the app gradle, not the root grade- fs.writeFileSync(path.join(this.root, 'app', 'build.gradle'), buildGradle);-};--StudioBuilder.prototype.prepEnv = function (opts) {- var self = this;- return check_reqs.check_gradle()- .then(function (gradlePath) {- return self.runGradleWrapper(gradlePath);- }).then(function () {- return self.prepBuildFiles();- }).then(function () {- // If the gradle distribution URL is set, make sure it points to version we want.- // If it's not set, do nothing, assuming that we're using a future version of gradle that we don't want to mess with.- // For some reason, using ^ and $ don't work. This does the job, though.- var distributionUrlRegex = /distributionUrl.*zip/;- var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-4.1-all.zip';- var gradleWrapperPropertiesPath = path.join(self.root, 'gradle', 'wrapper', 'gradle-wrapper.properties');- shell.chmod('u+w', gradleWrapperPropertiesPath);- shell.sed('-i', distributionUrlRegex, 'distributionUrl=' + distributionUrl, gradleWrapperPropertiesPath);-- var propertiesFile = opts.buildType + SIGNING_PROPERTIES;- var propertiesFilePath = path.join(self.root, propertiesFile);- if (opts.packageInfo) {- fs.writeFileSync(propertiesFilePath, TEMPLATE + opts.packageInfo.toProperties());- } else if (isAutoGenerated(propertiesFilePath)) {- shell.rm('-f', propertiesFilePath);- }- });-};--/*- * Builds the project with gradle.- * Returns a promise.- */-StudioBuilder.prototype.build = function (opts) {- var wrapper = path.join(this.root, 'gradlew');- var args = this.getArgs(opts.buildType === 'debug' ? 'debug' : 'release', opts);-- return spawn(wrapper, args, {stdio: 'pipe'})- .progress(function (stdio) {- if (stdio.stderr) {- /*- * Workaround for the issue with Java printing some unwanted information to- * stderr instead of stdout.- * This function suppresses 'Picked up _JAVA_OPTIONS' message from being- * printed to stderr. See https://issues.apache.org/jira/browse/CB-9971 for- * explanation.- */- var suppressThisLine = /^Picked up _JAVA_OPTIONS: /i.test(stdio.stderr.toString());- if (suppressThisLine) {- return;- }- process.stderr.write(stdio.stderr);- } else {- process.stdout.write(stdio.stdout);- }- }).catch(function (error) {- if (error.toString().indexOf('failed to find target with hash string') >= 0) {- return check_reqs.check_android_target(error).then(function () {- // If due to some odd reason - check_android_target succeeds- // we should still fail here.- return Q.reject(error);- });- }- return Q.reject(error);- });-};--StudioBuilder.prototype.clean = function (opts) {- var builder = this;- var wrapper = path.join(this.root, 'gradlew');- var args = builder.getArgs('clean', opts);- return Q().then(function () {- return spawn(wrapper, args, {stdio: 'inherit'});- })- .then(function () {- shell.rm('-rf', path.join(builder.root, 'out'));-- ['debug', 'release'].forEach(function (config) {- var propertiesFilePath = path.join(builder.root, config + SIGNING_PROPERTIES);- if (isAutoGenerated(propertiesFilePath)) {- shell.rm('-f', propertiesFilePath);- }- });- });-};--module.exports = StudioBuilder;--function isAutoGenerated (file) {- return fs.existsSync(file) && fs.readFileSync(file, 'utf8').indexOf(MARKER) > 0;-}diff --git a/cordova/platforms/android/cordova/lib/builders/builders.js b/cordova/platforms/android/cordova/lib/builders/builders.jsindex aedf9be52..edc1a5255 100644--- a/cordova/platforms/android/cordova/lib/builders/builders.js+++ b/cordova/platforms/android/cordova/lib/builders/builders.js@@ -1,46 +1,34 @@/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at- http://www.apache.org/licenses/LICENSE-2.0+ http://www.apache.org/licenses/LICENSE-2.0- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.+ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.*/-var CordovaError = require('cordova-common').CordovaError;--var knownBuilders = {- gradle: 'GradleBuilder',- studio: 'StudioBuilder',- none: 'GenericBuilder'-};+const CordovaError = require('cordova-common').CordovaError;/**- * Helper method that instantiates and returns a builder for specified build- * type.+ * Helper method that instantiates and returns a builder for specified build type.*- * @param {String} builderType Builder name to construct and return. Must- * be one of 'ant', 'gradle' or 'none'- *- * @return {Builder} A builder instance for specified build type.+ * @return {Builder} A builder instance for specified build type.*/-module.exports.getBuilder = function (builderType, projectRoot) {- if (!knownBuilders[builderType]) { throw new CordovaError('Builder ' + builderType + ' is not supported.'); }-+module.exports.getBuilder = function (projectPath) {try {- var Builder = require('./' + knownBuilders[builderType]);- return new Builder(projectRoot);+ const Builder = require('./ProjectBuilder');+ return new Builder(projectPath);} catch (err) {- throw new CordovaError('Failed to instantiate ' + knownBuilders[builderType] + ' builder: ' + err);+ throw new CordovaError('Failed to instantiate ProjectBuilder builder: ' + err);}};diff --git a/cordova/platforms/android/cordova/lib/check_reqs.js b/cordova/platforms/android/cordova/lib/check_reqs.jsindex d9c5f99d5..21d90f769 100644--- a/cordova/platforms/android/cordova/lib/check_reqs.js+++ b/cordova/platforms/android/cordova/lib/check_reqs.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,26 +17,37 @@under the License.*/-/* jshint sub:true */--var shelljs = require('shelljs');-var child_process = require('child_process');-var Q = require('q');+const execa = require('execa');var path = require('path');-var fs = require('fs');+var fs = require('fs-extra');var os = require('os');+var which = require('which');var REPO_ROOT = path.join(__dirname, '..', '..', '..', '..');var PROJECT_ROOT = path.join(__dirname, '..', '..');-var CordovaError = require('cordova-common').CordovaError;-var superspawn = require('cordova-common').superspawn;+const { CordovaError, ConfigParser, events } = require('cordova-common');var android_sdk = require('./android_sdk');+const { createEditor } = require('properties-parser');function forgivingWhichSync (cmd) {- try {- return fs.realpathSync(shelljs.which(cmd));- } catch (e) {- return '';+ const whichResult = which.sync(cmd, { nothrow: true });++ // On null, returns empty string to maintain backwards compatibility+ // realpathSync follows symlinks+ return whichResult === null ? '' : fs.realpathSync(whichResult);+}++function getJDKDirectory (directory) {+ const p = path.resolve(directory, 'java');+ if (fs.existsSync(p)) {+ const directories = fs.readdirSync(p);+ for (let i = 0; i < directories.length; i++) {+ const dir = directories[i];+ if (/^(jdk)+./.test(dir)) {+ return path.resolve(directory, 'java', dir);+ }+ }}+ return null;}module.exports.isWindows = function () {@@ -49,31 +58,49 @@ module.exports.isDarwin = function () {return (os.platform() === 'darwin');};-// Get valid target from framework/project.properties if run from this repo-// Otherwise get target from project.properties file within a generated cordova-android project+/**+ * @description Get valid target from framework/project.properties if run from this repo+ * Otherwise get target from project.properties file within a generated cordova-android project+ * @returns {string} The android target in format "android-${target}"+ */module.exports.get_target = function () {- function extractFromFile (filePath) {- var target = shelljs.grep(/\btarget=/, filePath);- if (!target) {- throw new Error('Could not find android target within: ' + filePath);- }- return target.split('=')[1].trim();- }- var repo_file = path.join(REPO_ROOT, 'framework', 'project.properties');- if (fs.existsSync(repo_file)) {- return extractFromFile(repo_file);+ const projectPropertiesPaths = [+ path.join(REPO_ROOT, 'framework', 'project.properties'),+ path.join(PROJECT_ROOT, 'project.properties')+ ];++ // Get the minimum required target API from the framework.+ let target = projectPropertiesPaths.filter(filePath => fs.existsSync(filePath))+ .map(filePath => createEditor(filePath).get('target'))+ .pop();++ if (!target) {+ throw new Error(`We could not locate the target from the "project.properties" at either "${projectPropertiesPaths.join('", "')}".`);}- var project_file = path.join(PROJECT_ROOT, 'project.properties');- if (fs.existsSync(project_file)) {- // if no target found, we're probably in a project and project.properties is in PROJECT_ROOT.- return extractFromFile(project_file);++ // If the repo config.xml file exists, find the desired targetSdkVersion.+ const configFile = path.join(REPO_ROOT, 'config.xml');+ if (!fs.existsSync(configFile)) return target;++ const configParser = new ConfigParser(configFile);+ const desiredAPI = parseInt(configParser.getPreference('android-targetSdkVersion', 'android'), 10);++ if (!isNaN(desiredAPI)) {+ const minimumAPI = parseInt(target.split('-').pop(), 10);++ if (desiredAPI >= minimumAPI) {+ target = `android-${desiredAPI}`;+ } else {+ events.emit('warn', `android-targetSdkVersion should be greater than or equal to ${minimumAPI}.`);+ }}- throw new Error('Could not find android target in either ' + repo_file + ' nor ' + project_file);++ return target;};// Returns a promise. Called only by build and clean commands.module.exports.check_ant = function () {- return superspawn.spawn('ant', ['-version']).then(function (output) {+ return execa('ant', ['-version']).then(({ stdout: output }) => {// Parse Ant version from command outputreturn /version ((?:\d+\.)+(?:\d+))/i.exec(output)[1];}).catch(function (err) {@@ -90,19 +117,18 @@ module.exports.get_gradle_wrapper = function () {var program_dir;// OK, This hack only works on Windows, not on Mac OS or Linux. We will be deleting this eventually!if (module.exports.isWindows()) {-- var result = child_process.spawnSync(path.join(__dirname, 'getASPath.bat'));+ var result = execa.sync(path.join(__dirname, 'getASPath.bat'));// console.log('result.stdout =' + result.stdout.toString());// console.log('result.stderr =' + result.stderr.toString());if (result.stderr.toString().length > 0) {- var androidPath = path.join(process.env['ProgramFiles'], 'Android') + '/';+ var androidPath = path.join(process.env.ProgramFiles, 'Android') + '/';if (fs.existsSync(androidPath)) {program_dir = fs.readdirSync(androidPath);while (i < program_dir.length && !foundStudio) {if (program_dir[i].startsWith('Android Studio')) {foundStudio = true;- androidStudioPath = path.join(process.env['ProgramFiles'], 'Android', program_dir[i], 'gradle');+ androidStudioPath = path.join(process.env.ProgramFiles, 'Android', program_dir[i], 'gradle');} else { ++i; }}}@@ -127,31 +153,30 @@ module.exports.get_gradle_wrapper = function () {// Returns a promise. Called only by build and clean commands.module.exports.check_gradle = function () {- var sdkDir = process.env['ANDROID_HOME'];- var d = Q.defer();+ var sdkDir = process.env.ANDROID_SDK_ROOT || process.env.ANDROID_HOME;if (!sdkDir) {- return Q.reject(new CordovaError('Could not find gradle wrapper within Android SDK. Could not find Android SDK directory.\n' +- 'Might need to install Android SDK or set up \'ANDROID_HOME\' env variable.'));+ return Promise.reject(new CordovaError('Could not find gradle wrapper within Android SDK. Could not find Android SDK directory.\n' ++ 'Might need to install Android SDK or set up \'ANDROID_SDK_ROOT\' env variable.'));}var gradlePath = module.exports.get_gradle_wrapper();- if (gradlePath.length !== 0) { d.resolve(gradlePath); } else {- d.reject(new CordovaError('Could not find an installed version of Gradle either in Android Studio,\n' +- 'or on your system to install the gradle wrapper. Please include gradle \n' +- 'in your path, or install Android Studio'));- }- return d.promise;++ if (gradlePath.length !== 0) return Promise.resolve(gradlePath);++ return Promise.reject(new CordovaError('Could not find an installed version of Gradle either in Android Studio,\n' ++ 'or on your system to install the gradle wrapper. Please include gradle \n' ++ 'in your path, or install Android Studio'));};// Returns a promise.module.exports.check_java = function () {var javacPath = forgivingWhichSync('javac');- var hasJavaHome = !!process.env['JAVA_HOME'];- return Q().then(function () {+ var hasJavaHome = !!process.env.JAVA_HOME;+ return Promise.resolve().then(function () {if (hasJavaHome) {// Windows java installer doesn't add javac to PATH, nor set JAVA_HOME (ugh).if (!javacPath) {- process.env['PATH'] += path.delimiter + path.join(process.env['JAVA_HOME'], 'bin');+ process.env.PATH += path.delimiter + path.join(process.env.JAVA_HOME, 'bin');}} else {if (javacPath) {@@ -159,8 +184,8 @@ module.exports.check_java = function () {var find_java = '/usr/libexec/java_home';var default_java_error_msg = 'Failed to find \'JAVA_HOME\' environment variable. Try setting it manually.';if (fs.existsSync(find_java)) {- return superspawn.spawn(find_java).then(function (stdout) {- process.env['JAVA_HOME'] = stdout.trim();+ return execa(find_java).then(({ stdout }) => {+ process.env.JAVA_HOME = stdout;}).catch(function (err) {if (err) {throw new CordovaError(default_java_error_msg);@@ -168,47 +193,46 @@ module.exports.check_java = function () {});} else {// See if we can derive it from javac's location.- // fs.realpathSync is require on Ubuntu, which symplinks from /usr/bin -> JDKvar maybeJavaHome = path.dirname(path.dirname(javacPath));if (fs.existsSync(path.join(maybeJavaHome, 'lib', 'tools.jar'))) {- process.env['JAVA_HOME'] = maybeJavaHome;+ process.env.JAVA_HOME = maybeJavaHome;} else {throw new CordovaError(default_java_error_msg);}}} else if (module.exports.isWindows()) {- // Try to auto-detect java in the default install paths.- var oldSilent = shelljs.config.silent;- shelljs.config.silent = true;- var firstJdkDir =- shelljs.ls(process.env['ProgramFiles'] + '\\java\\jdk*')[0] ||- shelljs.ls('C:\\Program Files\\java\\jdk*')[0] ||- shelljs.ls('C:\\Program Files (x86)\\java\\jdk*')[0];- shelljs.config.silent = oldSilent;+ const programFilesEnv = path.resolve(process.env.ProgramFiles);+ const programFiles = 'C:\\Program Files\\';+ const programFilesx86 = 'C:\\Program Files (x86)\\';++ let firstJdkDir =+ getJDKDirectory(programFilesEnv) ||+ getJDKDirectory(programFiles) ||+ getJDKDirectory(programFilesx86);+if (firstJdkDir) {- // shelljs always uses / in paths.firstJdkDir = firstJdkDir.replace(/\//g, path.sep);if (!javacPath) {- process.env['PATH'] += path.delimiter + path.join(firstJdkDir, 'bin');+ process.env.PATH += path.delimiter + path.join(firstJdkDir, 'bin');}- process.env['JAVA_HOME'] = firstJdkDir;+ process.env.JAVA_HOME = firstJdkDir;}}}}).then(function () {- return Q.denodeify(child_process.exec)('javac -version')- .then(outputs => {- // outputs contains two entries: stdout and stderr+ return execa('javac', ['-version'], { all: true })+ .then(({ all: output }) => {// Java <= 8 writes version info to stderr, Java >= 9 to stdout- const output = outputs.join('').trim();const match = /javac\s+([\d.]+)/i.exec(output);return match && match[1];}, () => {var msg =- 'Failed to run "javac -version", make sure that you have a JDK installed.\n' +- 'You can get it from: http://www.oracle.com/technetwork/java/javase/downloads.\n';- if (process.env['JAVA_HOME']) {- msg += 'Your JAVA_HOME is invalid: ' + process.env['JAVA_HOME'] + '\n';+ 'Failed to run "javac -version", make sure that you have a JDK version 8 installed.\n' ++ 'You can get it from the following location:\n' ++ 'https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html';+ if (process.env.JAVA_HOME) {+ msg += '\n\n';+ msg += 'Your JAVA_HOME is invalid: ' + process.env.JAVA_HOME;}throw new CordovaError(msg);});@@ -217,47 +241,74 @@ module.exports.check_java = function () {// Returns a promise.module.exports.check_android = function () {- return Q().then(function () {- var androidCmdPath = forgivingWhichSync('android');- var adbInPath = forgivingWhichSync('adb');- var avdmanagerInPath = forgivingWhichSync('avdmanager');- var hasAndroidHome = !!process.env['ANDROID_HOME'] && fs.existsSync(process.env['ANDROID_HOME']);+ return Promise.resolve().then(function () {function maybeSetAndroidHome (value) {if (!hasAndroidHome && fs.existsSync(value)) {hasAndroidHome = true;- process.env['ANDROID_HOME'] = value;+ process.env.ANDROID_SDK_ROOT = value;}}++ var androidCmdPath = forgivingWhichSync('android');+ var adbInPath = forgivingWhichSync('adb');+ var avdmanagerInPath = forgivingWhichSync('avdmanager');+ var hasAndroidHome = false;++ if (process.env.ANDROID_SDK_ROOT) {+ maybeSetAndroidHome(path.resolve(process.env.ANDROID_SDK_ROOT));+ }+// First ensure ANDROID_HOME is set// If we have no hints (nothing in PATH), try a few default locationsif (!hasAndroidHome && !androidCmdPath && !adbInPath && !avdmanagerInPath) {+ if (process.env.ANDROID_HOME) {+ // Fallback to deprecated `ANDROID_HOME` variable+ maybeSetAndroidHome(path.join(process.env.ANDROID_HOME));+ }if (module.exports.isWindows()) {// Android Studio 1.0 installer- maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'sdk'));- maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'sdk'));+ if (process.env.LOCALAPPDATA) {+ maybeSetAndroidHome(path.join(process.env.LOCALAPPDATA, 'Android', 'sdk'));+ }+ if (process.env.ProgramFiles) {+ maybeSetAndroidHome(path.join(process.env.ProgramFiles, 'Android', 'sdk'));+ }+// Android Studio pre-1.0 installer- maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-studio', 'sdk'));- maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-studio', 'sdk'));+ if (process.env.LOCALAPPDATA) {+ maybeSetAndroidHome(path.join(process.env.LOCALAPPDATA, 'Android', 'android-studio', 'sdk'));+ }+ if (process.env.ProgramFiles) {+ maybeSetAndroidHome(path.join(process.env.ProgramFiles, 'Android', 'android-studio', 'sdk'));+ }+// Stand-alone installer- maybeSetAndroidHome(path.join(process.env['LOCALAPPDATA'], 'Android', 'android-sdk'));- maybeSetAndroidHome(path.join(process.env['ProgramFiles'], 'Android', 'android-sdk'));+ if (process.env.LOCALAPPDATA) {+ maybeSetAndroidHome(path.join(process.env.LOCALAPPDATA, 'Android', 'android-sdk'));+ }+ if (process.env.ProgramFiles) {+ maybeSetAndroidHome(path.join(process.env.ProgramFiles, 'Android', 'android-sdk'));+ }} else if (module.exports.isDarwin()) {// Android Studio 1.0 installer- maybeSetAndroidHome(path.join(process.env['HOME'], 'Library', 'Android', 'sdk'));+ if (process.env.HOME) {+ maybeSetAndroidHome(path.join(process.env.HOME, 'Library', 'Android', 'sdk'));+ }// Android Studio pre-1.0 installermaybeSetAndroidHome('/Applications/Android Studio.app/sdk');// Stand-alone zip file that user might think to put under /ApplicationsmaybeSetAndroidHome('/Applications/android-sdk-macosx');maybeSetAndroidHome('/Applications/android-sdk');}- if (process.env['HOME']) {+ if (process.env.HOME) {// Stand-alone zip file that user might think to put under their home directory- maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk-macosx'));- maybeSetAndroidHome(path.join(process.env['HOME'], 'android-sdk'));+ maybeSetAndroidHome(path.join(process.env.HOME, 'android-sdk-macosx'));+ maybeSetAndroidHome(path.join(process.env.HOME, 'android-sdk'));}}+if (!hasAndroidHome) {- // If we dont have ANDROID_HOME, but we do have some tools on the PATH, try to infer from the tooling PATH.+ // If we dont have ANDROID_SDK_ROOT, but we do have some tools on the PATH, try to infer from the tooling PATH.var parentDir, grandParentDir;if (androidCmdPath) {parentDir = path.dirname(androidCmdPath);@@ -265,7 +316,7 @@ module.exports.check_android = function () {if (path.basename(parentDir) === 'tools' || fs.existsSync(path.join(grandParentDir, 'tools', 'android'))) {maybeSetAndroidHome(grandParentDir);} else {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' ++ throw new CordovaError('Failed to find \'ANDROID_SDK_ROOT\' environment variable. Try setting it manually.\n' +'Detected \'android\' command at ' + parentDir + ' but no \'tools\' directory found near.\n' +'Try reinstall Android SDK or update your PATH to include valid path to SDK' + path.sep + 'tools directory.');}@@ -276,7 +327,7 @@ module.exports.check_android = function () {if (path.basename(parentDir) === 'platform-tools') {maybeSetAndroidHome(grandParentDir);} else {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' ++ throw new CordovaError('Failed to find \'ANDROID_SDK_ROOT\' environment variable. Try setting it manually.\n' +'Detected \'adb\' command at ' + parentDir + ' but no \'platform-tools\' directory found near.\n' +'Try reinstall Android SDK or update your PATH to include valid path to SDK' + path.sep + 'platform-tools directory.');}@@ -287,29 +338,29 @@ module.exports.check_android = function () {if (path.basename(parentDir) === 'bin' && path.basename(grandParentDir) === 'tools') {maybeSetAndroidHome(path.dirname(grandParentDir));} else {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' ++ throw new CordovaError('Failed to find \'ANDROID_SDK_ROOT\' environment variable. Try setting it manually.\n' +'Detected \'avdmanager\' command at ' + parentDir + ' but no \'tools' + path.sep + 'bin\' directory found near.\n' +'Try reinstall Android SDK or update your PATH to include valid path to SDK' + path.sep + 'tools' + path.sep + 'bin directory.');}}}- if (!process.env['ANDROID_HOME']) {- throw new CordovaError('Failed to find \'ANDROID_HOME\' environment variable. Try setting it manually.\n' ++ if (!process.env.ANDROID_SDK_ROOT) {+ throw new CordovaError('Failed to find \'ANDROID_SDK_ROOT\' environment variable. Try setting it manually.\n' +'Failed to find \'android\' command in your \'PATH\'. Try update your \'PATH\' to include path to valid SDK directory.');}- if (!fs.existsSync(process.env['ANDROID_HOME'])) {- throw new CordovaError('\'ANDROID_HOME\' environment variable is set to non-existent path: ' + process.env['ANDROID_HOME'] ++ if (!fs.existsSync(process.env.ANDROID_SDK_ROOT)) {+ throw new CordovaError('\'ANDROID_SDK_ROOT\' environment variable is set to non-existent path: ' + process.env.ANDROID_SDK_ROOT +'\nTry update it manually to point to valid SDK directory.');}// Next let's make sure relevant parts of the SDK tooling is in our PATHif (hasAndroidHome && !androidCmdPath) {- process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'tools');+ process.env.PATH += path.delimiter + path.join(process.env.ANDROID_SDK_ROOT, 'tools');}if (hasAndroidHome && !adbInPath) {- process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'platform-tools');+ process.env.PATH += path.delimiter + path.join(process.env.ANDROID_SDK_ROOT, 'platform-tools');}if (hasAndroidHome && !avdmanagerInPath) {- process.env['PATH'] += path.delimiter + path.join(process.env['ANDROID_HOME'], 'tools', 'bin');+ process.env.PATH += path.delimiter + path.join(process.env.ANDROID_SDK_ROOT, 'tools', 'bin');}return hasAndroidHome;});@@ -354,16 +405,22 @@ module.exports.check_android_target = function (originalError) {// Returns a promise.module.exports.run = function () {- return Q.all([this.check_java(), this.check_android()]).then(function (values) {- console.log('ANDROID_HOME=' + process.env['ANDROID_HOME']);- console.log('JAVA_HOME=' + process.env['JAVA_HOME']);+ console.log('Checking Java JDK and Android SDK versions');+ console.log('ANDROID_SDK_ROOT=' + process.env.ANDROID_SDK_ROOT + ' (recommended setting)');+ console.log('ANDROID_HOME=' + process.env.ANDROID_HOME + ' (DEPRECATED)');++ return Promise.all([this.check_java(), this.check_android()]).then(function (values) {+ console.log('Using Android SDK: ' + process.env.ANDROID_SDK_ROOT);if (!String(values[0]).startsWith('1.8.')) {- throw new CordovaError('Requirements check failed for JDK 1.8');+ throw new CordovaError(+ 'Requirements check failed for JDK 8 (\'1.8.*\')! Detected version: ' + values[0] + '\n' ++ 'Check your ANDROID_SDK_ROOT / JAVA_HOME / PATH environment variables.'+ );}if (!values[1]) {- throw new CordovaError('Requirements check failed for Android SDK');+ throw new CordovaError('Requirements check failed for Android SDK! Android SDK was not detected.');}});};@@ -392,7 +449,6 @@ var Requirement = function (id, name, version, installed) {* @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.*/module.exports.check_all = function () {-var requirements = [new Requirement('java', 'Java JDK'),new Requirement('androidSdk', 'Android SDK'),@@ -417,7 +473,7 @@ module.exports.check_all = function () {}, function (err) {requirement.metadata.reason = err instanceof Error ? err.message : err;});- }, Q()).then(function () {+ }, Promise.resolve()).then(function () {// When chain is completed, return requirements array to upstream APIreturn requirements;});diff --git a/cordova/platforms/android/cordova/lib/config/GradlePropertiesParser.js b/cordova/platforms/android/cordova/lib/config/GradlePropertiesParser.jsnew file mode 100644index 000000000..8955aa946--- /dev/null+++ b/cordova/platforms/android/cordova/lib/config/GradlePropertiesParser.js@@ -0,0 +1,150 @@+/**+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++const fs = require('fs');+const path = require('path');+const propertiesParser = require('properties-parser');+const events = require('cordova-common').events;++class GradlePropertiesParser {+ /**+ * Loads and Edits Gradle Properties File.+ *+ * @param {String} platformDir is the path of the Android platform directory+ */+ constructor (platformDir) {+ this._defaults = {+ // 10 seconds -> 6 seconds+ 'org.gradle.daemon': 'true',++ // to allow dex in process+ 'org.gradle.jvmargs': '-Xmx2048m',++ // Android X+ 'android.useAndroidX': 'false',+ 'android.enableJetifier': 'false'++ // Shaves another 100ms, but produces a "try at own risk" warning. Not worth it (yet):+ // 'org.gradle.parallel': 'true'+ };++ this.gradleFilePath = path.join(platformDir, 'gradle.properties');+ }++ configure (userConfigs) {+ events.emit('verbose', '[Gradle Properties] Preparing Configuration');++ this._initializeEditor();++ events.emit('verbose', '[Gradle Properties] Appending default configuration properties');+ this._configureProperties(this._defaults);++ events.emit('verbose', '[Gradle Properties] Appending custom configuration properties');+ this._configureProperties(userConfigs);++ this._save();+ }++ /**+ * Initialize the properties editor for parsing, setting, etc.+ */+ _initializeEditor () {+ // Touch empty gradle.properties file if missing.+ if (!fs.existsSync(this.gradleFilePath)) {+ events.emit('verbose', '[Gradle Properties] File missing, creating file with Cordova defaults.');+ fs.writeFileSync(this.gradleFilePath, '', 'utf-8');+ }++ // Create an editor for parsing, getting, and setting configurations.+ this.gradleFile = propertiesParser.createEditor(this.gradleFilePath);+ }++ /**+ * Validate that defaults or user configuration properties are set and+ * set the missing items.+ */+ _configureProperties (properties) {+ // Iterate though the properties and set only if missing.+ Object.keys(properties).forEach(key => {+ const value = this.gradleFile.get(key);++ if (!value) {+ // Handles the case of adding missing defaults or new properties that are missing.+ events.emit('verbose', `[Gradle Properties] Appending configuration item: ${key}=${properties[key]}`);+ this.gradleFile.set(key, properties[key]);+ } else if (value !== properties[key]) {+ if (this._defaults[key] && this._defaults[key] !== properties[key]) {+ let shouldEmit = true;+ if (key === 'org.gradle.jvmargs') {+ shouldEmit = this._isJVMMemoryLessThanRecommended(properties[key], this._defaults[key]);+ }++ if (shouldEmit) {+ // Since the value does not match default, we will notify the discrepancy with Cordova's recommended value.+ events.emit('info', `[Gradle Properties] Detected Gradle property "${key}" with the value of "${properties[key]}", Cordova's recommended value is "${this._defaults[key]}"`);+ }+ } else {+ // When the current value exists but does not match the new value or does matches the default key value, the new value it set.+ events.emit('verbose', `[Gradle Properties] Updating Gradle property "${key}" with the value of "${properties[key]}"`);+ }++ // We will set the new value in either case.+ this.gradleFile.set(key, properties[key]);+ }+ });+ }++ _isJVMMemoryLessThanRecommended (memoryValue, recommendedMemoryValue) {+ const UNIT = 2;+ const SIZE = 1;+ const regex = /-Xmx+([0-9]+)+([mMgGkK])/;++ const recommendedCapture = regex.exec(recommendedMemoryValue);+ const recommendedBase = this._getBaseJVMSize(recommendedCapture[SIZE], recommendedCapture[UNIT]);+ const memoryCapture = regex.exec(memoryValue);+ const memoryBase = this._getBaseJVMSize(memoryCapture[SIZE], memoryCapture[UNIT]);++ return memoryBase < recommendedBase;+ }++ _getBaseJVMSize (size, unit) {+ const KILOBYTE = 1024;+ const MEGABYTE = 1048576;+ const GIGABYTE = 1073741824;++ switch (unit.toLowerCase()) {+ case 'k': return size * KILOBYTE;+ case 'm': return size * MEGABYTE;+ case 'g': return size * GIGABYTE;+ }++ events.emit('warn', `[Gradle Properties] Unknown memory size unit (${unit})`);+ return null;+ }++ /**+ * Saves any changes that has been made to the properties file.+ */+ _save () {+ events.emit('verbose', '[Gradle Properties] Updating and Saving File');+ this.gradleFile.save();+ }+}++module.exports = GradlePropertiesParser;diff --git a/cordova/platforms/android/cordova/lib/device.js b/cordova/platforms/android/cordova/lib/device.jsindex 84b509479..3bb95c90a 100644--- a/cordova/platforms/android/cordova/lib/device.js+++ b/cordova/platforms/android/cordova/lib/device.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,12 +17,11 @@under the License.*/-var Q = require('q');+const execa = require('execa');var build = require('./build');var path = require('path');var Adb = require('./Adb');var AndroidManifest = require('./AndroidManifest');-var spawn = require('cordova-common').superspawn.spawn;var CordovaError = require('cordova-common').CordovaError;var events = require('cordova-common').events;@@ -38,7 +35,7 @@ module.exports.list = function (lookHarder) {// adb kill-server doesn't seem to do the trick.// Could probably find a x-platform version of killall, but I'm not actually// sure that this scenario even happens on non-OSX machines.- return spawn('killall', ['adb']).then(function () {+ return execa('killall', ['adb']).then(function () {events.emit('verbose', 'Restarting adb to see if more devices are detected.');return Adb.devices();}, function () {@@ -53,13 +50,13 @@ module.exports.list = function (lookHarder) {module.exports.resolveTarget = function (target) {return this.list(true).then(function (device_list) {if (!device_list || !device_list.length) {- return Q.reject(new CordovaError('Failed to deploy to device, no devices found.'));+ return Promise.reject(new CordovaError('Failed to deploy to device, no devices found.'));}// default devicetarget = target || device_list[0];if (device_list.indexOf(target) < 0) {- return Q.reject('ERROR: Unable to find target \'' + target + '\'.');+ return Promise.reject(new CordovaError('ERROR: Unable to find target \'' + target + '\'.'));}return build.detectArchitecture(target).then(function (arch) {@@ -74,7 +71,7 @@ module.exports.resolveTarget = function (target) {* Returns a promise.*/module.exports.install = function (target, buildResults) {- return Q().then(function () {+ return Promise.resolve().then(function () {if (target && typeof target === 'object') {return target;}@@ -87,7 +84,7 @@ module.exports.install = function (target, buildResults) {events.emit('log', 'Using apk: ' + apk_path);events.emit('log', 'Package name: ' + pkgName);- return Adb.install(resolvedTarget.target, apk_path, {replace: true}).catch(function (error) {+ return Adb.install(resolvedTarget.target, apk_path, { replace: true }).catch(function (error) {// CB-9557 CB-10157 only uninstall and reinstall app if the one that// is already installed on device was signed w/different certificateif (!/INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES/.test(error.toString())) { throw error; }@@ -98,7 +95,7 @@ module.exports.install = function (target, buildResults) {// This promise is always resolved, even if 'adb uninstall' fails to uninstall app// or the app doesn't installed at all, so no error catching needed.return Adb.uninstall(resolvedTarget.target, pkgName).then(function () {- return Adb.install(resolvedTarget.target, apk_path, {replace: true});+ return Adb.install(resolvedTarget.target, apk_path, { replace: true });});}).then(function () {// unlock screendiff --git a/cordova/platforms/android/cordova/lib/emulator.js b/cordova/platforms/android/cordova/lib/emulator.jsindex 63ed302fe..928ad44d5 100644--- a/cordova/platforms/android/cordova/lib/emulator.js+++ b/cordova/platforms/android/cordova/lib/emulator.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,8 +17,8 @@under the License.*/-/* jshint sub:true */-+const execa = require('execa');+const fs = require('fs-extra');var android_versions = require('android-versions');var retry = require('./retry');var build = require('./build');@@ -28,54 +26,49 @@ var path = require('path');var Adb = require('./Adb');var AndroidManifest = require('./AndroidManifest');var events = require('cordova-common').events;-var superspawn = require('cordova-common').superspawn;var CordovaError = require('cordova-common').CordovaError;-var shelljs = require('shelljs');var android_sdk = require('./android_sdk');var check_reqs = require('./check_reqs');--var Q = require('q');+var which = require('which');var os = require('os');-var fs = require('fs');-var child_process = require('child_process');// constants-var ONE_SECOND = 1000; // in milliseconds-var ONE_MINUTE = 60 * ONE_SECOND; // in milliseconds-var INSTALL_COMMAND_TIMEOUT = 5 * ONE_MINUTE; // in milliseconds-var NUM_INSTALL_RETRIES = 3;-var CHECK_BOOTED_INTERVAL = 3 * ONE_SECOND; // in milliseconds-var EXEC_KILL_SIGNAL = 'SIGKILL';+const ONE_SECOND = 1000; // in milliseconds+const ONE_MINUTE = 60 * ONE_SECOND; // in milliseconds+const INSTALL_COMMAND_TIMEOUT = 5 * ONE_MINUTE; // in milliseconds+const NUM_INSTALL_RETRIES = 3;+const CHECK_BOOTED_INTERVAL = 3 * ONE_SECOND; // in milliseconds+const EXEC_KILL_SIGNAL = 'SIGKILL';function forgivingWhichSync (cmd) {- try {- return fs.realpathSync(shelljs.which(cmd));- } catch (e) {- return '';- }+ const whichResult = which.sync(cmd, { nothrow: true });++ // On null, returns empty string to maintain backwards compatibility+ // realpathSync follows symlinks+ return whichResult === null ? '' : fs.realpathSync(whichResult);}module.exports.list_images_using_avdmanager = function () {- return superspawn.spawn('avdmanager', ['list', 'avd']).then(function (output) {+ return execa('avdmanager', ['list', 'avd']).then(({ stdout: output }) => {var response = output.split('\n');var emulator_list = [];for (var i = 1; i < response.length; i++) {// To return more detailed information use img_objvar img_obj = {};if (response[i].match(/Name:\s/)) {- img_obj['name'] = response[i].split('Name: ')[1].replace('\r', '');+ img_obj.name = response[i].split('Name: ')[1].replace('\r', '');if (response[i + 1].match(/Device:\s/)) {i++;- img_obj['device'] = response[i].split('Device: ')[1].replace('\r', '');+ img_obj.device = response[i].split('Device: ')[1].replace('\r', '');}if (response[i + 1].match(/Path:\s/)) {i++;- img_obj['path'] = response[i].split('Path: ')[1].replace('\r', '');+ img_obj.path = response[i].split('Path: ')[1].replace('\r', '');}if (response[i + 1].match(/Target:\s/)) {i++;if (response[i + 1].match(/ABI:\s/)) {- img_obj['abi'] = response[i + 1].split('ABI: ')[1].replace('\r', '');+ img_obj.abi = response[i + 1].split('ABI: ')[1].replace('\r', '');}// This next conditional just aims to match the old output of `android list avd`// We do so so that we don't have to change the logic when parsing for the@@ -83,24 +76,24 @@ module.exports.list_images_using_avdmanager = function () {// This allows us to transitionally support both `android` and `avdmanager` binaries,// depending on what SDK version the user hasif (response[i + 1].match(/Based\son:\s/)) {- img_obj['target'] = response[i + 1].split('Based on:')[1];- if (img_obj['target'].match(/Tag\/ABI:\s/)) {- img_obj['target'] = img_obj['target'].split('Tag/ABI:')[0].replace('\r', '').trim();- if (img_obj['target'].indexOf('(') > -1) {- img_obj['target'] = img_obj['target'].substr(0, img_obj['target'].indexOf('(') - 1).trim();+ img_obj.target = response[i + 1].split('Based on:')[1];+ if (img_obj.target.match(/Tag\/ABI:\s/)) {+ img_obj.target = img_obj.target.split('Tag/ABI:')[0].replace('\r', '').trim();+ if (img_obj.target.indexOf('(') > -1) {+ img_obj.target = img_obj.target.substr(0, img_obj.target.indexOf('(') - 1).trim();}}- var version_string = img_obj['target'].replace(/Android\s+/, '');+ var version_string = img_obj.target.replace(/Android\s+/, '');var api_level = android_sdk.version_string_to_api_level[version_string];if (api_level) {- img_obj['target'] += ' (API level ' + api_level + ')';+ img_obj.target += ' (API level ' + api_level + ')';}}}if (response[i + 1].match(/Skin:\s/)) {i++;- img_obj['skin'] = response[i].split('Skin: ')[1].replace('\r', '');+ img_obj.skin = response[i].split('Skin: ')[1].replace('\r', '');}emulator_list.push(img_obj);@@ -109,41 +102,40 @@ module.exports.list_images_using_avdmanager = function () {if (response[i].match(/Name:\s/)) {emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');} */-}return emulator_list;});};module.exports.list_images_using_android = function () {- return superspawn.spawn('android', ['list', 'avd']).then(function (output) {+ return execa('android', ['list', 'avd']).then(({ stdout: output }) => {var response = output.split('\n');var emulator_list = [];for (var i = 1; i < response.length; i++) {// To return more detailed information use img_objvar img_obj = {};if (response[i].match(/Name:\s/)) {- img_obj['name'] = response[i].split('Name: ')[1].replace('\r', '');+ img_obj.name = response[i].split('Name: ')[1].replace('\r', '');if (response[i + 1].match(/Device:\s/)) {i++;- img_obj['device'] = response[i].split('Device: ')[1].replace('\r', '');+ img_obj.device = response[i].split('Device: ')[1].replace('\r', '');}if (response[i + 1].match(/Path:\s/)) {i++;- img_obj['path'] = response[i].split('Path: ')[1].replace('\r', '');+ img_obj.path = response[i].split('Path: ')[1].replace('\r', '');}if (response[i + 1].match(/\(API\slevel\s/) || (response[i + 2] && response[i + 2].match(/\(API\slevel\s/))) {i++;var secondLine = response[i + 1].match(/\(API\slevel\s/) ? response[i + 1] : '';- img_obj['target'] = (response[i] + secondLine).split('Target: ')[1].replace('\r', '');+ img_obj.target = (response[i] + secondLine).split('Target: ')[1].replace('\r', '');}if (response[i + 1].match(/ABI:\s/)) {i++;- img_obj['abi'] = response[i].split('ABI: ')[1].replace('\r', '');+ img_obj.abi = response[i].split('ABI: ')[1].replace('\r', '');}if (response[i + 1].match(/Skin:\s/)) {i++;- img_obj['skin'] = response[i].split('Skin: ')[1].replace('\r', '');+ img_obj.skin = response[i].split('Skin: ')[1].replace('\r', '');}emulator_list.push(img_obj);@@ -152,7 +144,6 @@ module.exports.list_images_using_android = function () {if (response[i].match(/Name:\s/)) {emulator_list.push(response[i].split('Name: ')[1].replace('\r', '');} */-}return emulator_list;});@@ -170,15 +161,13 @@ module.exports.list_images_using_android = function () {}*/module.exports.list_images = function () {- return Q.fcall(function () {+ return Promise.resolve().then(function () {if (forgivingWhichSync('avdmanager')) {return module.exports.list_images_using_avdmanager();} else if (forgivingWhichSync('android')) {return module.exports.list_images_using_android();} else {- return Q().then(function () {- throw new CordovaError('Could not find either `android` or `avdmanager` on your $PATH! Are you sure the Android SDK is installed and available?');- });+ return Promise.reject(new CordovaError('Could not find either `android` or `avdmanager` on your $PATH! Are you sure the Android SDK is installed and available?'));}}).then(function (avds) {// In case we're missing the Android OS version string from the target description, add it.@@ -228,13 +217,13 @@ module.exports.best_image = function () {// Returns a promise.module.exports.list_started = function () {- return Adb.devices({emulators: true});+ return Adb.devices({ emulators: true });};// Returns a promise.// TODO: we should remove this, there's a more robust method under android_sdk.jsmodule.exports.list_targets = function () {- return superspawn.spawn('android', ['list', 'targets'], {cwd: os.tmpdir()}).then(function (output) {+ return execa('android', ['list', 'targets'], { cwd: os.tmpdir() }).then(({ stdout: output }) => {var target_out = output.split('\n');var targets = [];for (var i = target_out.length; i >= 0; i--) {@@ -277,8 +266,8 @@ module.exports.get_available_port = function () {module.exports.start = function (emulator_ID, boot_timeout) {var self = this;- return Q().then(function () {- if (emulator_ID) return Q(emulator_ID);+ return Promise.resolve().then(function () {+ if (emulator_ID) return Promise.resolve(emulator_ID);return self.best_image().then(function (best) {if (best && best.name) {@@ -287,7 +276,7 @@ module.exports.start = function (emulator_ID, boot_timeout) {}var androidCmd = check_reqs.getAbsoluteAndroidCmd();- return Q.reject(new CordovaError('No emulator images (avds) found.\n' ++ return Promise.reject(new CordovaError('No emulator images (avds) found.\n' +'1. Download desired System Image by running: ' + androidCmd + ' sdk\n' +'2. Create an AVD by running: ' + androidCmd + ' avd\n' +'HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver\n'));@@ -296,11 +285,10 @@ module.exports.start = function (emulator_ID, boot_timeout) {return self.get_available_port().then(function (port) {// Figure out the directory the emulator binary runs in, and set the cwd to that directory.// Workaround for https://code.google.com/p/android/issues/detail?id=235461- var emulator_dir = path.dirname(shelljs.which('emulator'));+ var emulator_dir = path.dirname(which.sync('emulator'));var args = ['-avd', emulatorId, '-port', port];// Don't wait for it to finish, since the emulator will probably keep running for a long time.- child_process- .spawn('emulator', args, { stdio: 'inherit', detached: true, cwd: emulator_dir })+ execa('emulator', args, { stdio: 'inherit', detached: true, cwd: emulator_dir }).unref();// wait for emulator to start@@ -308,7 +296,7 @@ module.exports.start = function (emulator_ID, boot_timeout) {return self.wait_for_emulator(port);});}).then(function (emulatorId) {- if (!emulatorId) { return Q.reject(new CordovaError('Failed to start emulator')); }+ if (!emulatorId) { return Promise.reject(new CordovaError('Failed to start emulator')); }// wait for emulator to boot upprocess.stdout.write('Waiting for emulator to boot (this may take a while)...');@@ -334,7 +322,7 @@ module.exports.start = function (emulator_ID, boot_timeout) {*/module.exports.wait_for_emulator = function (port) {var self = this;- return Q().then(function () {+ return Promise.resolve().then(function () {var emulator_id = 'emulator-' + port;return Adb.shell(emulator_id, 'getprop dev.bootcomplete').then(function (output) {if (output.indexOf('1') >= 0) {@@ -345,7 +333,8 @@ module.exports.wait_for_emulator = function (port) {if ((error && error.message &&(error.message.indexOf('not found') > -1)) ||(error.message.indexOf('device offline') > -1) ||- (error.message.indexOf('device still connecting') > -1)) {+ (error.message.indexOf('device still connecting') > -1) ||+ (error.message.indexOf('device still authorizing') > -1)) {// emulator not yet started, continue waitingreturn self.wait_for_emulator(port);} else {@@ -363,18 +352,21 @@ module.exports.wait_for_emulator = function (port) {*/module.exports.wait_for_boot = function (emulator_id, time_remaining) {var self = this;- return Adb.shell(emulator_id, 'ps').then(function (output) {- if (output.match(/android\.process\.acore/)) {+ return Adb.shell(emulator_id, 'getprop sys.boot_completed').then(function (output) {+ if (output.match(/1/)) {return true;} else if (time_remaining === 0) {return false;} else {process.stdout.write('.');- // Check at regular intervals- return Q.delay(time_remaining < CHECK_BOOTED_INTERVAL ? time_remaining : CHECK_BOOTED_INTERVAL).then(function () {- var updated_time = time_remaining >= 0 ? Math.max(time_remaining - CHECK_BOOTED_INTERVAL, 0) : time_remaining;- return self.wait_for_boot(emulator_id, updated_time);+ return new Promise(resolve => {+ const delay = time_remaining < CHECK_BOOTED_INTERVAL ? time_remaining : CHECK_BOOTED_INTERVAL;++ setTimeout(() => {+ const updated_time = time_remaining >= 0 ? Math.max(time_remaining - CHECK_BOOTED_INTERVAL, 0) : time_remaining;+ resolve(self.wait_for_boot(emulator_id, updated_time));+ }, delay);});}});@@ -388,22 +380,22 @@ module.exports.wait_for_boot = function (emulator_id, time_remaining) {module.exports.create_image = function (name, target) {console.log('Creating new avd named ' + name);if (target) {- return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', target]).then(null, function (error) {+ return execa('android', ['create', 'avd', '--name', name, '--target', target]).then(null, function (error) {console.error('ERROR : Failed to create emulator image : ');console.error(' Do you have the latest android targets including ' + target + '?');- console.error(error);+ console.error(error.message);});} else {console.log('WARNING : Project target not found, creating avd with a different target but the project may fail to install.');// TODO: there's a more robust method for finding targets in android_sdk.js- return superspawn.spawn('android', ['create', 'avd', '--name', name, '--target', this.list_targets()[0]]).then(function () {+ return execa('android', ['create', 'avd', '--name', name, '--target', this.list_targets()[0]]).then(function () {// TODO: This seems like another error case, even though it always happens.console.error('ERROR : Unable to create an avd emulator, no targets found.');console.error('Ensure you have targets available by running the "android" command');- return Q.reject();+ return Promise.reject(new CordovaError());}, function (error) {console.error('ERROR : Failed to create emulator image : ');- console.error(error);+ console.error(error.message);});}};@@ -411,17 +403,17 @@ module.exports.create_image = function (name, target) {module.exports.resolveTarget = function (target) {return this.list_started().then(function (emulator_list) {if (emulator_list.length < 1) {- return Q.reject('No running Android emulators found, please start an emulator before deploying your project.');+ return Promise.reject(new CordovaError('No running Android emulators found, please start an emulator before deploying your project.'));}// default emulatortarget = target || emulator_list[0];if (emulator_list.indexOf(target) < 0) {- return Q.reject('Unable to find target \'' + target + '\'. Failed to deploy to emulator.');+ return Promise.reject(new CordovaError('Unable to find target \'' + target + '\'. Failed to deploy to emulator.'));}return build.detectArchitecture(target).then(function (arch) {- return {target: target, arch: arch, isEmulator: true};+ return { target: target, arch: arch, isEmulator: true };});});};@@ -433,18 +425,14 @@ module.exports.resolveTarget = function (target) {* Returns a promise.*/module.exports.install = function (givenTarget, buildResults) {-var target;// We need to find the proper path to the Android Manifest- var manifestPath = path.join(__dirname, '..', '..', 'app', 'src', 'main', 'AndroidManifest.xml');- if (buildResults.buildMethod === 'gradle') {- manifestPath = path.join(__dirname, '../../AndroidManifest.xml');- }- var manifest = new AndroidManifest(manifestPath);- var pkgName = manifest.getPackageId();+ const manifestPath = path.join(__dirname, '..', '..', 'app', 'src', 'main', 'AndroidManifest.xml');+ const manifest = new AndroidManifest(manifestPath);+ const pkgName = manifest.getPackageId();// resolve the target emulator- return Q().then(function () {+ return Promise.resolve().then(function () {if (givenTarget && typeof givenTarget === 'object') {return givenTarget;} else {@@ -459,8 +447,7 @@ module.exports.install = function (givenTarget, buildResults) {}).then(function () {// This promise is always resolved, even if 'adb uninstall' fails to uninstall app// or the app doesn't installed at all, so no error catching needed.- return Q.when().then(function () {-+ return Promise.resolve().then(function () {var apk_path = build.findBestApkForArchitecture(buildResults, target.arch);var execOptions = {cwd: os.tmpdir(),@@ -478,24 +465,21 @@ module.exports.install = function (givenTarget, buildResults) {function adbInstallWithOptions (target, apk, opts) {events.emit('verbose', 'Installing apk ' + apk + ' on ' + target + '...');- var command = 'adb -s ' + target + ' install -r "' + apk + '"';- return Q.promise(function (resolve, reject) {- child_process.exec(command, opts, function (err, stdout, stderr) {- if (err) reject(new CordovaError('Error executing "' + command + '": ' + stderr));- // adb does not return an error code even if installation fails. Instead it puts a specific- // message to stdout, so we have to use RegExp matching to detect installation failure.- else if (/Failure/.test(stdout)) {- if (stdout.match(/INSTALL_PARSE_FAILED_NO_CERTIFICATES/)) {- stdout += 'Sign the build using \'-- --keystore\' or \'--buildConfig\'' +- ' or sign and deploy the unsigned apk manually using Android tools.';- } else if (stdout.match(/INSTALL_FAILED_VERSION_DOWNGRADE/)) {- stdout += 'You\'re trying to install apk with a lower versionCode that is already installed.' +- '\nEither uninstall an app or increment the versionCode.';- }+ const args = ['-s', target, 'install', '-r', apk];+ return execa('adb', args, opts).then(({ stdout }) => {+ // adb does not return an error code even if installation fails. Instead it puts a specific+ // message to stdout, so we have to use RegExp matching to detect installation failure.+ if (/Failure/.test(stdout)) {+ if (stdout.match(/INSTALL_PARSE_FAILED_NO_CERTIFICATES/)) {+ stdout += 'Sign the build using \'-- --keystore\' or \'--buildConfig\'' ++ ' or sign and deploy the unsigned apk manually using Android tools.';+ } else if (stdout.match(/INSTALL_FAILED_VERSION_DOWNGRADE/)) {+ stdout += 'You\'re trying to install apk with a lower versionCode that is already installed.' ++ '\nEither uninstall an app or increment the versionCode.';+ }- reject(new CordovaError('Failed to install apk to emulator: ' + stdout));- } else resolve(stdout);- });+ throw new CordovaError('Failed to install apk to emulator: ' + stdout);+ }});}@@ -522,7 +506,6 @@ module.exports.install = function (givenTarget, buildResults) {});// unlock screen}).then(function () {-events.emit('verbose', 'Unlocking screen...');return Adb.shell(target.target, 'input keyevent 82');}).then(function () {diff --git a/cordova/platforms/android/cordova/lib/install-device b/cordova/platforms/android/cordova/lib/install-deviceindex fc4b7841f..03873883e 100755--- a/cordova/platforms/android/cordova/lib/install-device+++ b/cordova/platforms/android/cordova/lib/install-device@@ -19,23 +19,23 @@under the License.*/-var device = require('./device'),- args = process.argv;+var device = require('./device');+var args = process.argv;-if(args.length > 2) {+if (args.length > 2) {var install_target;- if (args[2].substring(0, 9) == '--target=') {+ if (args[2].substring(0, 9) === '--target=') {install_target = args[2].substring(9, args[2].length);- device.install(install_target).done(null, function(err) {+ device.install(install_target).catch(function (err) {console.error('ERROR: ' + err);process.exit(2);});- } else {+ } else {console.error('ERROR : argument \'' + args[2] + '\' not recognized.');process.exit(2);- }+ }} else {- device.install().done(null, function(err) {+ device.install().catch(function (err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/install-device.bat b/cordova/platforms/android/cordova/lib/install-device.batindex 109b470eb..fe5d74304 100644--- a/cordova/platforms/android/cordova/lib/install-device.bat+++ b/cordova/platforms/android/cordova/lib/install-device.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -23,4 +23,4 @@ IF EXIST %script_path% (ECHO.ECHO ERROR: Could not find 'install-device' script in 'cordova\lib' folder, aborting...>&2EXIT /B 1-)\ No newline at end of file+)diff --git a/cordova/platforms/android/cordova/lib/install-emulator b/cordova/platforms/android/cordova/lib/install-emulatorindex aa2a34f6f..2d46dbe93 100755--- a/cordova/platforms/android/cordova/lib/install-emulator+++ b/cordova/platforms/android/cordova/lib/install-emulator@@ -19,20 +19,20 @@under the License.*/-var emulator = require('./emulator'),- args = process.argv;+var emulator = require('./emulator');+var args = process.argv;var install_target;-if(args.length > 2) {- if (args[2].substring(0, 9) == '--target=') {+if (args.length > 2) {+ if (args[2].substring(0, 9) === '--target=') {install_target = args[2].substring(9, args[2].length);- } else {+ } else {console.error('ERROR : argument \'' + args[2] + '\' not recognized.');process.exit(2);- }+ }}-emulator.install(install_target).done(null, function(err) {+emulator.install(install_target).catch(function (err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/install-emulator.bat b/cordova/platforms/android/cordova/lib/install-emulator.batindex a28c23a18..c9e56fc5a 100644--- a/cordova/platforms/android/cordova/lib/install-emulator.bat+++ b/cordova/platforms/android/cordova/lib/install-emulator.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -23,4 +23,4 @@ IF EXIST %script_path% (ECHO.ECHO ERROR: Could not find 'install-emulator' script in 'cordova\lib' folder, aborting...>&2EXIT /B 1-)\ No newline at end of file+)diff --git a/cordova/platforms/android/cordova/lib/list-devices b/cordova/platforms/android/cordova/lib/list-devicesindex 8e22c7f2f..339c6658d 100755--- a/cordova/platforms/android/cordova/lib/list-devices+++ b/cordova/platforms/android/cordova/lib/list-devices@@ -22,12 +22,12 @@var devices = require('./device');// Usage support for when args are given-require('./check_reqs').check_android().then(function() {- devices.list().done(function(device_list) {- device_list && device_list.forEach(function(dev) {+require('./check_reqs').check_android().then(function () {+ devices.list().then(function (device_list) {+ device_list && device_list.forEach(function (dev) {console.log(dev);});- }, function(err) {+ }, function (err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/list-devices.bat b/cordova/platforms/android/cordova/lib/list-devices.batindex ad5f03ed0..04abda8e1 100644--- a/cordova/platforms/android/cordova/lib/list-devices.bat+++ b/cordova/platforms/android/cordova/lib/list-devices.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -23,4 +23,4 @@ IF EXIST %script_path% (ECHO.ECHO ERROR: Could not find 'list-devices' script in 'cordova\lib' folder, aborting...>&2EXIT /B 1-)\ No newline at end of file+)diff --git a/cordova/platforms/android/cordova/lib/list-emulator-images b/cordova/platforms/android/cordova/lib/list-emulator-imagesindex 25e5c81a4..03cfb190c 100755--- a/cordova/platforms/android/cordova/lib/list-emulator-images+++ b/cordova/platforms/android/cordova/lib/list-emulator-images@@ -22,12 +22,12 @@var emulators = require('./emulator');// Usage support for when args are given-require('./check_reqs').check_android().then(function() {- emulators.list_images().done(function(emulator_list) {- emulator_list && emulator_list.forEach(function(emu) {+require('./check_reqs').check_android().then(function () {+ emulators.list_images().then(function (emulator_list) {+ emulator_list && emulator_list.forEach(function (emu) {console.log(emu.name);});- }, function(err) {+ }, function (err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/list-emulator-images.bat b/cordova/platforms/android/cordova/lib/list-emulator-images.batindex 616ffb751..55c399d7a 100644--- a/cordova/platforms/android/cordova/lib/list-emulator-images.bat+++ b/cordova/platforms/android/cordova/lib/list-emulator-images.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -20,7 +20,7 @@ SET script_path="%~dp0list-emulator-images"IF EXIST %script_path% (node %script_path% %*) ELSE (- ECHO.+ ECHO.ECHO ERROR: Could not find 'list-emulator-images' script in 'cordova\lib' folder, aborting...>&2EXIT /B 1)diff --git a/cordova/platforms/android/cordova/lib/list-started-emulators b/cordova/platforms/android/cordova/lib/list-started-emulatorsindex 43ebda25b..2a83e03a1 100755--- a/cordova/platforms/android/cordova/lib/list-started-emulators+++ b/cordova/platforms/android/cordova/lib/list-started-emulators@@ -22,12 +22,12 @@var emulators = require('./emulator');// Usage support for when args are given-require('./check_reqs').check_android().then(function() {- emulators.list_started().done(function(emulator_list) {- emulator_list && emulator_list.forEach(function(emu) {+require('./check_reqs').check_android().then(function () {+ emulators.list_started().then(function (emulator_list) {+ emulator_list && emulator_list.forEach(function (emu) {console.log(emu);});- }, function(err) {+ }, function (err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/lib/list-started-emulators.bat b/cordova/platforms/android/cordova/lib/list-started-emulators.batindex eed02a5c5..56243fc2b 100644--- a/cordova/platforms/android/cordova/lib/list-started-emulators.bat+++ b/cordova/platforms/android/cordova/lib/list-started-emulators.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -23,4 +23,4 @@ IF EXIST %script_path% (ECHO.ECHO ERROR: Could not find 'list-started-emulators' script in 'cordova\lib' folder, aborting...>&2EXIT /B 1-)\ No newline at end of file+)diff --git a/cordova/platforms/android/cordova/lib/log.js b/cordova/platforms/android/cordova/lib/log.jsindex ef2dd5cb0..4e087651b 100644--- a/cordova/platforms/android/cordova/lib/log.js+++ b/cordova/platforms/android/cordova/lib/log.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -21,8 +19,7 @@var path = require('path');var os = require('os');-var Q = require('q');-var child_process = require('child_process');+var execa = require('execa');var ROOT = path.join(__dirname, '..', '..');/*@@ -30,8 +27,7 @@ var ROOT = path.join(__dirname, '..', '..');* Returns a promise.*/module.exports.run = function () {- var d = Q.defer();- var adb = child_process.spawn('adb', ['logcat'], {cwd: os.tmpdir()});+ var adb = execa('adb', ['logcat'], { cwd: os.tmpdir(), stderr: 'inherit' });adb.stdout.on('data', function (data) {var lines = data ? data.toString().split('\n') : [];@@ -39,14 +35,7 @@ module.exports.run = function () {console.log(out.join('\n'));});- adb.stderr.on('data', console.error);- adb.on('close', function (code) {- if (code > 0) {- d.reject('Failed to run logcat command.');- } else d.resolve();- });-- return d.promise;+ return adb;};module.exports.help = function () {diff --git a/cordova/platforms/android/cordova/lib/plugin-build.gradle b/cordova/platforms/android/cordova/lib/plugin-build.gradleindex fdef1f73f..032b870e1 100644--- a/cordova/platforms/android/cordova/lib/plugin-build.gradle+++ b/cordova/platforms/android/cordova/lib/plugin-build.gradle@@ -20,9 +20,7 @@buildscript {repositories {- maven {- url "https://maven.google.com"- }+ google()jcenter()}@@ -38,7 +36,7 @@ buildscript {apply plugin: 'com.android.library'dependencies {- compile fileTree(dir: 'libs', include: '*.jar')+ implementation fileTree(dir: 'libs', include: '*.jar')debugCompile project(path: ":CordovaLib", configuration: "debug")releaseCompile project(path: ":CordovaLib", configuration: "release")}@@ -46,7 +44,6 @@ dependencies {android {compileSdkVersion cdvCompileSdkVersionbuildToolsVersion cdvBuildToolsVersion- publishNonDefault truecompileOptions {sourceCompatibility JavaVersion.VERSION_1_6diff --git a/cordova/platforms/android/cordova/lib/pluginHandlers.js b/cordova/platforms/android/cordova/lib/pluginHandlers.jsindex f5be4b49d..99e4bac72 100644--- a/cordova/platforms/android/cordova/lib/pluginHandlers.js+++ b/cordova/platforms/android/cordova/lib/pluginHandlers.js@@ -14,11 +14,8 @@**/-/* jshint unused: vars */--var fs = require('fs');+var fs = require('fs-extra');var path = require('path');-var shell = require('shelljs');var events = require('cordova-common').events;var CordovaError = require('cordova-common').CordovaError;@@ -28,14 +25,7 @@ var handlers = {if (!obj.src) throw new CordovaError(generateAttributeError('src', 'source-file', plugin.id));if (!obj.targetDir) throw new CordovaError(generateAttributeError('target-dir', 'source-file', plugin.id));- var dest = path.join(obj.targetDir, path.basename(obj.src));-- // TODO: This code needs to be replaced, since the core plugins need to be re-mapped to a different location in- // a later plugins release. This is for legacy plugins to work with Cordova.-- if (options && options.android_studio === true) {- dest = getInstallDestination(obj);- }+ var dest = getInstallDestination(obj);if (options && options.force) {copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));@@ -44,54 +34,38 @@ var handlers = {}},uninstall: function (obj, plugin, project, options) {- var dest = path.join(obj.targetDir, path.basename(obj.src));-- if (options && options.android_studio === true) {- dest = getInstallDestination(obj);- }+ var dest = getInstallDestination(obj);// TODO: Add Koltin extension to uninstall, since they are handled like Java filesif (obj.src.endsWith('java')) {deleteJava(project.projectDir, dest);} else {// Just remove the file, not the whole parent directory- removeFile(project.projectDir, dest);+ removeFile(path.resolve(project.projectDir, dest));}}},'lib-file': {install: function (obj, plugin, project, options) {- var dest = path.join('libs', path.basename(obj.src));- if (options && options.android_studio === true) {- dest = path.join('app/libs', path.basename(obj.src));- }+ var dest = path.join('app/libs', path.basename(obj.src));copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));},uninstall: function (obj, plugin, project, options) {- var dest = path.join('libs', path.basename(obj.src));- if (options && options.android_studio === true) {- dest = path.join('app/libs', path.basename(obj.src));- }- removeFile(project.projectDir, dest);+ var dest = path.join('app/libs', path.basename(obj.src));+ removeFile(path.resolve(project.projectDir, dest));}},'resource-file': {install: function (obj, plugin, project, options) {- var dest = path.normalize(obj.target);- if (options && options.android_studio === true) {- dest = path.join('app/src/main', dest);- }+ var dest = path.join('app', 'src', 'main', obj.target);copyFile(plugin.dir, obj.src, project.projectDir, dest, !!(options && options.link));},uninstall: function (obj, plugin, project, options) {- var dest = path.normalize(obj.target);- if (options && options.android_studio === true) {- dest = path.join('app/src/main', dest);- }- removeFile(project.projectDir, dest);+ var dest = path.join('app', 'src', 'main', obj.target);+ removeFile(path.resolve(project.projectDir, dest));}},- 'framework': {+ framework: {install: function (obj, plugin, project, options) {var src = obj.src;if (!src) throw new CordovaError(generateAttributeError('src', 'framework', plugin.id));@@ -127,7 +101,7 @@ var handlers = {if (obj.custom) {var subRelativeDir = project.getCustomSubprojectRelativeDir(plugin.id, src);- removeFile(project.projectDir, subRelativeDir);+ removeFile(path.resolve(project.projectDir, subRelativeDir));subDir = path.resolve(project.projectDir, subRelativeDir);// If it's the last framework in the plugin, remove the parent directory.var parDir = path.dirname(subDir);@@ -168,12 +142,12 @@ var handlers = {if (!target) throw new CordovaError(generateAttributeError('target', 'asset', plugin.id));- removeFileF(path.resolve(project.www, target));- removeFileF(path.resolve(project.www, 'plugins', plugin.id));+ removeFile(path.resolve(project.www, target));+ removeFile(path.resolve(project.www, 'plugins', plugin.id));if (options && options.usePlatformWww) {// CB-11022 remove file from both directories if usePlatformWww is specified- removeFileF(path.resolve(project.platformWww, target));- removeFileF(path.resolve(project.platformWww, 'plugins', plugin.id));+ removeFile(path.resolve(project.platformWww, target));+ removeFile(path.resolve(project.platformWww, 'plugins', plugin.id));}}},@@ -191,13 +165,13 @@ var handlers = {scriptContent = 'cordova.define("' + moduleName + '", function(require, exports, module) {\n' + scriptContent + '\n});\n';var wwwDest = path.resolve(project.www, 'plugins', plugin.id, obj.src);- shell.mkdir('-p', path.dirname(wwwDest));+ fs.ensureDirSync(path.dirname(wwwDest));fs.writeFileSync(wwwDest, scriptContent, 'utf-8');if (options && options.usePlatformWww) {// CB-11022 copy file to both directories if usePlatformWww is specifiedvar platformWwwDest = path.resolve(project.platformWww, 'plugins', plugin.id, obj.src);- shell.mkdir('-p', path.dirname(platformWwwDest));+ fs.ensureDirSync(path.dirname(platformWwwDest));fs.writeFileSync(platformWwwDest, scriptContent, 'utf-8');}},@@ -242,14 +216,11 @@ function copyFile (plugin_dir, src, project_dir, dest, link) {// check that dest path is located in project directoryif (dest.indexOf(project_dir) !== 0) { throw new CordovaError('Destination "' + dest + '" for source file "' + src + '" is located outside the project'); }- shell.mkdir('-p', path.dirname(dest));+ fs.ensureDirSync(path.dirname(dest));if (link) {symlinkFileOrDirTree(src, dest);- } else if (fs.statSync(src).isDirectory()) {- // XXX shelljs decides to create a directory when -R|-r is used which sucks. http://goo.gl/nbsjq- shell.cp('-Rf', src + '/*', dest);} else {- shell.cp('-f', src, dest);+ fs.copySync(src, dest);}}@@ -263,11 +234,11 @@ function copyNewFile (plugin_dir, src, project_dir, dest, link) {function symlinkFileOrDirTree (src, dest) {if (fs.existsSync(dest)) {- shell.rm('-Rf', dest);+ fs.removeSync(dest);}if (fs.statSync(src).isDirectory()) {- shell.mkdir('-p', dest);+ fs.ensureDirSync(path.dirname(dest));fs.readdirSync(src).forEach(function (entry) {symlinkFileOrDirTree(path.join(src, entry), path.join(dest, entry));});@@ -276,15 +247,8 @@ function symlinkFileOrDirTree (src, dest) {}}-// checks if file exists and then deletes. Error if doesn't exist-function removeFile (project_dir, src) {- var file = path.resolve(project_dir, src);- shell.rm('-Rf', file);-}--// deletes file/directory without checking-function removeFileF (file) {- shell.rm('-Rf', file);+function removeFile (file) {+ fs.removeSync(file);}// Sometimes we want to remove some java, and prune any unnecessary empty directories@@ -297,7 +261,7 @@ function removeFileAndParents (baseDir, destFile, stopper) {var file = path.resolve(baseDir, destFile);if (!fs.existsSync(file)) return;- removeFileF(file);+ removeFile(file);// check if directory is emptyvar curDir = path.dirname(file);@@ -319,27 +283,41 @@ function generateAttributeError (attribute, element, id) {function getInstallDestination (obj) {var APP_MAIN_PREFIX = 'app/src/main';+ var PATH_SEPARATOR = '/';++ var PATH_SEP_MATCH = '\\' + PATH_SEPARATOR;+ var PATH_SEP_OR_EOL_MATCH = '(\\' + PATH_SEPARATOR + '|$)';++ var appReg = new RegExp('^app' + PATH_SEP_OR_EOL_MATCH);+ var libsReg = new RegExp('^libs' + PATH_SEP_OR_EOL_MATCH);+ var srcReg = new RegExp('^src' + PATH_SEP_OR_EOL_MATCH);+ var srcMainReg = new RegExp('^src' + PATH_SEP_MATCH + 'main' + PATH_SEP_OR_EOL_MATCH);- if (obj.targetDir.startsWith('app')) {+ if (appReg.test(obj.targetDir)) {// If any source file is using the new app directory structure,// don't penalize itreturn path.join(obj.targetDir, path.basename(obj.src));- } else if (obj.src.endsWith('.java')) {- return path.join(APP_MAIN_PREFIX, 'java', obj.targetDir.substring(4), path.basename(obj.src));- } else if (obj.src.endsWith('.aidl')) {- return path.join(APP_MAIN_PREFIX, 'aidl', obj.targetDir.substring(4), path.basename(obj.src));- } else if (obj.targetDir.includes('libs')) {- if (obj.src.endsWith('.so')) {- return path.join(APP_MAIN_PREFIX, 'jniLibs', obj.targetDir.substring(5), path.basename(obj.src));- } else {+ } else {+ // Plugin using deprecated target directory structure (GH-580)+ if (obj.src.endsWith('.java')) {+ return path.join(APP_MAIN_PREFIX, 'java', obj.targetDir.replace(srcReg, ''),+ path.basename(obj.src));+ } else if (obj.src.endsWith('.aidl')) {+ return path.join(APP_MAIN_PREFIX, 'aidl', obj.targetDir.replace(srcReg, ''),+ path.basename(obj.src));+ } else if (libsReg.test(obj.targetDir)) {+ if (obj.src.endsWith('.so')) {+ return path.join(APP_MAIN_PREFIX, 'jniLibs', obj.targetDir.replace(libsReg, ''),+ path.basename(obj.src));+ } else {+ return path.join('app', obj.targetDir, path.basename(obj.src));+ }+ } else if (srcMainReg.test(obj.targetDir)) {return path.join('app', obj.targetDir, path.basename(obj.src));}- } else if (obj.targetDir.includes('src/main')) {- return path.join('app', obj.targetDir, path.basename(obj.src));- } else {+// For all other source files not using the new app directory structure,// add 'app/src/main' to the targetDirreturn path.join(APP_MAIN_PREFIX, obj.targetDir, path.basename(obj.src));}-}diff --git a/cordova/platforms/android/cordova/lib/prepare.js b/cordova/platforms/android/cordova/lib/prepare.jsindex ac63f8a68..6e8e92fe6 100644--- a/cordova/platforms/android/cordova/lib/prepare.js+++ b/cordova/platforms/android/cordova/lib/prepare.js@@ -16,12 +16,10 @@specific language governing permissions and limitationsunder the License.*/-/* eslint no-useless-escape: 0 */-var Q = require('q');-var fs = require('fs');+var fs = require('fs-extra');var path = require('path');-var shell = require('shelljs');+const nopt = require('nopt');var events = require('cordova-common').events;var AndroidManifest = require('./AndroidManifest');var checkReqs = require('./check_reqs');@@ -32,17 +30,58 @@ var FileUpdater = require('cordova-common').FileUpdater;var PlatformJson = require('cordova-common').PlatformJson;var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;var PluginInfoProvider = require('cordova-common').PluginInfoProvider;+const utils = require('./utils');++const GradlePropertiesParser = require('./config/GradlePropertiesParser');++function parseArguments (argv) {+ return nopt({+ // `jvmargs` is a valid option however, we don't actually want to parse it because we want the entire string as is.+ // jvmargs: String+ }, {}, argv || [], 0);+}module.exports.prepare = function (cordovaProject, options) {var self = this;+ let args = {};+ if (options && options.options) {+ args = parseArguments(options.options.argv);+ }+var platformJson = PlatformJson.load(this.locations.root, this.platform);var munger = new PlatformMunger(this.platform, this.locations.root, platformJson, new PluginInfoProvider());this._config = updateConfigFilesFrom(cordovaProject.projectConfig, munger, this.locations);+ // Get the min SDK version from config.xml+ const minSdkVersion = this._config.getPreference('android-minSdkVersion', 'android');+ const maxSdkVersion = this._config.getPreference('android-maxSdkVersion', 'android');+ const targetSdkVersion = this._config.getPreference('android-targetSdkVersion', 'android');+ const androidXEnabled = this._config.getPreference('AndroidXEnabled', 'android');+ const isGradlePluginKotlinEnabled = this._config.getPreference('GradlePluginKotlinEnabled', 'android');+ const gradlePluginKotlinCodeStyle = this._config.getPreference('GradlePluginKotlinCodeStyle', 'android');++ const gradlePropertiesUserConfig = {};+ if (minSdkVersion) gradlePropertiesUserConfig.cdvMinSdkVersion = minSdkVersion;+ if (maxSdkVersion) gradlePropertiesUserConfig.cdvMaxSdkVersion = maxSdkVersion;+ if (targetSdkVersion) gradlePropertiesUserConfig.cdvTargetSdkVersion = targetSdkVersion;+ if (args.jvmargs) gradlePropertiesUserConfig['org.gradle.jvmargs'] = args.jvmargs;+ if (isGradlePluginKotlinEnabled) {+ gradlePropertiesUserConfig['kotlin.code.style'] = gradlePluginKotlinCodeStyle || 'official';+ }++ // Both 'useAndroidX' and 'enableJetifier' are linked together.+ if (androidXEnabled) {+ gradlePropertiesUserConfig['android.useAndroidX'] = androidXEnabled;+ gradlePropertiesUserConfig['android.enableJetifier'] = androidXEnabled;+ }++ const gradlePropertiesParser = new GradlePropertiesParser(this.locations.root);+ gradlePropertiesParser.configure(gradlePropertiesUserConfig);+// Update own www dir with project's www assets and plugins' assets and js-files- return Q.when(updateWww(cordovaProject, this.locations)).then(function () {+ return Promise.resolve(updateWww(cordovaProject, this.locations)).then(function () {// update project according to config.xml changes.return updateProjectAccordingTo(self._config, self.locations);}).then(function () {@@ -62,13 +101,13 @@ module.exports.clean = function (options) {var projectRoot = path.resolve(this.root, '../..');if ((options && options.noPrepare) || !fs.existsSync(this.locations.configXml) ||!fs.existsSync(this.locations.configXml)) {- return Q();+ return Promise.resolve();}var projectConfig = new ConfigParser(this.locations.configXml);var self = this;- return Q().then(function () {+ return Promise.resolve().then(function () {cleanWww(projectRoot, self.locations);cleanIcons(projectRoot, projectConfig, path.relative(projectRoot, self.locations.res));cleanSplashes(projectRoot, projectConfig, path.relative(projectRoot, self.locations.res));@@ -95,7 +134,7 @@ function updateConfigFilesFrom (sourceConfig, configMunger, locations) {// First cleanup current config and merge project's one into own// Overwrite platform config.xml with defaults.xml.- shell.cp('-f', locations.defaultConfigXml, locations.configXml);+ fs.copySync(locations.defaultConfigXml, locations.configXml);// Then apply config changes from global munge to all config files// in project (including project's config)@@ -171,14 +210,14 @@ function updateProjectAccordingTo (platformConfig, locations) {var strings = xmlHelpers.parseElementtreeSync(locations.strings);var name = platformConfig.name();- strings.find('string[@name="app_name"]').text = name.replace(/\'/g, '\\\'');+ strings.find('string[@name="app_name"]').text = name.replace(/'/g, '\\\'');var shortName = platformConfig.shortName && platformConfig.shortName();if (shortName && shortName !== name) {- strings.find('string[@name="launcher_name"]').text = shortName.replace(/\'/g, '\\\'');+ strings.find('string[@name="launcher_name"]').text = shortName.replace(/'/g, '\\\'');}- fs.writeFileSync(locations.strings, strings.write({indent: 4}), 'utf-8');+ fs.writeFileSync(locations.strings, strings.write({ indent: 4 }), 'utf-8');events.emit('verbose', 'Wrote out android application name "' + name + '" to ' + locations.strings);// Java packages cannot support dashes@@ -194,15 +233,13 @@ function updateProjectAccordingTo (platformConfig, locations) {manifest.setVersionName(platformConfig.version()).setVersionCode(platformConfig.android_versionCode() || default_versionCode(platformConfig.version())).setPackageId(androidPkgName)- .setMinSdkVersion(platformConfig.getPreference('android-minSdkVersion', 'android'))- .setMaxSdkVersion(platformConfig.getPreference('android-maxSdkVersion', 'android'))- .setTargetSdkVersion(platformConfig.getPreference('android-targetSdkVersion', 'android')).write();// Java file paths shouldn't be hard coded- var javaPattern = path.join(locations.javaSrc, manifestId.replace(/\./g, '/'), '*.java');- var java_files = shell.ls(javaPattern).filter(function (f) {- return shell.grep(/extends\s+CordovaActivity/g, f);+ const javaDirectory = path.join(locations.javaSrc, manifestId.replace(/\./g, '/'));+ const javaPattern = /\.java$/;+ const java_files = utils.scanDirectory(javaDirectory, javaPattern, true).filter(function (f) {+ return utils.grep(f, /extends\s+CordovaActivity/g) !== null;});if (java_files.length === 0) {@@ -211,18 +248,24 @@ function updateProjectAccordingTo (platformConfig, locations) {events.emit('log', 'Multiple candidate Java files that extend CordovaActivity found. Guessing at the first one, ' + java_files[0]);}- var destFile = path.join(locations.root, 'app', 'src', 'main', 'java', androidPkgName.replace(/\./g, '/'), path.basename(java_files[0]));- shell.mkdir('-p', path.dirname(destFile));- shell.sed(/package [\w\.]*;/, 'package ' + androidPkgName + ';', java_files[0]).to(destFile);+ const destFile = java_files[0];++ // var destFile = path.join(locations.root, 'app', 'src', 'main', 'java', androidPkgName.replace(/\./g, '/'), path.basename(java_files[0]));+ // fs.ensureDirSync(path.dirname(destFile));+ // events.emit('verbose', java_files[0]);+ // events.emit('verbose', destFile);+ // console.log(locations);+ // fs.copySync(java_files[0], destFile);+ utils.replaceFileContents(destFile, /package [\w.]*;/, 'package ' + androidPkgName + ';');events.emit('verbose', 'Wrote out Android package name "' + androidPkgName + '" to ' + destFile);- var removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin() ?- manifestId.toUpperCase() !== androidPkgName.toUpperCase() :- manifestId !== androidPkgName;+ var removeOrigPkg = checkReqs.isWindows() || checkReqs.isDarwin()+ ? manifestId.toUpperCase() !== androidPkgName.toUpperCase()+ : manifestId !== androidPkgName;if (removeOrigPkg) {// If package was name changed we need to remove old java with main activity- shell.rm('-Rf', java_files[0]);+ fs.removeSync(java_files[0]);// remove any empty directoriesvar currentDir = path.dirname(java_files[0]);var sourcesRoot = path.resolve(locations.root, 'src');@@ -265,6 +308,14 @@ function getImageResourcePath (resourcesDir, type, density, name, sourceName) {return resourcePath;}+function getAdaptiveImageResourcePath (resourcesDir, type, density, name, sourceName) {+ if (/\.9\.png$/.test(sourceName)) {+ name = name.replace(/\.png$/, '.9.png');+ }+ var resourcePath = path.join(resourcesDir, (density ? type + '-' + density + '-v26' : type), name);+ return resourcePath;+}+function updateSplashes (cordovaProject, platformResourcesDir) {var resources = cordovaProject.projectConfig.getSplashScreens('android');@@ -314,20 +365,202 @@ function cleanSplashes (projectRoot, projectConfig, platformResourcesDir) {}function updateIcons (cordovaProject, platformResourcesDir) {- var icons = cordovaProject.projectConfig.getIcons('android');+ const icons = cordovaProject.projectConfig.getIcons('android');- // if there are icon elements in config.xml+ // Skip if there are no app defined icons in config.xmlif (icons.length === 0) {events.emit('verbose', 'This app does not have launcher icons defined');return;}- var resourceMap = mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'icon.png');+ // 1. loop icons determin if there is an error in the setup.+ // 2. during initial loop, also setup for legacy support.+ const errorMissingAttributes = [];+ const errorLegacyIconNeeded = [];+ let hasAdaptive = false;+ icons.forEach((icon, key) => {+ if (+ (icon.background && !icon.foreground) ||+ (!icon.background && icon.foreground) ||+ (!icon.background && !icon.foreground && !icon.src)+ ) {+ errorMissingAttributes.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width));+ }++ if (icon.foreground) {+ hasAdaptive = true;++ if (+ !icon.src &&+ (+ icon.foreground.startsWith('@color') ||+ path.extname(path.basename(icon.foreground)) === '.xml'+ )+ ) {+ errorLegacyIconNeeded.push(icon.density ? icon.density : 'size=' + (icon.height || icon.width));+ } else if (!icon.src) {+ icons[key].src = icon.foreground;+ }+ }+ });++ const errorMessage = [];+ if (errorMissingAttributes.length > 0) {+ errorMessage.push('One of the following attributes are set but missing the other for the density type: ' + errorMissingAttributes.join(', ') + '. Please ensure that all require attributes are defined.');+ }++ if (errorLegacyIconNeeded.length > 0) {+ errorMessage.push('For the following icons with the density of: ' + errorLegacyIconNeeded.join(', ') + ', adaptive foreground with a defined color or vector can not be used as a standard fallback icon for older Android devices. To support older Android environments, please provide a value for the src attribute.');+ }++ if (errorMessage.length > 0) {+ throw new CordovaError(errorMessage.join(' '));+ }++ let resourceMap = Object.assign(+ {},+ mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher.png'),+ mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.png'),+ mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_background.png'),+ mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.xml'),+ mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher_background.xml'),+ mapImageResources(cordovaProject.root, platformResourcesDir, 'mipmap', 'ic_launcher.xml')+ );++ const preparedIcons = prepareIcons(icons);++ if (hasAdaptive) {+ resourceMap = updateIconResourceForAdaptive(preparedIcons, resourceMap, platformResourcesDir);+ }++ resourceMap = updateIconResourceForLegacy(preparedIcons, resourceMap, platformResourcesDir);++ events.emit('verbose', 'Updating icons at ' + platformResourcesDir);+ FileUpdater.updatePaths(resourceMap, { rootDir: cordovaProject.root }, logFileOp);+}++function updateIconResourceForAdaptive (preparedIcons, resourceMap, platformResourcesDir) {+ const android_icons = preparedIcons.android_icons;+ const default_icon = preparedIcons.default_icon;++ // The source paths for icons and splashes are relative to+ // project's config.xml location, so we use it as base path.+ let background;+ let foreground;+ let targetPathBackground;+ let targetPathForeground;++ for (const density in android_icons) {+ let backgroundVal = '@mipmap/ic_launcher_background';+ let foregroundVal = '@mipmap/ic_launcher_foreground';++ background = android_icons[density].background;+ foreground = android_icons[density].foreground;++ if (!background || !foreground) {+ // This icon isn't an adaptive icon, so skip it+ continue;+ }++ if (background.startsWith('@color')) {+ // Colors Use Case+ backgroundVal = background; // Example: @color/background_foobar_1+ } else if (path.extname(path.basename(background)) === '.xml') {+ // Vector Use Case+ targetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_background.xml', path.basename(android_icons[density].background));+ resourceMap[targetPathBackground] = android_icons[density].background;+ } else if (path.extname(path.basename(background)) === '.png') {+ // Images Use Case+ targetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_background.png', path.basename(android_icons[density].background));+ resourceMap[targetPathBackground] = android_icons[density].background;+ }++ if (foreground.startsWith('@color')) {+ // Colors Use Case+ foregroundVal = foreground;+ } else if (path.extname(path.basename(foreground)) === '.xml') {+ // Vector Use Case+ targetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_foreground.xml', path.basename(android_icons[density].foreground));+ resourceMap[targetPathForeground] = android_icons[density].foreground;+ } else if (path.extname(path.basename(foreground)) === '.png') {+ // Images Use Case+ targetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher_foreground.png', path.basename(android_icons[density].foreground));+ resourceMap[targetPathForeground] = android_icons[density].foreground;+ }++ // create an XML for DPI and set color+ const icLauncherTemplate = `<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="` + backgroundVal + `" />+ <foreground android:drawable="` + foregroundVal + `" />+</adaptive-icon>`;++ const launcherXmlPath = path.join(platformResourcesDir, 'mipmap-' + density + '-v26', 'ic_launcher.xml');++ // Remove the XML from the resourceMap so the file does not get removed.+ delete resourceMap[launcherXmlPath];++ fs.writeFileSync(path.resolve(launcherXmlPath), icLauncherTemplate);+ }++ // There's no "default" drawable, so assume default == mdpi.+ if (default_icon && !android_icons.mdpi) {+ let defaultTargetPathBackground;+ let defaultTargetPathForeground;++ if (background.startsWith('@color')) {+ // Colors Use Case+ targetPathBackground = default_icon.background;+ } else if (path.extname(path.basename(background)) === '.xml') {+ // Vector Use Case+ defaultTargetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_background.xml', path.basename(default_icon.background));+ resourceMap[defaultTargetPathBackground] = default_icon.background;+ } else if (path.extname(path.basename(background)) === '.png') {+ // Images Use Case+ defaultTargetPathBackground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_background.png', path.basename(default_icon.background));+ resourceMap[defaultTargetPathBackground] = default_icon.background;+ }++ if (foreground.startsWith('@color')) {+ // Colors Use Case+ targetPathForeground = default_icon.foreground;+ } else if (path.extname(path.basename(foreground)) === '.xml') {+ // Vector Use Case+ defaultTargetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_foreground.xml', path.basename(default_icon.foreground));+ resourceMap[defaultTargetPathForeground] = default_icon.foreground;+ } else if (path.extname(path.basename(foreground)) === '.png') {+ // Images Use Case+ defaultTargetPathForeground = getAdaptiveImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher_foreground.png', path.basename(default_icon.foreground));+ resourceMap[defaultTargetPathForeground] = default_icon.foreground;+ }+ }++ return resourceMap;+}++function updateIconResourceForLegacy (preparedIcons, resourceMap, platformResourcesDir) {+ const android_icons = preparedIcons.android_icons;+ const default_icon = preparedIcons.default_icon;- var android_icons = {};- var default_icon;+ // The source paths for icons and splashes are relative to+ // project's config.xml location, so we use it as base path.+ for (var density in android_icons) {+ var targetPath = getImageResourcePath(platformResourcesDir, 'mipmap', density, 'ic_launcher.png', path.basename(android_icons[density].src));+ resourceMap[targetPath] = android_icons[density].src;+ }++ // There's no "default" drawable, so assume default == mdpi.+ if (default_icon && !android_icons.mdpi) {+ var defaultTargetPath = getImageResourcePath(platformResourcesDir, 'mipmap', 'mdpi', 'ic_launcher.png', path.basename(default_icon.src));+ resourceMap[defaultTargetPath] = default_icon.src;+ }++ return resourceMap;+}++function prepareIcons (icons) {// http://developer.android.com/design/style/iconography.html- var sizeToDensityMap = {+ const SIZE_TO_DENSITY_MAP = {36: 'ldpi',48: 'mdpi',72: 'hdpi',@@ -335,11 +568,15 @@ function updateIcons (cordovaProject, platformResourcesDir) {144: 'xxhdpi',192: 'xxxhdpi'};++ const android_icons = {};+ let default_icon;+// find the best matching icon for a given density or size// @output android_iconsvar parseIcon = function (icon, icon_size) {// do I have a platform icon for that density already- var density = icon.density || sizeToDensityMap[icon_size];+ var density = icon.density || SIZE_TO_DENSITY_MAP[icon_size];if (!density) {// invalid icon defition ( or unsupported size)return;@@ -355,12 +592,34 @@ function updateIcons (cordovaProject, platformResourcesDir) {for (var i = 0; i < icons.length; i++) {var icon = icons[i];var size = icon.width;+if (!size) {size = icon.height;}+if (!size && !icon.density) {if (default_icon) {- events.emit('verbose', 'Found extra default icon: ' + icon.src + ' (ignoring in favor of ' + default_icon.src + ')');+ const found = {};+ const favor = {};++ // populating found icon.+ if (icon.background && icon.foreground) {+ found.background = icon.background;+ found.foreground = icon.foreground;+ }+ if (icon.src) {+ found.src = icon.src;+ }++ if (default_icon.background && default_icon.foreground) {+ favor.background = default_icon.background;+ favor.foreground = default_icon.foreground;+ }+ if (default_icon.src) {+ favor.src = default_icon.src;+ }++ events.emit('verbose', 'Found extra default icon: ' + JSON.stringify(found) + ' and ignoring in favor of ' + JSON.stringify(favor) + '.');} else {default_icon = icon;}@@ -369,45 +628,45 @@ function updateIcons (cordovaProject, platformResourcesDir) {}}- // The source paths for icons and splashes are relative to- // project's config.xml location, so we use it as base path.- for (var density in android_icons) {- var targetPath = getImageResourcePath(- platformResourcesDir, 'mipmap', density, 'icon.png', path.basename(android_icons[density].src));- resourceMap[targetPath] = android_icons[density].src;- }-- // There's no "default" drawable, so assume default == mdpi.- if (default_icon && !android_icons.mdpi) {- var defaultTargetPath = getImageResourcePath(- platformResourcesDir, 'mipmap', 'mdpi', 'icon.png', path.basename(default_icon.src));- resourceMap[defaultTargetPath] = default_icon.src;- }-- events.emit('verbose', 'Updating icons at ' + platformResourcesDir);- FileUpdater.updatePaths(- resourceMap, { rootDir: cordovaProject.root }, logFileOp);+ return {+ android_icons: android_icons,+ default_icon: default_icon+ };}function cleanIcons (projectRoot, projectConfig, platformResourcesDir) {var icons = projectConfig.getIcons('android');- if (icons.length > 0) {- var resourceMap = mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'icon.png');- events.emit('verbose', 'Cleaning icons at ' + platformResourcesDir);- // No source paths are specified in the map, so updatePaths() will delete the target files.- FileUpdater.updatePaths(- resourceMap, { rootDir: projectRoot, all: true }, logFileOp);+ // Skip if there are no app defined icons in config.xml+ if (icons.length === 0) {+ events.emit('verbose', 'This app does not have launcher icons defined');+ return;}++ const resourceMap = Object.assign(+ {},+ mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher.png'),+ mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.png'),+ mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_background.png'),+ mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_foreground.xml'),+ mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher_background.xml'),+ mapImageResources(projectRoot, platformResourcesDir, 'mipmap', 'ic_launcher.xml')+ );++ events.emit('verbose', 'Cleaning icons at ' + platformResourcesDir);++ // No source paths are specified in the map, so updatePaths() will delete the target files.+ FileUpdater.updatePaths(resourceMap, { rootDir: projectRoot, all: true }, logFileOp);}/*** Gets a map containing resources of a specified name from all drawable folders in a directory.*/function mapImageResources (rootDir, subDir, type, resourceName) {- var pathMap = {};- shell.ls(path.join(rootDir, subDir, type + '-*')).forEach(function (drawableFolder) {- var imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);+ const pathMap = {};+ const pattern = new RegExp(type + '+-.+');+ utils.scanDirectory(path.join(rootDir, subDir), pattern).forEach(function (drawableFolder) {+ const imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);pathMap[imagePath] = null;});return pathMap;@@ -445,8 +704,7 @@ function cleanFileResources (projectRoot, projectConfig, platformDir) {});FileUpdater.updatePaths(- resourceMap, {- rootDir: projectRoot, all: true}, logFileOp);+ resourceMap, { rootDir: projectRoot, all: true }, logFileOp);}}diff --git a/cordova/platforms/android/cordova/lib/retry.js b/cordova/platforms/android/cordova/lib/retry.jsindex c464b9d5f..6ce8e818b 100644--- a/cordova/platforms/android/cordova/lib/retry.js+++ b/cordova/platforms/android/cordova/lib/retry.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,8 +17,6 @@under the License.*/-/* jshint node: true */-'use strict';var events = require('cordova-common').events;@@ -29,21 +25,19 @@ var events = require('cordova-common').events;* Retry a promise-returning function a number of times, propagating its* results on success or throwing its error on a failed final attempt.*- * @arg {Number} attemts_left - The number of times to retry the passed call.+ * @arg {Number} attemptsLeft - The number of times to retry the passed call.* @arg {Function} promiseFunction - A function that returns a promise.* @arg {...} - Arguments to pass to promiseFunction.** @returns {Promise}*/-module.exports.retryPromise = function (attemts_left, promiseFunction) {-+module.exports.retryPromise = function (attemptsLeft, promiseFunction) {// NOTE:- // get all trailing arguments, by skipping the first two (attemts_left and+ // get all trailing arguments, by skipping the first two (attemptsLeft and// promiseFunction) because they shouldn't get passed to promiseFunctionvar promiseFunctionArguments = Array.prototype.slice.call(arguments, 2);return promiseFunction.apply(undefined, promiseFunctionArguments).then(-// on success pass results throughfunction onFulfilled (value) {return value;@@ -51,17 +45,16 @@ module.exports.retryPromise = function (attemts_left, promiseFunction) {// on rejection either retry, or throw the errorfunction onRejected (error) {+ attemptsLeft -= 1;- attemts_left -= 1;-- if (attemts_left < 1) {+ if (attemptsLeft < 1) {throw error;}- events.emit('verbose', 'A retried call failed. Retrying ' + attemts_left + ' more time(s).');+ events.emit('verbose', 'A retried call failed. Retrying ' + attemptsLeft + ' more time(s).');- // retry call self again with the same arguments, except attemts_left is now lower- var fullArguments = [attemts_left, promiseFunction].concat(promiseFunctionArguments);+ // retry call self again with the same arguments, except attemptsLeft is now lower+ var fullArguments = [attemptsLeft, promiseFunction].concat(promiseFunctionArguments);return module.exports.retryPromise.apply(undefined, fullArguments);});diff --git a/cordova/platforms/android/cordova/lib/run.js b/cordova/platforms/android/cordova/lib/run.jsindex 4d7927ced..892e9b0ca 100644--- a/cordova/platforms/android/cordova/lib/run.js+++ b/cordova/platforms/android/cordova/lib/run.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,14 +17,11 @@under the License.*/-/* jshint loopfunc:true */-var path = require('path');-var build = require('./build');var emulator = require('./emulator');var device = require('./device');-var Q = require('q');-var events = require('cordova-common').events;+var PackageType = require('./PackageType');+const { CordovaError, events } = require('cordova-common');function getInstallTarget (runOptions) {var install_target;@@ -52,11 +47,12 @@ function getInstallTarget (runOptions) {* @return {Promise}*/module.exports.run = function (runOptions) {+ runOptions = runOptions || {};var self = this;var install_target = getInstallTarget(runOptions);- return Q().then(function () {+ return Promise.resolve().then(function () {if (!install_target) {// no target given, deploy to device if available, otherwise use the emulator.return device.list().then(function (device_list) {@@ -98,21 +94,30 @@ module.exports.run = function (runOptions) {});}}- return Q.reject('Target \'' + install_target + '\' not found, unable to run project');+ return Promise.reject(new CordovaError(`Target '${install_target}' not found, unable to run project`));});});});}).then(function (resolvedTarget) {- // Better just call self.build, but we're doing some processing of- // build results (according to platformApi spec) so they are in different- // format than emulator.install expects.- // TODO: Update emulator/device.install to handle this change- return build.run.call(self, runOptions, resolvedTarget).then(function (buildResults) {+ return new Promise((resolve) => {+ const builder = require('./builders/builders').getBuilder();+ const buildOptions = require('./build').parseBuildOptions(runOptions, null, self.root);++ // Android app bundles cannot be deployed directly to the device+ if (buildOptions.packageType === PackageType.BUNDLE) {+ const packageTypeErrorMessage = 'Package type "bundle" is not supported during cordova run.';+ events.emit('error', packageTypeErrorMessage);+ throw packageTypeErrorMessage;+ }++ resolve(builder.fetchBuildResults(buildOptions.buildType, buildOptions.arch));+ }).then(function (buildResults) {if (resolvedTarget && resolvedTarget.isEmulator) {return emulator.wait_for_boot(resolvedTarget.target).then(function () {return emulator.install(resolvedTarget, buildResults);});}+return device.install(resolvedTarget, buildResults);});});diff --git a/cordova/platforms/android/cordova/lib/start-emulator b/cordova/platforms/android/cordova/lib/start-emulatorindex f96bdc3ef..20c92b70b 100755--- a/cordova/platforms/android/cordova/lib/start-emulator+++ b/cordova/platforms/android/cordova/lib/start-emulator@@ -19,21 +19,20 @@under the License.*/-var emulator = require('./emulator'),- args = process.argv;+var emulator = require('./emulator');+var args = process.argv;var install_target;-if(args.length > 2) {- if (args[2].substring(0, 9) == '--target=') {+if (args.length > 2) {+ if (args[2].substring(0, 9) === '--target=') {install_target = args[2].substring(9, args[2].length);- } else {+ } else {console.error('ERROR : argument \'' + args[2] + '\' not recognized.');process.exit(2);- }+ }}-emulator.start(install_target).done(null, function(err) {+emulator.start(install_target).catch(function (err) {console.error('ERROR: ' + err);process.exit(2);});-diff --git a/cordova/platforms/android/cordova/lib/start-emulator.bat b/cordova/platforms/android/cordova/lib/start-emulator.batindex 6c237ea2a..bf341b72c 100644--- a/cordova/platforms/android/cordova/lib/start-emulator.bat+++ b/cordova/platforms/android/cordova/lib/start-emulator.bat@@ -5,9 +5,9 @@:: to you under the Apache License, Version 2.0 (the:: "License"); you may not use this file except in compliance:: with the License. You may obtain a copy of the License at-::+:::: http://www.apache.org/licenses/LICENSE-2.0-::+:::: Unless required by applicable law or agreed to in writing,:: software distributed under the License is distributed on an:: "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -23,4 +23,4 @@ IF EXIST %script_path% (ECHO.ECHO ERROR: Could not find 'start-emulator' script in 'cordova\lib' folder, aborting...>&2EXIT /B 1-)\ No newline at end of file+)diff --git a/cordova/platforms/android/cordova/lib/utils.js b/cordova/platforms/android/cordova/lib/utils.jsnew file mode 100644index 000000000..760eda604--- /dev/null+++ b/cordova/platforms/android/cordova/lib/utils.js@@ -0,0 +1,97 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++/*+ Provides a set of utility methods, which can also be spied on during unit tests.+*/++// TODO: Perhaps this should live in cordova-common?++const fs = require('fs-extra');+const path = require('path');++/**+ * Reads, searches, and replaces the found occurences with replacementString and then writes the file back out.+ * A backup is not made.+ *+ * @param {string} file A file path to a readable & writable file+ * @param {RegExp} searchRegex The search regex+ * @param {string} replacementString The string to replace the found occurences+ * @returns void+ */+exports.replaceFileContents = function (file, searchRegex, replacementString) {+ let contents = fs.readFileSync(file).toString();+ contents = contents.replace(searchRegex, replacementString);+ fs.writeFileSync(file, contents);+};++/**+ * Reads a file and scans for regex. Returns the line of the first occurence or null if no occurences are found.+ *+ * @param {string} file A file path+ * @param {RegExp} regex A search regex+ * @returns string|null+ */+exports.grep = function (file, regex) {+ const contents = fs.readFileSync(file).toString().replace(/\\r/g, '').split('\n');+ for (let i = 0; i < contents.length; i++) {+ const line = contents[i];+ if (regex.test(line)) {+ return line;+ }+ }+ return null;+};++/**+ * Scans directories and outputs a list of found paths that matches the regex+ *+ * @param {string} directory The starting directory+ * @param {RegExp} regex The search regex+ * @param {boolean} recursive Enables recursion+ * @returns Array<string>+ */+exports.scanDirectory = function (directory, regex, recursive) {+ let output = [];++ if (fs.existsSync(directory)) {+ const items = fs.readdirSync(directory);++ for (let i = 0; i < items.length; i++) {+ const item = items[i];+ const itemPath = path.join(directory, item);+ const stats = fs.statSync(itemPath);++ if (regex.test(itemPath)) {+ output.push(itemPath);+ }++ if (stats.isDirectory()) {+ if (recursive) {+ output = output.concat(exports.scanDirectory(itemPath, regex, recursive));+ } else {+ // Move onto the next item+ continue;+ }+ }+ }+ }++ return output;+};diff --git a/cordova/platforms/android/cordova/log b/cordova/platforms/android/cordova/logindex 47f060505..216c8d767 100755--- a/cordova/platforms/android/cordova/log+++ b/cordova/platforms/android/cordova/log@@ -19,17 +19,17 @@under the License.*/-var log = require('./lib/log'),- reqs = require('./lib/check_reqs'),- args = process.argv;+var log = require('./lib/log');+var reqs = require('./lib/check_reqs');+var args = process.argv;// Usage support for when args are given-if(args.length > 2) {+if (args.length > 2) {log.help();} else {- reqs.run().done(function() {+ reqs.run().then(function () {return log.run();- }, function(err) {+ }, function (err) {console.error('ERROR: ' + err);process.exit(2);});diff --git a/cordova/platforms/android/cordova/run b/cordova/platforms/android/cordova/runindex 9544c1dcf..2e7efe269 100755--- a/cordova/platforms/android/cordova/run+++ b/cordova/platforms/android/cordova/run@@ -24,22 +24,23 @@ var nopt = require('nopt');var path = require('path');// Support basic help commands-if(['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0)+if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >= 0) {require('./lib/run').help();+}// Do some basic argument parsingvar runOpts = nopt({- 'verbose' : Boolean,- 'silent' : Boolean,- 'debug' : Boolean,- 'release' : Boolean,- 'nobuild': Boolean,- 'buildConfig' : path,- 'archs' : String,- 'device' : Boolean,- 'emulator': Boolean,- 'target' : String-}, { 'd' : '--verbose' });+ verbose: Boolean,+ silent: Boolean,+ debug: Boolean,+ release: Boolean,+ nobuild: Boolean,+ buildConfig: path,+ archs: String,+ device: Boolean,+ emulator: Boolean,+ target: String+}, { d: '--verbose' });// Make runOptions compatible with PlatformApi run method specrunOpts.argv = runOpts.argv.remain;@@ -47,7 +48,7 @@ runOpts.argv = runOpts.argv.remain;require('./loggingHelper').adjustLoggerLevel(runOpts);new Api().run(runOpts)-.catch(function(err) {- console.error(err, err.stack);- process.exit(2);-});+ .catch(function (err) {+ console.error(err, err.stack);+ process.exit(2);+ });diff --git a/cordova/platforms/android/cordova/version b/cordova/platforms/android/cordova/versionindex 42d31ce6d..00f44bbb7 100755--- a/cordova/platforms/android/cordova/version+++ b/cordova/platforms/android/cordova/version@@ -19,11 +19,6 @@under the License.*/-// Coho updates this line:-var VERSION = "7.1.4";+const Api = require('./Api');-module.exports.version = VERSION;--if (!module.parent) {- console.log(VERSION);-}+console.log(Api.version());diff --git a/cordova/platforms/android/gradle.properties b/cordova/platforms/android/gradle.propertiesnew file mode 100644index 000000000..821729695--- /dev/null+++ b/cordova/platforms/android/gradle.properties@@ -0,0 +1,5 @@+org.gradle.daemon=true+org.gradle.jvmargs=-Xmx2048m+android.useAndroidX=false+android.enableJetifier=false+cdvMinSdkVersion=23diff --git a/cordova/platforms/android/gradle/wrapper/gradle-wrapper.properties b/cordova/platforms/android/gradle/wrapper/gradle-wrapper.propertiesindex 45d84399a..4154807e5 100644--- a/cordova/platforms/android/gradle/wrapper/gradle-wrapper.properties+++ b/cordova/platforms/android/gradle/wrapper/gradle-wrapper.properties@@ -1,5 +1,5 @@distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/dists-distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip+distributionUrl=https://services.gradle.org/distributions/gradle-6.5-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsdiff --git a/cordova/platforms/android/platform_www/cordova-js-src/android/nativeapiprovider.js b/cordova/platforms/android/platform_www/cordova-js-src/android/nativeapiprovider.jsindex 2e9aa67bb..44f4aacf3 100644--- a/cordova/platforms/android/platform_www/cordova-js-src/android/nativeapiprovider.js+++ b/cordova/platforms/android/platform_www/cordova-js-src/android/nativeapiprovider.js@@ -25,12 +25,12 @@ var nativeApi = this._cordovaNative || require('cordova/android/promptbasednativvar currentApi = nativeApi;module.exports = {- get: function() { return currentApi; },- setPreferPrompt: function(value) {+ get: function () { return currentApi; },+ setPreferPrompt: function (value) {currentApi = value ? require('cordova/android/promptbasednativeapi') : nativeApi;},// Used only by tests.- set: function(value) {+ set: function (value) {currentApi = value;}};diff --git a/cordova/platforms/android/platform_www/cordova-js-src/android/promptbasednativeapi.js b/cordova/platforms/android/platform_www/cordova-js-src/android/promptbasednativeapi.jsindex f7fb6bc7f..86fc1d9fe 100644--- a/cordova/platforms/android/platform_www/cordova-js-src/android/promptbasednativeapi.js+++ b/cordova/platforms/android/platform_www/cordova-js-src/android/promptbasednativeapi.js@@ -23,13 +23,13 @@*/module.exports = {- exec: function(bridgeSecret, service, action, callbackId, argsJson) {- return prompt(argsJson, 'gap:'+JSON.stringify([bridgeSecret, service, action, callbackId]));+ exec: function (bridgeSecret, service, action, callbackId, argsJson) {+ return prompt(argsJson, 'gap:' + JSON.stringify([bridgeSecret, service, action, callbackId]));},- setNativeToJsBridgeMode: function(bridgeSecret, value) {+ setNativeToJsBridgeMode: function (bridgeSecret, value) {prompt(value, 'gap_bridge_mode:' + bridgeSecret);},- retrieveJsMessages: function(bridgeSecret, fromOnlineEvent) {+ retrieveJsMessages: function (bridgeSecret, fromOnlineEvent) {return prompt(+fromOnlineEvent, 'gap_poll:' + bridgeSecret);}};diff --git a/cordova/platforms/android/platform_www/cordova-js-src/exec.js b/cordova/platforms/android/platform_www/cordova-js-src/exec.jsindex 39e8c97ee..c98212ee2 100644--- a/cordova/platforms/android/platform_www/cordova-js-src/exec.js+++ b/cordova/platforms/android/platform_www/cordova-js-src/exec.js@@ -33,38 +33,38 @@* @param {String} action Action to be run in cordova* @param {String[]} [args] Zero or more arguments to pass to the method*/-var cordova = require('cordova'),- nativeApiProvider = require('cordova/android/nativeapiprovider'),- utils = require('cordova/utils'),- base64 = require('cordova/base64'),- channel = require('cordova/channel'),- jsToNativeModes = {- PROMPT: 0,- JS_OBJECT: 1- },- nativeToJsModes = {- // Polls for messages using the JS->Native bridge.- POLLING: 0,- // For LOAD_URL to be viable, it would need to have a work-around for- // the bug where the soft-keyboard gets dismissed when a message is sent.- LOAD_URL: 1,- // For the ONLINE_EVENT to be viable, it would need to intercept all event- // listeners (both through addEventListener and window.ononline) as well- // as set the navigator property itself.- ONLINE_EVENT: 2,- EVAL_BRIDGE: 3- },- jsToNativeBridgeMode, // Set lazily.- nativeToJsBridgeMode = nativeToJsModes.EVAL_BRIDGE,- pollEnabled = false,- bridgeSecret = -1;+var cordova = require('cordova');+var nativeApiProvider = require('cordova/android/nativeapiprovider');+var utils = require('cordova/utils');+var base64 = require('cordova/base64');+var channel = require('cordova/channel');+var jsToNativeModes = {+ PROMPT: 0,+ JS_OBJECT: 1+};+var nativeToJsModes = {+ // Polls for messages using the JS->Native bridge.+ POLLING: 0,+ // For LOAD_URL to be viable, it would need to have a work-around for+ // the bug where the soft-keyboard gets dismissed when a message is sent.+ LOAD_URL: 1,+ // For the ONLINE_EVENT to be viable, it would need to intercept all event+ // listeners (both through addEventListener and window.ononline) as well+ // as set the navigator property itself.+ ONLINE_EVENT: 2,+ EVAL_BRIDGE: 3+};+var jsToNativeBridgeMode; // Set lazily.+var nativeToJsBridgeMode = nativeToJsModes.EVAL_BRIDGE;+var pollEnabled = false;+var bridgeSecret = -1;var messagesFromNative = [];var isProcessing = false;-var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();-var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };+var resolvedPromise = typeof Promise === 'undefined' ? null : Promise.resolve();+var nextTick = resolvedPromise ? function (fn) { resolvedPromise.then(fn); } : function (fn) { setTimeout(fn); };-function androidExec(success, fail, service, action, args) {+function androidExec (success, fail, service, action, args) {if (bridgeSecret < 0) {// If we ever catch this firing, we'll need to queue up exec()s// and fire them once we get a secret. For now, I don't think@@ -83,21 +83,21 @@ function androidExec(success, fail, service, action, args) {// Process any ArrayBuffers in the args into a string.for (var i = 0; i < args.length; i++) {- if (utils.typeName(args[i]) == 'ArrayBuffer') {+ if (utils.typeName(args[i]) === 'ArrayBuffer') {args[i] = base64.fromArrayBuffer(args[i]);}}- var callbackId = service + cordova.callbackId++,- argsJson = JSON.stringify(args);+ var callbackId = service + cordova.callbackId++;+ var argsJson = JSON.stringify(args);if (success || fail) {- cordova.callbacks[callbackId] = {success:success, fail:fail};+ cordova.callbacks[callbackId] = { success: success, fail: fail };}var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);// If argsJson was received by Java as null, try again with the PROMPT bridge mode.// This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.- if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "@Null arguments.") {+ if (jsToNativeBridgeMode === jsToNativeModes.JS_OBJECT && msgs === '@Null arguments.') {androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);androidExec(success, fail, service, action, args);androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);@@ -108,16 +108,16 @@ function androidExec(success, fail, service, action, args) {}}-androidExec.init = function() {+androidExec.init = function () {bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode);channel.onNativeReady.fire();};-function pollOnceFromOnlineEvent() {+function pollOnceFromOnlineEvent () {pollOnce(true);}-function pollOnce(opt_fromOnlineEvent) {+function pollOnce (opt_fromOnlineEvent) {if (bridgeSecret < 0) {// This can happen when the NativeToJsMessageQueue resets the online state on page transitions.// We know there's nothing to retrieve, so no need to poll.@@ -131,15 +131,15 @@ function pollOnce(opt_fromOnlineEvent) {}}-function pollingTimerFunc() {+function pollingTimerFunc () {if (pollEnabled) {pollOnce();setTimeout(pollingTimerFunc, 50);}}-function hookOnlineApis() {- function proxyEvent(e) {+function hookOnlineApis () {+ function proxyEvent (e) {cordova.fireWindowEvent(e.type);}// The network module takes care of firing online and offline events.@@ -159,19 +159,19 @@ hookOnlineApis();androidExec.jsToNativeModes = jsToNativeModes;androidExec.nativeToJsModes = nativeToJsModes;-androidExec.setJsToNativeBridgeMode = function(mode) {- if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) {+androidExec.setJsToNativeBridgeMode = function (mode) {+ if (mode === jsToNativeModes.JS_OBJECT && !window._cordovaNative) {mode = jsToNativeModes.PROMPT;}- nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT);+ nativeApiProvider.setPreferPrompt(mode === jsToNativeModes.PROMPT);jsToNativeBridgeMode = mode;};-androidExec.setNativeToJsBridgeMode = function(mode) {- if (mode == nativeToJsBridgeMode) {+androidExec.setNativeToJsBridgeMode = function (mode) {+ if (mode === nativeToJsBridgeMode) {return;}- if (nativeToJsBridgeMode == nativeToJsModes.POLLING) {+ if (nativeToJsBridgeMode === nativeToJsModes.POLLING) {pollEnabled = false;}@@ -182,32 +182,32 @@ androidExec.setNativeToJsBridgeMode = function(mode) {nativeApiProvider.get().setNativeToJsBridgeMode(bridgeSecret, mode);}- if (mode == nativeToJsModes.POLLING) {+ if (mode === nativeToJsModes.POLLING) {pollEnabled = true;setTimeout(pollingTimerFunc, 1);}};-function buildPayload(payload, message) {+function buildPayload (payload, message) {var payloadKind = message.charAt(0);- if (payloadKind == 's') {+ if (payloadKind === 's') {payload.push(message.slice(1));- } else if (payloadKind == 't') {+ } else if (payloadKind === 't') {payload.push(true);- } else if (payloadKind == 'f') {+ } else if (payloadKind === 'f') {payload.push(false);- } else if (payloadKind == 'N') {+ } else if (payloadKind === 'N') {payload.push(null);- } else if (payloadKind == 'n') {+ } else if (payloadKind === 'n') {payload.push(+message.slice(1));- } else if (payloadKind == 'A') {+ } else if (payloadKind === 'A') {var data = message.slice(1);payload.push(base64.toArrayBuffer(data));- } else if (payloadKind == 'S') {+ } else if (payloadKind === 'S') {payload.push(window.atob(message.slice(1)));- } else if (payloadKind == 'M') {+ } else if (payloadKind === 'M') {var multipartMessages = message.slice(1);- while (multipartMessages !== "") {+ while (multipartMessages !== '') {var spaceIdx = multipartMessages.indexOf(' ');var msgLen = +multipartMessages.slice(0, spaceIdx);var multipartMessage = multipartMessages.substr(spaceIdx + 1, msgLen);@@ -220,14 +220,15 @@ function buildPayload(payload, message) {}// Processes a single message, as encoded by NativeToJsMessageQueue.java.-function processMessage(message) {+function processMessage (message) {var firstChar = message.charAt(0);- if (firstChar == 'J') {+ if (firstChar === 'J') {// This is deprecated on the .java side. It doesn't work with CSP enabled.+ // eslint-disable-next-line no-evaleval(message.slice(1));- } else if (firstChar == 'S' || firstChar == 'F') {- var success = firstChar == 'S';- var keepCallback = message.charAt(1) == '1';+ } else if (firstChar === 'S' || firstChar === 'F') {+ var success = firstChar === 'S';+ var keepCallback = message.charAt(1) === '1';var spaceIdx = message.indexOf(' ', 2);var status = +message.slice(2, spaceIdx);var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);@@ -237,11 +238,11 @@ function processMessage(message) {buildPayload(payload, payloadMessage);cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);} else {- console.log("processMessage failed: invalid message: " + JSON.stringify(message));+ console.log('processMessage failed: invalid message: ' + JSON.stringify(message));}}-function processMessages() {+function processMessages () {// Check for the reentrant case.if (isProcessing) {return;@@ -254,7 +255,7 @@ function processMessages() {var msg = popMessageFromQueue();// The Java side can send a * message to indicate that it// still has messages waiting to be retrieved.- if (msg == '*' && messagesFromNative.length === 0) {+ if (msg === '*' && messagesFromNative.length === 0) {nextTick(pollOnce);return;}@@ -267,9 +268,9 @@ function processMessages() {}}-function popMessageFromQueue() {+function popMessageFromQueue () {var messageBatch = messagesFromNative.shift();- if (messageBatch == '*') {+ if (messageBatch === '*') {return '*';}diff --git a/cordova/platforms/android/platform_www/cordova-js-src/platform.js b/cordova/platforms/android/platform_www/cordova-js-src/platform.jsindex 2bfd02471..14eddd7f7 100644--- a/cordova/platforms/android/platform_www/cordova-js-src/platform.js+++ b/cordova/platforms/android/platform_www/cordova-js-src/platform.js@@ -24,11 +24,11 @@ var lastResumeEvent = null;module.exports = {id: 'android',- bootstrap: function() {- var channel = require('cordova/channel'),- cordova = require('cordova'),- exec = require('cordova/exec'),- modulemapper = require('cordova/modulemapper');+ bootstrap: function () {+ var channel = require('cordova/channel');+ var cordova = require('cordova');+ var exec = require('cordova/exec');+ var modulemapper = require('cordova/modulemapper');// Get the shared secret needed to use the bridge.exec.init();@@ -40,21 +40,21 @@ module.exports = {// Inject a listener for the backbutton on the document.var backButtonChannel = cordova.addDocumentEventHandler('backbutton');- backButtonChannel.onHasSubscribersChange = function() {+ backButtonChannel.onHasSubscribersChange = function () {// If we just attached the first handler or detached the last handler,// let native know we need to override the back button.- exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [this.numHandlers == 1]);+ exec(null, null, APP_PLUGIN_NAME, 'overrideBackbutton', [this.numHandlers === 1]);};// Add hardware MENU and SEARCH button handlerscordova.addDocumentEventHandler('menubutton');cordova.addDocumentEventHandler('searchbutton');- function bindButtonChannel(buttonName) {+ function bindButtonChannel (buttonName) {// generic button bind used for volumeup/volumedown buttonsvar volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button');- volumeButtonChannel.onHasSubscribersChange = function() {- exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]);+ volumeButtonChannel.onHasSubscribersChange = function () {+ exec(null, null, APP_PLUGIN_NAME, 'overrideButton', [buttonName, this.numHandlers === 1]);};}// Inject a listener for the volume buttons on the document.@@ -66,7 +66,7 @@ module.exports = {// plugin result is delivered even after the event is fired (CB-10498)var cordovaAddEventListener = document.addEventListener;- document.addEventListener = function(evt, handler, capture) {+ document.addEventListener = function (evt, handler, capture) {cordovaAddEventListener(evt, handler, capture);if (evt === 'resume' && lastResumeEvent) {@@ -76,50 +76,47 @@ module.exports = {// Let native code know we are all done on the JS side.// Native code will then un-hide the WebView.- channel.onCordovaReady.subscribe(function() {+ channel.onCordovaReady.subscribe(function () {exec(onMessageFromNative, null, APP_PLUGIN_NAME, 'messageChannel', []);- exec(null, null, APP_PLUGIN_NAME, "show", []);+ exec(null, null, APP_PLUGIN_NAME, 'show', []);});}};-function onMessageFromNative(msg) {+function onMessageFromNative (msg) {var cordova = require('cordova');var action = msg.action;- switch (action)- {- // Button events- case 'backbutton':- case 'menubutton':- case 'searchbutton':- // App life cycle events- case 'pause':- // Volume events- case 'volumedownbutton':- case 'volumeupbutton':- cordova.fireDocumentEvent(action);- break;- case 'resume':- if(arguments.length > 1 && msg.pendingResult) {- if(arguments.length === 2) {- msg.pendingResult.result = arguments[1];- } else {- // The plugin returned a multipart message- var res = [];- for(var i = 1; i < arguments.length; i++) {- res.push(arguments[i]);- }- msg.pendingResult.result = res;+ switch (action) {+ // pause and resume are Android app life cycle events+ case 'backbutton':+ case 'menubutton':+ case 'searchbutton':+ case 'pause':+ case 'volumedownbutton':+ case 'volumeupbutton':+ cordova.fireDocumentEvent(action);+ break;+ case 'resume':+ if (arguments.length > 1 && msg.pendingResult) {+ if (arguments.length === 2) {+ msg.pendingResult.result = arguments[1];+ } else {+ // The plugin returned a multipart message+ var res = [];+ for (var i = 1; i < arguments.length; i++) {+ res.push(arguments[i]);}-- // Save the plugin result so that it can be delivered to the js- // even if they miss the initial firing of the event- lastResumeEvent = msg;+ msg.pendingResult.result = res;}- cordova.fireDocumentEvent(action, msg);- break;- default:- throw new Error('Unknown event action ' + action);++ // Save the plugin result so that it can be delivered to the js+ // even if they miss the initial firing of the event+ lastResumeEvent = msg;+ }+ cordova.fireDocumentEvent(action, msg);+ break;+ default:+ throw new Error('Unknown event action ' + action);}}diff --git a/cordova/platforms/android/platform_www/cordova-js-src/plugin/android/app.js b/cordova/platforms/android/platform_www/cordova-js-src/plugin/android/app.jsindex 22cf96e81..027ce31b1 100644--- a/cordova/platforms/android/platform_www/cordova-js-src/plugin/android/app.js+++ b/cordova/platforms/android/platform_www/cordova-js-src/plugin/android/app.js@@ -26,8 +26,8 @@ module.exports = {/*** Clear the resource cache.*/- clearCache:function() {- exec(null, null, APP_PLUGIN_NAME, "clearCache", []);+ clearCache: function () {+ exec(null, null, APP_PLUGIN_NAME, 'clearCache', []);},/**@@ -44,31 +44,31 @@ module.exports = {* Example:* navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});*/- loadUrl:function(url, props) {- exec(null, null, APP_PLUGIN_NAME, "loadUrl", [url, props]);+ loadUrl: function (url, props) {+ exec(null, null, APP_PLUGIN_NAME, 'loadUrl', [url, props]);},/*** Cancel loadUrl that is waiting to be loaded.*/- cancelLoadUrl:function() {- exec(null, null, APP_PLUGIN_NAME, "cancelLoadUrl", []);+ cancelLoadUrl: function () {+ exec(null, null, APP_PLUGIN_NAME, 'cancelLoadUrl', []);},/*** Clear web history in this web view.* Instead of BACK button loading the previous web page, it will exit the app.*/- clearHistory:function() {- exec(null, null, APP_PLUGIN_NAME, "clearHistory", []);+ clearHistory: function () {+ exec(null, null, APP_PLUGIN_NAME, 'clearHistory', []);},/*** Go to previous page displayed.* This is the same as pressing the backbutton on Android device.*/- backHistory:function() {- exec(null, null, APP_PLUGIN_NAME, "backHistory", []);+ backHistory: function () {+ exec(null, null, APP_PLUGIN_NAME, 'backHistory', []);},/**@@ -80,8 +80,8 @@ module.exports = {** @param override T=override, F=cancel override*/- overrideBackbutton:function(override) {- exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [override]);+ overrideBackbutton: function (override) {+ exec(null, null, APP_PLUGIN_NAME, 'overrideBackbutton', [override]);},/**@@ -95,14 +95,14 @@ module.exports = {* @param button volumeup, volumedown* @param override T=override, F=cancel override*/- overrideButton:function(button, override) {- exec(null, null, APP_PLUGIN_NAME, "overrideButton", [button, override]);+ overrideButton: function (button, override) {+ exec(null, null, APP_PLUGIN_NAME, 'overrideButton', [button, override]);},/*** Exit and terminate the application.*/- exitApp:function() {- return exec(null, null, APP_PLUGIN_NAME, "exitApp", []);+ exitApp: function () {+ return exec(null, null, APP_PLUGIN_NAME, 'exitApp', []);}};diff --git a/cordova/platforms/android/platform_www/cordova.js b/cordova/platforms/android/platform_www/cordova.jsindex da35c0214..3d71792dd 100644--- a/cordova/platforms/android/platform_www/cordova.js+++ b/cordova/platforms/android/platform_www/cordova.js@@ -1,5 +1,5 @@// Platform: android-// 9e8e1b716252c4a08abcd31a13013b868d6f4141+// 538a985db128858c0a0eb4dd40fb9c8e5433fc94/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -8,9 +8,9 @@to you under the Apache License, Version 2.0 (the"License"); you may not use this file except in compliancewith the License. You may obtain a copy of the License at-+http://www.apache.org/licenses/LICENSE-2.0-+Unless required by applicable law or agreed to in writing,software distributed under the License is distributed on an"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -19,12 +19,8 @@under the License.*/;(function() {-var PLATFORM_VERSION_BUILD_LABEL = '7.1.4';+var PLATFORM_VERSION_BUILD_LABEL = '9.0.0';// file: src/scripts/require.js--/* jshint -W079 */-/* jshint -W020 */-var require;var define;@@ -54,10 +50,10 @@ var define;require = function (id) {if (!modules[id]) {- throw 'module ' + id + ' not found';+ throw new Error('module ' + id + ' not found');} else if (id in inProgressModules) {var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;- throw 'Cycle in require graph: ' + cycle;+ throw new Error('Cycle in require graph: ' + cycle);}if (modules[id].factory) {try {@@ -73,8 +69,8 @@ var define;};define = function (id, factory) {- if (modules[id]) {- throw 'module ' + id + ' already defined';+ if (Object.prototype.hasOwnProperty.call(modules, id)) {+ throw new Error('module ' + id + ' already defined');}modules[id] = {@@ -101,7 +97,7 @@ define("cordova", function(require, exports, module) {// Workaround for Windows 10 in hosted environment case// http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object-if (window.cordova && !(window.cordova instanceof HTMLElement)) { // eslint-disable-line no-undef+if (window.cordova && !(window.cordova instanceof HTMLElement)) {throw new Error('cordova already defined');}@@ -166,7 +162,7 @@ function createEvent (type, data) {event.initEvent(type, false, false);if (data) {for (var i in data) {- if (data.hasOwnProperty(i)) {+ if (Object.prototype.hasOwnProperty.call(data, i)) {event[i] = data[i];}}@@ -174,7 +170,6 @@ function createEvent (type, data) {return event;}-/* eslint-disable no-undef */var cordova = {define: define,require: require,@@ -182,8 +177,6 @@ var cordova = {platformVersion: PLATFORM_VERSION_BUILD_LABEL,platformId: platform.id,- /* eslint-enable no-undef */-/*** Methods to add/remove your own addEventListener hijacking on document + window.*/@@ -202,15 +195,25 @@ var cordova = {removeDocumentEventHandler: function (event) {delete documentEventHandlers[event];},+/*** Retrieve original event handlers that were replaced by Cordova** @return object*/getOriginalHandlers: function () {- return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener},- 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}};+ return {+ document: {+ addEventListener: m_document_addEventListener,+ removeEventListener: m_document_removeEventListener+ },+ window: {+ addEventListener: m_window_addEventListener,+ removeEventListener: m_window_removeEventListener+ }+ };},+/*** Method to fire event from native code* bNoDetach is required for events which cause an exception which needs to be caught in native code@@ -233,6 +236,7 @@ var cordova = {document.dispatchEvent(evt);}},+fireWindowEvent: function (type, data) {var evt = createEvent(type, data);if (typeof windowEventHandlers[type] !== 'undefined') {@@ -306,12 +310,11 @@ var cordova = {}} catch (err) {var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;- console && console.log && console.log(msg);- console && console.log && err.stack && console.log(err.stack);- cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ cordova.fireWindowEvent('cordovacallbackerror', { message: msg, error: err });throw err;}},+addConstructor: function (func) {channel.onCordovaReady.subscribe(function () {try {@@ -327,7 +330,7 @@ module.exports = cordova;});-// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/android/nativeapiprovider.js+// file: ../cordova-android/cordova-js-src/android/nativeapiprovider.jsdefine("cordova/android/nativeapiprovider", function(require, exports, module) {/**@@ -338,19 +341,19 @@ var nativeApi = this._cordovaNative || require('cordova/android/promptbasednativvar currentApi = nativeApi;module.exports = {- get: function() { return currentApi; },- setPreferPrompt: function(value) {+ get: function () { return currentApi; },+ setPreferPrompt: function (value) {currentApi = value ? require('cordova/android/promptbasednativeapi') : nativeApi;},// Used only by tests.- set: function(value) {+ set: function (value) {currentApi = value;}};});-// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/android/promptbasednativeapi.js+// file: ../cordova-android/cordova-js-src/android/promptbasednativeapi.jsdefine("cordova/android/promptbasednativeapi", function(require, exports, module) {/**@@ -359,13 +362,13 @@ define("cordova/android/promptbasednativeapi", function(require, exports, module*/module.exports = {- exec: function(bridgeSecret, service, action, callbackId, argsJson) {- return prompt(argsJson, 'gap:'+JSON.stringify([bridgeSecret, service, action, callbackId]));+ exec: function (bridgeSecret, service, action, callbackId, argsJson) {+ return prompt(argsJson, 'gap:' + JSON.stringify([bridgeSecret, service, action, callbackId]));},- setNativeToJsBridgeMode: function(bridgeSecret, value) {+ setNativeToJsBridgeMode: function (bridgeSecret, value) {prompt(value, 'gap_bridge_mode:' + bridgeSecret);},- retrieveJsMessages: function(bridgeSecret, fromOnlineEvent) {+ retrieveJsMessages: function (bridgeSecret, fromOnlineEvent) {return prompt(+fromOnlineEvent, 'gap_poll:' + bridgeSecret);}};@@ -380,18 +383,47 @@ var utils = require('cordova/utils');var moduleExports = module.exports;var typeMap = {- 'A': 'Array',- 'D': 'Date',- 'N': 'Number',- 'S': 'String',- 'F': 'Function',- 'O': 'Object'+ A: 'Array',+ D: 'Date',+ N: 'Number',+ S: 'String',+ F: 'Function',+ O: 'Object'};function extractParamName (callee, argIndex) {- return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex];+ return (/\(\s*([^)]*?)\s*\)/).exec(callee)[1].split(/\s*,\s*/)[argIndex];}+/**+ * Checks the given arguments' types and throws if they are not as expected.+ *+ * `spec` is a string where each character stands for the required type of the+ * argument at the same position. In other words: the character at `spec[i]`+ * specifies the required type for `args[i]`. The characters in `spec` are the+ * first letter of the required type's name. The supported types are:+ *+ * Array, Date, Number, String, Function, Object+ *+ * Lowercase characters specify arguments that must not be `null` or `undefined`+ * while uppercase characters allow those values to be passed.+ *+ * Finally, `*` can be used to allow any type at the corresponding position.+ *+ * @example+ * function foo (arr, opts) {+ * // require `arr` to be an Array and `opts` an Object, null or undefined+ * checkArgs('aO', 'my.package.foo', arguments);+ * // ...+ * }+ * @param {String} spec - the type specification for `args` as described above+ * @param {String} functionName - full name of the callee.+ * Used in the error message+ * @param {Array|arguments} args - the arguments to be checked against `spec`+ * @param {Function} [opt_callee=args.callee] - the recipient of `args`.+ * Used to extract parameter names for the error message+ * @throws {TypeError} if args do not satisfy spec+ */function checkArgs (spec, functionName, args, opt_callee) {if (!moduleExports.enableChecks) {return;@@ -447,7 +479,7 @@ base64.fromArrayBuffer = function (arrayBuffer) {};base64.toArrayBuffer = function (str) {- var decodedStr = typeof atob !== 'undefined' ? atob(str) : Buffer.from(str, 'base64').toString('binary'); // eslint-disable-line no-undef+ var decodedStr = atob(str);var arrayBuffer = new ArrayBuffer(decodedStr.length);var array = new Uint8Array(arrayBuffer);for (var i = 0, len = decodedStr.length; i < len; i++) {@@ -509,14 +541,13 @@ var utils = require('cordova/utils');function each (objects, func, context) {for (var prop in objects) {- if (objects.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(objects, prop)) {func.apply(context, [objects[prop], prop]);}}}function clobber (obj, key, value) {- exports.replaceHookForTesting(obj, key);var needsProperty = false;try {obj[key] = value;@@ -590,7 +621,7 @@ function include (parent, objects, clobber, merge) {*/function recursiveMerge (target, src) {for (var prop in src) {- if (src.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(src, prop)) {if (target.prototype && target.prototype.constructor === target) {// If the target object is a constructor override off prototype.clobber(target.prototype, prop, src[prop]);@@ -616,7 +647,6 @@ exports.buildIntoAndMerge = function (objects, target) {};exports.recursiveMerge = recursiveMerge;exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter;-exports.replaceHookForTesting = function () {};});@@ -697,14 +727,14 @@ var channel = {}if (!len) h();},- /* eslint-disable no-return-assign */+create: function (type) {- return channel[type] = new Channel(type, false);+ return (channel[type] = new Channel(type, false));},createSticky: function (type) {- return channel[type] = new Channel(type, true);+ return (channel[type] = new Channel(type, true));},- /* eslint-enable no-return-assign */+/*** cordova Channels that must fire before "deviceready" is fired.*/@@ -825,7 +855,6 @@ Channel.prototype.unsubscribe = function (eventListenerOrFunction) {* Calls all functions subscribed to this channel.*/Channel.prototype.fire = function (e) {- var fail = false; // eslint-disable-line no-unused-varsvar fireArgs = Array.prototype.slice.call(arguments);// Apply stickiness.if (this.state === 1) {@@ -882,7 +911,7 @@ module.exports = channel;});-// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/exec.js+// file: ../cordova-android/cordova-js-src/exec.jsdefine("cordova/exec", function(require, exports, module) {/**@@ -899,38 +928,38 @@ define("cordova/exec", function(require, exports, module) {* @param {String} action Action to be run in cordova* @param {String[]} [args] Zero or more arguments to pass to the method*/-var cordova = require('cordova'),- nativeApiProvider = require('cordova/android/nativeapiprovider'),- utils = require('cordova/utils'),- base64 = require('cordova/base64'),- channel = require('cordova/channel'),- jsToNativeModes = {- PROMPT: 0,- JS_OBJECT: 1- },- nativeToJsModes = {- // Polls for messages using the JS->Native bridge.- POLLING: 0,- // For LOAD_URL to be viable, it would need to have a work-around for- // the bug where the soft-keyboard gets dismissed when a message is sent.- LOAD_URL: 1,- // For the ONLINE_EVENT to be viable, it would need to intercept all event- // listeners (both through addEventListener and window.ononline) as well- // as set the navigator property itself.- ONLINE_EVENT: 2,- EVAL_BRIDGE: 3- },- jsToNativeBridgeMode, // Set lazily.- nativeToJsBridgeMode = nativeToJsModes.EVAL_BRIDGE,- pollEnabled = false,- bridgeSecret = -1;+var cordova = require('cordova');+var nativeApiProvider = require('cordova/android/nativeapiprovider');+var utils = require('cordova/utils');+var base64 = require('cordova/base64');+var channel = require('cordova/channel');+var jsToNativeModes = {+ PROMPT: 0,+ JS_OBJECT: 1+};+var nativeToJsModes = {+ // Polls for messages using the JS->Native bridge.+ POLLING: 0,+ // For LOAD_URL to be viable, it would need to have a work-around for+ // the bug where the soft-keyboard gets dismissed when a message is sent.+ LOAD_URL: 1,+ // For the ONLINE_EVENT to be viable, it would need to intercept all event+ // listeners (both through addEventListener and window.ononline) as well+ // as set the navigator property itself.+ ONLINE_EVENT: 2,+ EVAL_BRIDGE: 3+};+var jsToNativeBridgeMode; // Set lazily.+var nativeToJsBridgeMode = nativeToJsModes.EVAL_BRIDGE;+var pollEnabled = false;+var bridgeSecret = -1;var messagesFromNative = [];var isProcessing = false;-var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve();-var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); };+var resolvedPromise = typeof Promise === 'undefined' ? null : Promise.resolve();+var nextTick = resolvedPromise ? function (fn) { resolvedPromise.then(fn); } : function (fn) { setTimeout(fn); };-function androidExec(success, fail, service, action, args) {+function androidExec (success, fail, service, action, args) {if (bridgeSecret < 0) {// If we ever catch this firing, we'll need to queue up exec()s// and fire them once we get a secret. For now, I don't think@@ -949,21 +978,21 @@ function androidExec(success, fail, service, action, args) {// Process any ArrayBuffers in the args into a string.for (var i = 0; i < args.length; i++) {- if (utils.typeName(args[i]) == 'ArrayBuffer') {+ if (utils.typeName(args[i]) === 'ArrayBuffer') {args[i] = base64.fromArrayBuffer(args[i]);}}- var callbackId = service + cordova.callbackId++,- argsJson = JSON.stringify(args);+ var callbackId = service + cordova.callbackId++;+ var argsJson = JSON.stringify(args);if (success || fail) {- cordova.callbacks[callbackId] = {success:success, fail:fail};+ cordova.callbacks[callbackId] = { success: success, fail: fail };}var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson);// If argsJson was received by Java as null, try again with the PROMPT bridge mode.// This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666.- if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "@Null arguments.") {+ if (jsToNativeBridgeMode === jsToNativeModes.JS_OBJECT && msgs === '@Null arguments.') {androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);androidExec(success, fail, service, action, args);androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);@@ -974,27 +1003,16 @@ function androidExec(success, fail, service, action, args) {}}-androidExec.init = function() {- //CB-11828- //This failsafe checks the version of Android and if it's Jellybean, it switches it to- //using the Online Event bridge for communicating from Native to JS- //- //It's ugly, but it's necessary.- var check = navigator.userAgent.toLowerCase().match(/android\s[0-9].[0-9]/);- var version_code = check && check[0].match(/4.[0-3].*/);- if (version_code != null && nativeToJsBridgeMode == nativeToJsModes.EVAL_BRIDGE) {- nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT;- }-+androidExec.init = function () {bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode);channel.onNativeReady.fire();};-function pollOnceFromOnlineEvent() {+function pollOnceFromOnlineEvent () {pollOnce(true);}-function pollOnce(opt_fromOnlineEvent) {+function pollOnce (opt_fromOnlineEvent) {if (bridgeSecret < 0) {// This can happen when the NativeToJsMessageQueue resets the online state on page transitions.// We know there's nothing to retrieve, so no need to poll.@@ -1008,15 +1026,15 @@ function pollOnce(opt_fromOnlineEvent) {}}-function pollingTimerFunc() {+function pollingTimerFunc () {if (pollEnabled) {pollOnce();setTimeout(pollingTimerFunc, 50);}}-function hookOnlineApis() {- function proxyEvent(e) {+function hookOnlineApis () {+ function proxyEvent (e) {cordova.fireWindowEvent(e.type);}// The network module takes care of firing online and offline events.@@ -1036,19 +1054,19 @@ hookOnlineApis();androidExec.jsToNativeModes = jsToNativeModes;androidExec.nativeToJsModes = nativeToJsModes;-androidExec.setJsToNativeBridgeMode = function(mode) {- if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) {+androidExec.setJsToNativeBridgeMode = function (mode) {+ if (mode === jsToNativeModes.JS_OBJECT && !window._cordovaNative) {mode = jsToNativeModes.PROMPT;}- nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT);+ nativeApiProvider.setPreferPrompt(mode === jsToNativeModes.PROMPT);jsToNativeBridgeMode = mode;};-androidExec.setNativeToJsBridgeMode = function(mode) {- if (mode == nativeToJsBridgeMode) {+androidExec.setNativeToJsBridgeMode = function (mode) {+ if (mode === nativeToJsBridgeMode) {return;}- if (nativeToJsBridgeMode == nativeToJsModes.POLLING) {+ if (nativeToJsBridgeMode === nativeToJsModes.POLLING) {pollEnabled = false;}@@ -1059,32 +1077,32 @@ androidExec.setNativeToJsBridgeMode = function(mode) {nativeApiProvider.get().setNativeToJsBridgeMode(bridgeSecret, mode);}- if (mode == nativeToJsModes.POLLING) {+ if (mode === nativeToJsModes.POLLING) {pollEnabled = true;setTimeout(pollingTimerFunc, 1);}};-function buildPayload(payload, message) {+function buildPayload (payload, message) {var payloadKind = message.charAt(0);- if (payloadKind == 's') {+ if (payloadKind === 's') {payload.push(message.slice(1));- } else if (payloadKind == 't') {+ } else if (payloadKind === 't') {payload.push(true);- } else if (payloadKind == 'f') {+ } else if (payloadKind === 'f') {payload.push(false);- } else if (payloadKind == 'N') {+ } else if (payloadKind === 'N') {payload.push(null);- } else if (payloadKind == 'n') {+ } else if (payloadKind === 'n') {payload.push(+message.slice(1));- } else if (payloadKind == 'A') {+ } else if (payloadKind === 'A') {var data = message.slice(1);payload.push(base64.toArrayBuffer(data));- } else if (payloadKind == 'S') {+ } else if (payloadKind === 'S') {payload.push(window.atob(message.slice(1)));- } else if (payloadKind == 'M') {+ } else if (payloadKind === 'M') {var multipartMessages = message.slice(1);- while (multipartMessages !== "") {+ while (multipartMessages !== '') {var spaceIdx = multipartMessages.indexOf(' ');var msgLen = +multipartMessages.slice(0, spaceIdx);var multipartMessage = multipartMessages.substr(spaceIdx + 1, msgLen);@@ -1097,14 +1115,15 @@ function buildPayload(payload, message) {}// Processes a single message, as encoded by NativeToJsMessageQueue.java.-function processMessage(message) {+function processMessage (message) {var firstChar = message.charAt(0);- if (firstChar == 'J') {+ if (firstChar === 'J') {// This is deprecated on the .java side. It doesn't work with CSP enabled.+ // eslint-disable-next-line no-evaleval(message.slice(1));- } else if (firstChar == 'S' || firstChar == 'F') {- var success = firstChar == 'S';- var keepCallback = message.charAt(1) == '1';+ } else if (firstChar === 'S' || firstChar === 'F') {+ var success = firstChar === 'S';+ var keepCallback = message.charAt(1) === '1';var spaceIdx = message.indexOf(' ', 2);var status = +message.slice(2, spaceIdx);var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);@@ -1114,11 +1133,11 @@ function processMessage(message) {buildPayload(payload, payloadMessage);cordova.callbackFromNative(callbackId, success, status, payload, keepCallback);} else {- console.log("processMessage failed: invalid message: " + JSON.stringify(message));+ console.log('processMessage failed: invalid message: ' + JSON.stringify(message));}}-function processMessages() {+function processMessages () {// Check for the reentrant case.if (isProcessing) {return;@@ -1131,7 +1150,7 @@ function processMessages() {var msg = popMessageFromQueue();// The Java side can send a * message to indicate that it// still has messages waiting to be retrieved.- if (msg == '*' && messagesFromNative.length === 0) {+ if (msg === '*' && messagesFromNative.length === 0) {nextTick(pollOnce);return;}@@ -1144,9 +1163,9 @@ function processMessages() {}}-function popMessageFromQueue() {+function popMessageFromQueue () {var messageBatch = messagesFromNative.shift();- if (messageBatch == '*') {+ if (messageBatch === '*') {return '*';}@@ -1202,7 +1221,6 @@ var cordova = require('cordova');var modulemapper = require('cordova/modulemapper');var platform = require('cordova/platform');var pluginloader = require('cordova/pluginloader');-var utils = require('cordova/utils');var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];@@ -1222,34 +1240,6 @@ window.setTimeout(function () {}}, 5000);-// Replace navigator before any modules are required(), to ensure it happens as soon as possible.-// We replace it so that properties that can't be clobbered can instead be overridden.-function replaceNavigator (origNavigator) {- var CordovaNavigator = function () {};- CordovaNavigator.prototype = origNavigator;- var newNavigator = new CordovaNavigator();- // This work-around really only applies to new APIs that are newer than Function.bind.- // Without it, APIs such as getGamepads() break.- if (CordovaNavigator.bind) {- for (var key in origNavigator) {- if (typeof origNavigator[key] === 'function') {- newNavigator[key] = origNavigator[key].bind(origNavigator);- } else {- (function (k) {- utils.defineGetterSetter(newNavigator, key, function () {- return origNavigator[k];- });- })(key);- }- }- }- return newNavigator;-}--if (window.navigator) {- window.navigator = replaceNavigator(window.navigator);-}-if (!window.console) {window.console = {log: function () {}@@ -1315,131 +1305,6 @@ channel.join(function () {channel.join(function () {require('cordova').fireDocumentEvent('deviceready');}, channel.deviceReadyChannelsArray);--}, platformInitChannelsArray);--});--// file: src/common/init_b.js-define("cordova/init_b", function(require, exports, module) {--var channel = require('cordova/channel');-var cordova = require('cordova');-var modulemapper = require('cordova/modulemapper');-var platform = require('cordova/platform');-var pluginloader = require('cordova/pluginloader');-var utils = require('cordova/utils');--var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeReady, channel.onPluginsReady];--// setting exec-cordova.exec = require('cordova/exec');--function logUnfiredChannels (arr) {- for (var i = 0; i < arr.length; ++i) {- if (arr[i].state !== 2) {- console.log('Channel not fired: ' + arr[i].type);- }- }-}--window.setTimeout(function () {- if (channel.onDeviceReady.state !== 2) {- console.log('deviceready has not fired after 5 seconds.');- logUnfiredChannels(platformInitChannelsArray);- logUnfiredChannels(channel.deviceReadyChannelsArray);- }-}, 5000);--// Replace navigator before any modules are required(), to ensure it happens as soon as possible.-// We replace it so that properties that can't be clobbered can instead be overridden.-function replaceNavigator (origNavigator) {- var CordovaNavigator = function () {};- CordovaNavigator.prototype = origNavigator;- var newNavigator = new CordovaNavigator();- // This work-around really only applies to new APIs that are newer than Function.bind.- // Without it, APIs such as getGamepads() break.- if (CordovaNavigator.bind) {- for (var key in origNavigator) {- if (typeof origNavigator[key] === 'function') {- newNavigator[key] = origNavigator[key].bind(origNavigator);- } else {- (function (k) {- utils.defineGetterSetter(newNavigator, key, function () {- return origNavigator[k];- });- })(key);- }- }- }- return newNavigator;-}-if (window.navigator) {- window.navigator = replaceNavigator(window.navigator);-}--if (!window.console) {- window.console = {- log: function () {}- };-}-if (!window.console.warn) {- window.console.warn = function (msg) {- this.log('warn: ' + msg);- };-}--// Register pause, resume and deviceready channels as events on document.-channel.onPause = cordova.addDocumentEventHandler('pause');-channel.onResume = cordova.addDocumentEventHandler('resume');-channel.onActivated = cordova.addDocumentEventHandler('activated');-channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');--// Listen for DOMContentLoaded and notify our channel subscribers.-if (document.readyState === 'complete' || document.readyState === 'interactive') {- channel.onDOMContentLoaded.fire();-} else {- document.addEventListener('DOMContentLoaded', function () {- channel.onDOMContentLoaded.fire();- }, false);-}--// _nativeReady is global variable that the native side can set-// to signify that the native code is ready. It is a global since-// it may be called before any cordova JS is ready.-if (window._nativeReady) {- channel.onNativeReady.fire();-}--// Call the platform-specific initialization.-platform.bootstrap && platform.bootstrap();--// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js.-// The delay allows the attached modules to be defined before the plugin loader looks for them.-setTimeout(function () {- pluginloader.load(function () {- channel.onPluginsReady.fire();- });-}, 0);--/**- * Create all cordova objects once native side is ready.- */-channel.join(function () {- modulemapper.mapModules(window);-- platform.initialize && platform.initialize();-- // Fire event to notify that all objects are created- channel.onCordovaReady.fire();-- // Fire onDeviceReady event once page has fully loaded, all- // constructors have run and cordova info has been received from native- // side.- channel.join(function () {- require('cordova').fireDocumentEvent('deviceready');- }, channel.deviceReadyChannelsArray);-}, platformInitChannelsArray);});@@ -1448,7 +1313,7 @@ channel.join(function () {define("cordova/modulemapper", function(require, exports, module) {var builder = require('cordova/builder');-var moduleMap = define.moduleMap; // eslint-disable-line no-undef+var moduleMap = define.moduleMap;var symbolList;var deprecationMap;@@ -1488,108 +1353,9 @@ function prepareNamespace (symbolPath, context) {if (!symbolPath) {return context;}- var parts = symbolPath.split('.');- var cur = context;- for (var i = 0, part; part = parts[i]; ++i) { // eslint-disable-line no-cond-assign- cur = cur[part] = cur[part] || {};- }- return cur;-}--exports.mapModules = function (context) {- var origSymbols = {};- context.CDV_origSymbols = origSymbols;- for (var i = 0, len = symbolList.length; i < len; i += 3) {- var strategy = symbolList[i];- var moduleName = symbolList[i + 1];- var module = require(moduleName);- // <runs/>- if (strategy === 'r') {- continue;- }- var symbolPath = symbolList[i + 2];- var lastDot = symbolPath.lastIndexOf('.');- var namespace = symbolPath.substr(0, lastDot);- var lastName = symbolPath.substr(lastDot + 1);-- var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null;- var parentObj = prepareNamespace(namespace, context);- var target = parentObj[lastName];-- if (strategy === 'm' && target) {- builder.recursiveMerge(target, module);- } else if ((strategy === 'd' && !target) || (strategy !== 'd')) {- if (!(symbolPath in origSymbols)) {- origSymbols[symbolPath] = target;- }- builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg);- }- }-};--exports.getOriginalSymbol = function (context, symbolPath) {- var origSymbols = context.CDV_origSymbols;- if (origSymbols && (symbolPath in origSymbols)) {- return origSymbols[symbolPath];- }- var parts = symbolPath.split('.');- var obj = context;- for (var i = 0; i < parts.length; ++i) {- obj = obj && obj[parts[i]];- }- return obj;-};--exports.reset();--});--// file: src/common/modulemapper_b.js-define("cordova/modulemapper_b", function(require, exports, module) {--var builder = require('cordova/builder');-var symbolList = [];-var deprecationMap;--exports.reset = function () {- symbolList = [];- deprecationMap = {};-};--function addEntry (strategy, moduleName, symbolPath, opt_deprecationMessage) {- symbolList.push(strategy, moduleName, symbolPath);- if (opt_deprecationMessage) {- deprecationMap[symbolPath] = opt_deprecationMessage;- }-}--// Note: Android 2.3 does have Function.bind().-exports.clobbers = function (moduleName, symbolPath, opt_deprecationMessage) {- addEntry('c', moduleName, symbolPath, opt_deprecationMessage);-};--exports.merges = function (moduleName, symbolPath, opt_deprecationMessage) {- addEntry('m', moduleName, symbolPath, opt_deprecationMessage);-};--exports.defaults = function (moduleName, symbolPath, opt_deprecationMessage) {- addEntry('d', moduleName, symbolPath, opt_deprecationMessage);-};--exports.runs = function (moduleName) {- addEntry('r', moduleName, null);-};--function prepareNamespace (symbolPath, context) {- if (!symbolPath) {- return context;- }- var parts = symbolPath.split('.');- var cur = context;- for (var i = 0, part; part = parts[i]; ++i) { // eslint-disable-line no-cond-assign- cur = cur[part] = cur[part] || {};- }- return cur;+ return symbolPath.split('.').reduce(function (cur, part) {+ return (cur[part] = cur[part] || {});+ }, context);}exports.mapModules = function (context) {@@ -1640,7 +1406,7 @@ exports.reset();});-// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/platform.js+// file: ../cordova-android/cordova-js-src/platform.jsdefine("cordova/platform", function(require, exports, module) {// The last resume event that was received that had the result of a plugin call.@@ -1648,11 +1414,11 @@ var lastResumeEvent = null;module.exports = {id: 'android',- bootstrap: function() {- var channel = require('cordova/channel'),- cordova = require('cordova'),- exec = require('cordova/exec'),- modulemapper = require('cordova/modulemapper');+ bootstrap: function () {+ var channel = require('cordova/channel');+ var cordova = require('cordova');+ var exec = require('cordova/exec');+ var modulemapper = require('cordova/modulemapper');// Get the shared secret needed to use the bridge.exec.init();@@ -1664,21 +1430,21 @@ module.exports = {// Inject a listener for the backbutton on the document.var backButtonChannel = cordova.addDocumentEventHandler('backbutton');- backButtonChannel.onHasSubscribersChange = function() {+ backButtonChannel.onHasSubscribersChange = function () {// If we just attached the first handler or detached the last handler,// let native know we need to override the back button.- exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [this.numHandlers == 1]);+ exec(null, null, APP_PLUGIN_NAME, 'overrideBackbutton', [this.numHandlers === 1]);};// Add hardware MENU and SEARCH button handlerscordova.addDocumentEventHandler('menubutton');cordova.addDocumentEventHandler('searchbutton');- function bindButtonChannel(buttonName) {+ function bindButtonChannel (buttonName) {// generic button bind used for volumeup/volumedown buttonsvar volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button');- volumeButtonChannel.onHasSubscribersChange = function() {- exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]);+ volumeButtonChannel.onHasSubscribersChange = function () {+ exec(null, null, APP_PLUGIN_NAME, 'overrideButton', [buttonName, this.numHandlers === 1]);};}// Inject a listener for the volume buttons on the document.@@ -1690,7 +1456,7 @@ module.exports = {// plugin result is delivered even after the event is fired (CB-10498)var cordovaAddEventListener = document.addEventListener;- document.addEventListener = function(evt, handler, capture) {+ document.addEventListener = function (evt, handler, capture) {cordovaAddEventListener(evt, handler, capture);if (evt === 'resume' && lastResumeEvent) {@@ -1700,57 +1466,54 @@ module.exports = {// Let native code know we are all done on the JS side.// Native code will then un-hide the WebView.- channel.onCordovaReady.subscribe(function() {+ channel.onCordovaReady.subscribe(function () {exec(onMessageFromNative, null, APP_PLUGIN_NAME, 'messageChannel', []);- exec(null, null, APP_PLUGIN_NAME, "show", []);+ exec(null, null, APP_PLUGIN_NAME, 'show', []);});}};-function onMessageFromNative(msg) {+function onMessageFromNative (msg) {var cordova = require('cordova');var action = msg.action;- switch (action)- {- // Button events- case 'backbutton':- case 'menubutton':- case 'searchbutton':- // App life cycle events- case 'pause':- // Volume events- case 'volumedownbutton':- case 'volumeupbutton':- cordova.fireDocumentEvent(action);- break;- case 'resume':- if(arguments.length > 1 && msg.pendingResult) {- if(arguments.length === 2) {- msg.pendingResult.result = arguments[1];- } else {- // The plugin returned a multipart message- var res = [];- for(var i = 1; i < arguments.length; i++) {- res.push(arguments[i]);- }- msg.pendingResult.result = res;+ switch (action) {+ // pause and resume are Android app life cycle events+ case 'backbutton':+ case 'menubutton':+ case 'searchbutton':+ case 'pause':+ case 'volumedownbutton':+ case 'volumeupbutton':+ cordova.fireDocumentEvent(action);+ break;+ case 'resume':+ if (arguments.length > 1 && msg.pendingResult) {+ if (arguments.length === 2) {+ msg.pendingResult.result = arguments[1];+ } else {+ // The plugin returned a multipart message+ var res = [];+ for (var i = 1; i < arguments.length; i++) {+ res.push(arguments[i]);}-- // Save the plugin result so that it can be delivered to the js- // even if they miss the initial firing of the event- lastResumeEvent = msg;+ msg.pendingResult.result = res;}- cordova.fireDocumentEvent(action, msg);- break;- default:- throw new Error('Unknown event action ' + action);++ // Save the plugin result so that it can be delivered to the js+ // even if they miss the initial firing of the event+ lastResumeEvent = msg;+ }+ cordova.fireDocumentEvent(action, msg);+ break;+ default:+ throw new Error('Unknown event action ' + action);}}});-// file: /Users/brodybits/Documents/cordova/cordova-android/cordova-js-src/plugin/android/app.js+// file: ../cordova-android/cordova-js-src/plugin/android/app.jsdefine("cordova/plugin/android/app", function(require, exports, module) {var exec = require('cordova/exec');@@ -1760,8 +1523,8 @@ module.exports = {/*** Clear the resource cache.*/- clearCache:function() {- exec(null, null, APP_PLUGIN_NAME, "clearCache", []);+ clearCache: function () {+ exec(null, null, APP_PLUGIN_NAME, 'clearCache', []);},/**@@ -1778,31 +1541,31 @@ module.exports = {* Example:* navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000});*/- loadUrl:function(url, props) {- exec(null, null, APP_PLUGIN_NAME, "loadUrl", [url, props]);+ loadUrl: function (url, props) {+ exec(null, null, APP_PLUGIN_NAME, 'loadUrl', [url, props]);},/*** Cancel loadUrl that is waiting to be loaded.*/- cancelLoadUrl:function() {- exec(null, null, APP_PLUGIN_NAME, "cancelLoadUrl", []);+ cancelLoadUrl: function () {+ exec(null, null, APP_PLUGIN_NAME, 'cancelLoadUrl', []);},/*** Clear web history in this web view.* Instead of BACK button loading the previous web page, it will exit the app.*/- clearHistory:function() {- exec(null, null, APP_PLUGIN_NAME, "clearHistory", []);+ clearHistory: function () {+ exec(null, null, APP_PLUGIN_NAME, 'clearHistory', []);},/*** Go to previous page displayed.* This is the same as pressing the backbutton on Android device.*/- backHistory:function() {- exec(null, null, APP_PLUGIN_NAME, "backHistory", []);+ backHistory: function () {+ exec(null, null, APP_PLUGIN_NAME, 'backHistory', []);},/**@@ -1814,8 +1577,8 @@ module.exports = {** @param override T=override, F=cancel override*/- overrideBackbutton:function(override) {- exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [override]);+ overrideBackbutton: function (override) {+ exec(null, null, APP_PLUGIN_NAME, 'overrideBackbutton', [override]);},/**@@ -1829,15 +1592,15 @@ module.exports = {* @param button volumeup, volumedown* @param override T=override, F=cancel override*/- overrideButton:function(button, override) {- exec(null, null, APP_PLUGIN_NAME, "overrideButton", [button, override]);+ overrideButton: function (button, override) {+ exec(null, null, APP_PLUGIN_NAME, 'overrideButton', [button, override]);},/*** Exit and terminate the application.*/- exitApp:function() {- return exec(null, null, APP_PLUGIN_NAME, "exitApp", []);+ exitApp: function () {+ return exec(null, null, APP_PLUGIN_NAME, 'exitApp', []);}};@@ -1862,11 +1625,11 @@ exports.injectScript = function (url, onload, onerror) {function injectIfNecessary (id, url, onload, onerror) {onerror = onerror || onload;- if (id in define.moduleMap) { // eslint-disable-line no-undef+ if (id in define.moduleMap) {onload();} else {exports.injectScript(url, function () {- if (id in define.moduleMap) { // eslint-disable-line no-undef+ if (id in define.moduleMap) {onload();} else {onerror();@@ -1877,7 +1640,7 @@ function injectIfNecessary (id, url, onload, onerror) {function onScriptLoadingComplete (moduleList, finishPluginLoading) {// Loop through all the plugins and then through their clobbers and merges.- for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign+ for (var i = 0, module; (module = moduleList[i]); i++) {if (module.clobbers && module.clobbers.length) {for (var j = 0; j < module.clobbers.length; j++) {modulemapper.clobbers(module.id, module.clobbers[j]);@@ -1953,53 +1716,6 @@ exports.load = function (callback) {});-// file: src/common/pluginloader_b.js-define("cordova/pluginloader_b", function(require, exports, module) {--var modulemapper = require('cordova/modulemapper');--// Handler for the cordova_plugins.js content.-// See plugman's plugin_loader.js for the details of this object.-function handlePluginsObject (moduleList) {- // if moduleList is not defined or empty, we've nothing to do- if (!moduleList || !moduleList.length) {- return;- }-- // Loop through all the modules and then through their clobbers and merges.- for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign- if (module.clobbers && module.clobbers.length) {- for (var j = 0; j < module.clobbers.length; j++) {- modulemapper.clobbers(module.id, module.clobbers[j]);- }- }-- if (module.merges && module.merges.length) {- for (var k = 0; k < module.merges.length; k++) {- modulemapper.merges(module.id, module.merges[k]);- }- }-- // Finally, if runs is truthy we want to simply require() the module.- if (module.runs) {- modulemapper.runs(module.id);- }- }-}--// Loads all plugins' js-modules. Plugin loading is syncronous in browserified bundle-// but the method accepts callback to be compatible with non-browserify flow.-// onDeviceReady is blocked on onPluginsReady. onPluginsReady is fired when there are-// no plugins to load, or they are all done.-exports.load = function (callback) {- var moduleList = require('cordova/plugin_list');- handlePluginsObject(moduleList);-- callback();-};--});-// file: src/common/urlutil.jsdefine("cordova/urlutil", function(require, exports, module) {@@ -2107,10 +1823,11 @@ utils.clone = function (obj) {retVal = {};for (i in obj) {- // 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') { // eslint-disable-line valid-typeof+ // 'unknown' type may be returned in custom protocol activation case on+ // Windows Phone 8.1 causing "No such interface supported" exception on+ // cloning (https://issues.apache.org/jira/browse/CB-11522)+ // eslint-disable-next-line valid-typeof+ if ((!(i in retVal) || retVal[i] !== obj[i]) && typeof obj[i] !== 'undefined' && typeof obj[i] !== 'unknown') {retVal[i] = utils.clone(obj[i]);}}@@ -2160,7 +1877,6 @@ utils.extend = (function () {var F = function () {};// extend Child from Parentreturn function (Child, Parent) {-F.prototype = Parent.prototype;Child.prototype = new F();Child.__super__ = Parent.prototype;@@ -2183,7 +1899,6 @@ utils.alert = function (msg) {window.cordova = require('cordova');// file: src/scripts/bootstrap.js-require('cordova/init');})();diff --git a/cordova/platforms/android/platform_www/cordova_plugins.js b/cordova/platforms/android/platform_www/cordova_plugins.jsindex 6264ff213..ae3bc4eb1 100644--- a/cordova/platforms/android/platform_www/cordova_plugins.js+++ b/cordova/platforms/android/platform_www/cordova_plugins.js@@ -1,271 +1,268 @@cordova.define('cordova/plugin_list', function(require, exports, module) {-module.exports = [- {- "id": "cordova-plugin-device.device",- "file": "plugins/cordova-plugin-device/www/device.js",- "pluginId": "cordova-plugin-device",- "clobbers": [- "device"- ]- },- {- "id": "cordova-plugin-background-mode.BackgroundMode",- "file": "plugins/cordova-plugin-background-mode/www/background-mode.js",- "pluginId": "cordova-plugin-background-mode",- "clobbers": [- "cordova.plugins.backgroundMode",- "plugin.backgroundMode"- ]- },- {- "id": "cordova-plugin-camera.Camera",- "file": "plugins/cordova-plugin-camera/www/CameraConstants.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "Camera"- ]- },- {- "id": "cordova-plugin-camera.CameraPopoverOptions",- "file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "CameraPopoverOptions"- ]- },- {- "id": "cordova-plugin-camera.camera",- "file": "plugins/cordova-plugin-camera/www/Camera.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "navigator.camera"- ]- },- {- "id": "cordova-plugin-camera.CameraPopoverHandle",- "file": "plugins/cordova-plugin-camera/www/CameraPopoverHandle.js",- "pluginId": "cordova-plugin-camera",- "clobbers": [- "CameraPopoverHandle"- ]- },- {- "id": "cordova-plugin-file.DirectoryEntry",- "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.DirectoryEntry"- ]- },- {- "id": "cordova-plugin-file.DirectoryReader",- "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.DirectoryReader"- ]- },- {- "id": "cordova-plugin-file.Entry",- "file": "plugins/cordova-plugin-file/www/Entry.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.Entry"- ]- },- {- "id": "cordova-plugin-file.File",- "file": "plugins/cordova-plugin-file/www/File.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.File"- ]- },- {- "id": "cordova-plugin-file.FileEntry",- "file": "plugins/cordova-plugin-file/www/FileEntry.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileEntry"- ]- },- {- "id": "cordova-plugin-file.FileError",- "file": "plugins/cordova-plugin-file/www/FileError.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileError"- ]- },- {- "id": "cordova-plugin-file.FileReader",- "file": "plugins/cordova-plugin-file/www/FileReader.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileReader"- ]- },- {- "id": "cordova-plugin-file.FileSystem",- "file": "plugins/cordova-plugin-file/www/FileSystem.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileSystem"- ]- },- {- "id": "cordova-plugin-file.FileUploadOptions",- "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileUploadOptions"- ]- },- {- "id": "cordova-plugin-file.FileUploadResult",- "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileUploadResult"- ]- },- {- "id": "cordova-plugin-file.FileWriter",- "file": "plugins/cordova-plugin-file/www/FileWriter.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.FileWriter"- ]- },- {- "id": "cordova-plugin-file.Flags",- "file": "plugins/cordova-plugin-file/www/Flags.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.Flags"- ]- },- {- "id": "cordova-plugin-file.LocalFileSystem",- "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.LocalFileSystem"- ],- "merges": [- "window"- ]- },- {- "id": "cordova-plugin-file.Metadata",- "file": "plugins/cordova-plugin-file/www/Metadata.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.Metadata"- ]- },- {- "id": "cordova-plugin-file.ProgressEvent",- "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.ProgressEvent"- ]- },- {- "id": "cordova-plugin-file.fileSystems",- "file": "plugins/cordova-plugin-file/www/fileSystems.js",- "pluginId": "cordova-plugin-file"- },- {- "id": "cordova-plugin-file.requestFileSystem",- "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",- "pluginId": "cordova-plugin-file",- "clobbers": [- "window.requestFileSystem"- ]- },- {- "id": "cordova-plugin-file.resolveLocalFileSystemURI",- "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",- "pluginId": "cordova-plugin-file",- "merges": [- "window"- ]- },- {- "id": "cordova-plugin-file.isChrome",- "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",- "pluginId": "cordova-plugin-file",- "runs": true- },- {- "id": "cordova-plugin-file.androidFileSystem",- "file": "plugins/cordova-plugin-file/www/android/FileSystem.js",- "pluginId": "cordova-plugin-file",- "merges": [- "FileSystem"- ]- },- {- "id": "cordova-plugin-file.fileSystems-roots",- "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",- "pluginId": "cordova-plugin-file",- "runs": true- },- {- "id": "cordova-plugin-file.fileSystemPaths",- "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",- "pluginId": "cordova-plugin-file",- "merges": [- "cordova"- ],- "runs": true- },- {- "id": "es6-promise-plugin.Promise",- "file": "plugins/es6-promise-plugin/www/promise.js",- "pluginId": "es6-promise-plugin",- "runs": true- },- {- "id": "cordova-plugin-x-socialsharing.SocialSharing",- "file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",- "pluginId": "cordova-plugin-x-socialsharing",- "clobbers": [- "window.plugins.socialsharing"- ]- },- {- "id": "cordova-plugin-file-opener2.FileOpener2",- "file": "plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js",- "pluginId": "cordova-plugin-file-opener2",- "clobbers": [- "cordova.plugins.fileOpener2"- ]- },- {- "id": "com.whebcraft.cordova.plugin.downloader.Downloader",- "file": "plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js",- "pluginId": "com.whebcraft.cordova.plugin.downloader",- "clobbers": [- "plugins.Downloader"- ]- }-];-module.exports.metadata =-// TOP OF METADATA-{- "cordova-plugin-device": "2.0.3",- "cordova-plugin-background-mode": "0.7.3",- "cordova-plugin-camera": "4.1.0",- "cordova-plugin-file": "6.0.2",- "cordova-plugin-whitelist": "1.3.4",- "es6-promise-plugin": "4.2.2",- "cordova-plugin-x-socialsharing": "5.6.8",- "cordova-plugin-file-opener2": "3.0.3",- "com.whebcraft.cordova.plugin.downloader": "0.1.0",- "cordova-plugin-wkwebview-engine": "1.2.1"-};-// BOTTOM OF METADATA+ module.exports = [+ {+ "id": "cordova-plugin-device.device",+ "file": "plugins/cordova-plugin-device/www/device.js",+ "pluginId": "cordova-plugin-device",+ "clobbers": [+ "device"+ ]+ },+ {+ "id": "cordova-plugin-background-mode.BackgroundMode",+ "file": "plugins/cordova-plugin-background-mode/www/background-mode.js",+ "pluginId": "cordova-plugin-background-mode",+ "clobbers": [+ "cordova.plugins.backgroundMode",+ "plugin.backgroundMode"+ ]+ },+ {+ "id": "cordova-plugin-camera.Camera",+ "file": "plugins/cordova-plugin-camera/www/CameraConstants.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "Camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverOptions",+ "file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverOptions"+ ]+ },+ {+ "id": "cordova-plugin-camera.camera",+ "file": "plugins/cordova-plugin-camera/www/Camera.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "navigator.camera"+ ]+ },+ {+ "id": "cordova-plugin-camera.CameraPopoverHandle",+ "file": "plugins/cordova-plugin-camera/www/CameraPopoverHandle.js",+ "pluginId": "cordova-plugin-camera",+ "clobbers": [+ "CameraPopoverHandle"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryEntry",+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.DirectoryReader",+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.DirectoryReader"+ ]+ },+ {+ "id": "cordova-plugin-file.Entry",+ "file": "plugins/cordova-plugin-file/www/Entry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Entry"+ ]+ },+ {+ "id": "cordova-plugin-file.File",+ "file": "plugins/cordova-plugin-file/www/File.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.File"+ ]+ },+ {+ "id": "cordova-plugin-file.FileEntry",+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileEntry"+ ]+ },+ {+ "id": "cordova-plugin-file.FileError",+ "file": "plugins/cordova-plugin-file/www/FileError.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileError"+ ]+ },+ {+ "id": "cordova-plugin-file.FileReader",+ "file": "plugins/cordova-plugin-file/www/FileReader.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileReader"+ ]+ },+ {+ "id": "cordova-plugin-file.FileSystem",+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadOptions",+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadOptions"+ ]+ },+ {+ "id": "cordova-plugin-file.FileUploadResult",+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileUploadResult"+ ]+ },+ {+ "id": "cordova-plugin-file.FileWriter",+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.FileWriter"+ ]+ },+ {+ "id": "cordova-plugin-file.Flags",+ "file": "plugins/cordova-plugin-file/www/Flags.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Flags"+ ]+ },+ {+ "id": "cordova-plugin-file.LocalFileSystem",+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.LocalFileSystem"+ ],+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.Metadata",+ "file": "plugins/cordova-plugin-file/www/Metadata.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.Metadata"+ ]+ },+ {+ "id": "cordova-plugin-file.ProgressEvent",+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.ProgressEvent"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems",+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",+ "pluginId": "cordova-plugin-file"+ },+ {+ "id": "cordova-plugin-file.requestFileSystem",+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",+ "pluginId": "cordova-plugin-file",+ "clobbers": [+ "window.requestFileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "window"+ ]+ },+ {+ "id": "cordova-plugin-file.isChrome",+ "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.androidFileSystem",+ "file": "plugins/cordova-plugin-file/www/android/FileSystem.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "FileSystem"+ ]+ },+ {+ "id": "cordova-plugin-file.fileSystems-roots",+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",+ "pluginId": "cordova-plugin-file",+ "runs": true+ },+ {+ "id": "cordova-plugin-file.fileSystemPaths",+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",+ "pluginId": "cordova-plugin-file",+ "merges": [+ "cordova"+ ],+ "runs": true+ },+ {+ "id": "cordova-plugin-file-opener2.FileOpener2",+ "file": "plugins/cordova-plugin-file-opener2/www/plugins.FileOpener2.js",+ "pluginId": "cordova-plugin-file-opener2",+ "clobbers": [+ "cordova.plugins.fileOpener2"+ ]+ },+ {+ "id": "com.whebcraft.cordova.plugin.downloader.Downloader",+ "file": "plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js",+ "pluginId": "com.whebcraft.cordova.plugin.downloader",+ "clobbers": [+ "plugins.Downloader"+ ]+ },+ {+ "id": "es6-promise-plugin.Promise",+ "file": "plugins/es6-promise-plugin/www/promise.js",+ "pluginId": "es6-promise-plugin",+ "runs": true+ },+ {+ "id": "cordova-plugin-x-socialsharing.SocialSharing",+ "file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",+ "pluginId": "cordova-plugin-x-socialsharing",+ "clobbers": [+ "window.plugins.socialsharing"+ ]+ }+ ];+ module.exports.metadata = {+ "cordova-plugin-device": "2.0.3",+ "cordova-plugin-background-mode": "0.7.3",+ "cordova-plugin-camera": "4.1.0",+ "cordova-plugin-file": "6.0.2",+ "cordova-plugin-file-opener2": "3.0.4",+ "cordova-plugin-whitelist": "1.3.4",+ "com.whebcraft.cordova.plugin.downloader": "0.1.0",+ "es6-promise-plugin": "4.2.2",+ "cordova-plugin-x-socialsharing": "5.6.8",+ "cordova-plugin-ios-xhr": "1.0.0"+ };});diff --git a/cordova/platforms/android/project.properties b/cordova/platforms/android/project.propertiesindex e8b2fb139..579479a1b 100644--- a/cordova/platforms/android/project.properties+++ b/cordova/platforms/android/project.properties@@ -8,8 +8,9 @@# This is the application project. This is only required for Android Studio Gradle projects# Project target.-target=android-27+target=android-29android.library.reference.1=CordovaLibandroid.library.reference.2=appcordova.system.library.1=com.android.support:support-v4:27.+-cordova.system.library.2=com.android.support:support-v4:27.+\ No newline at end of file+cordova.system.library.2=com.android.support:support-v4:27.++cordova.system.library.3=com.android.support:support-v4:24.1.1+diff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.hindex a038dbdee..14c6a66d3 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.h@@ -20,11 +20,7 @@#import <Cordova/CDVPlugin.h>#import <Cordova/CDVWhitelist.h>-#if WK_WEB_VIEW_ONLY#define CDVWebViewNavigationType int-#else-#define CDVWebViewNavigationType UIWebViewNavigationType-#endiftypedef NS_ENUM(NSInteger, CDVIntentAndNavigationFilterValue) {CDVIntentAndNavigationFilterValueIntentAllowed,diff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.mindex b656cd9eb..a098be2b9 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVIntentAndNavigationFilter/CDVIntentAndNavigationFilter.m@@ -46,7 +46,15 @@- (void)parserDidStartDocument:(NSXMLParser*)parser{// file: url <allow-navigations> are added by default- self.allowNavigations = [[NSMutableArray alloc] initWithArray:@[ @"file://" ]];+ // navigation to the scheme used by the app is also allowed+ self.allowNavigations = [[NSMutableArray alloc] initWithArray:@[ @"file://"]];++ // If the custom app scheme is defined, append it to the allow navigation as default+ NSString* scheme = ((CDVViewController*)self.viewController).appScheme;+ if (scheme) {+ [self.allowNavigations addObject: [NSString stringWithFormat:@"%@://", scheme]];+ }+// no intents are added by defaultself.allowIntents = [[NSMutableArray alloc] init];}@@ -95,21 +103,15 @@return [[self class] filterUrl:url intentsWhitelist:self.allowIntentsWhitelist navigationsWhitelist:self.allowNavigationsWhitelist];}-#if WK_WEB_VIEW_ONLY#define CDVWebViewNavigationTypeLinkClicked 0-#define CDVWebViewNavigationTypeOther 5-#else-#define CDVWebViewNavigationTypeLinkClicked UIWebViewNavigationTypeLinkClicked-#define CDVWebViewNavigationTypeOther UIWebViewNavigationTypeOther-#endif+#define CDVWebViewNavigationTypeLinkOther -1+ (BOOL)shouldOpenURLRequest:(NSURLRequest*)request navigationType:(CDVWebViewNavigationType)navigationType{- return (CDVWebViewNavigationTypeLinkClicked == navigationType ||- (CDVWebViewNavigationTypeOther == navigationType &&- [[request.mainDocumentURL absoluteString] isEqualToString:[request.URL absoluteString]]- )- );+ return (+ navigationType == CDVWebViewNavigationTypeLinkClicked ||+ navigationType == CDVWebViewNavigationTypeLinkOther+ );}+ (BOOL)shouldOverrideLoadWithRequest:(NSURLRequest*)request navigationType:(CDVWebViewNavigationType)navigationType filterValue:(CDVIntentAndNavigationFilterValue)filterValue@@ -123,8 +125,7 @@case CDVIntentAndNavigationFilterValueNavigationAllowed:return YES;case CDVIntentAndNavigationFilterValueIntentAllowed:- // only allow-intent if it's a UIWebViewNavigationTypeLinkClicked (anchor tag) OR- // it's a UIWebViewNavigationTypeOther, and it's an internal link+ // only allow-intent if it's a CDVWebViewNavigationTypeLinkClicked (anchor tag) or CDVWebViewNavigationTypeOther and it's an internal linkif ([[self class] shouldOpenURLRequest:request navigationType:navigationType]){[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];}diff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLaunchScreen/CDVLaunchScreen.hsimilarity index 83%rename from cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.hrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLaunchScreen/CDVLaunchScreen.hindex 0561e04d9..e973e373e 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLaunchScreen/CDVLaunchScreen.h@@ -17,11 +17,11 @@under the License.*/-#import <Foundation/Foundation.h>-#import "CDVAvailability.h"+#import <Cordova/CDVPlugin.h>-@class CDVViewController;+@interface CDVLaunchScreen : CDVPlugin-@interface CDVURLProtocol : NSURLProtocol {}+- (void)show:(CDVInvokedUrlCommand*)command;+- (void)hide:(CDVInvokedUrlCommand*)command;@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLaunchScreen/CDVLaunchScreen.msimilarity index 61%rename from cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.hrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLaunchScreen/CDVLaunchScreen.mindex 9b9b31f1f..9ff062af3 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLaunchScreen/CDVLaunchScreen.m@@ -17,17 +17,23 @@under the License.*/-#if !WK_WEB_VIEW_ONLY+#import "CDVLaunchScreen.h"+#import <Cordova/CDVViewController.h>-#import <UIKit/UIKit.h>-#import "CDVUIWebViewEngine.h"+@implementation CDVLaunchScreen-@interface CDVUIWebViewNavigationDelegate : NSObject <UIWebViewDelegate>+- (void)show:(CDVInvokedUrlCommand*)command+{+ if ([self.viewController isKindOfClass:[CDVViewController class]]) {+ [(CDVViewController*)self.viewController showLaunchScreen:YES];+ }+}-@property (nonatomic, weak) CDVPlugin* enginePlugin;--- (instancetype)initWithEnginePlugin:(CDVPlugin*)enginePlugin;+- (void)hide:(CDVInvokedUrlCommand*)command+{+ if ([self.viewController isKindOfClass:[CDVViewController class]]) {+ [(CDVViewController*)self.viewController showLaunchScreen:NO];+ }+}@end--#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.hdeleted file mode 100644index e93675ec2..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.h+++ /dev/null@@ -1,50 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#import <Cordova/CDVPlugin.h>--#define kCDVLocalStorageErrorDomain @"kCDVLocalStorageErrorDomain"-#define kCDVLocalStorageFileOperationError 1--@interface CDVLocalStorage : CDVPlugin--@property (nonatomic, readonly, strong) NSMutableArray* backupInfo;--- (BOOL)shouldBackup;-- (BOOL)shouldRestore;-- (void)backup:(CDVInvokedUrlCommand*)command;-- (void)restore:(CDVInvokedUrlCommand*)command;--+ (void)__fixupDatabaseLocationsWithBackupType:(NSString*)backupType;-// Visible for testing.-+ (BOOL)__verifyAndFixDatabaseLocationsWithAppPlistDict:(NSMutableDictionary*)appPlistDict- bundlePath:(NSString*)bundlePath- fileManager:(NSFileManager*)fileManager;-@end--@interface CDVBackupInfo : NSObject--@property (nonatomic, copy) NSString* original;-@property (nonatomic, copy) NSString* backup;-@property (nonatomic, copy) NSString* label;--- (BOOL)shouldBackup;-- (BOOL)shouldRestore;--@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.mdeleted file mode 100644index 25c48536d..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.m+++ /dev/null@@ -1,493 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#import "CDVLocalStorage.h"-#import <Cordova/CDV.h>--@interface CDVLocalStorage ()--@property (nonatomic, readwrite, strong) NSMutableArray* backupInfo; // array of CDVBackupInfo objects-#if !WK_WEB_VIEW_ONLY-@property (nonatomic, readwrite, weak) id <UIWebViewDelegate> webviewDelegate;-#endif--@end--@implementation CDVLocalStorage--#if WK_WEB_VIEW_ONLY-@synthesize backupInfo;-#else-@synthesize backupInfo, webviewDelegate;-#endif--- (void)pluginInitialize-{- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResignActive)- name:UIApplicationWillResignActiveNotification object:nil];- BOOL cloudBackup = [@"cloud" isEqualToString : self.commandDelegate.settings[[@"BackupWebStorage" lowercaseString]]];-- self.backupInfo = [[self class] createBackupInfoWithCloudBackup:cloudBackup];-}--#pragma mark --#pragma mark Plugin interface methods--+ (NSMutableArray*)createBackupInfoWithTargetDir:(NSString*)targetDir backupDir:(NSString*)backupDir targetDirNests:(BOOL)targetDirNests backupDirNests:(BOOL)backupDirNests rename:(BOOL)rename-{- /*- This "helper" does so much work and has so many options it would probably be clearer to refactor the whole thing.- Basically, there are three database locations:-- 1. "Normal" dir -- LIB/<nested dires WebKit/LocalStorage etc>/<normal filenames>- 2. "Caches" dir -- LIB/Caches/<normal filenames>- 3. "Backup" dir -- DOC/Backups/<renamed filenames>-- And between these three, there are various migration paths, most of which only consider 2 of the 3, which is why this helper is based on 2 locations and has a notion of "direction".- */- NSMutableArray* backupInfo = [NSMutableArray arrayWithCapacity:3];-- NSString* original;- NSString* backup;- CDVBackupInfo* backupItem;-- // ////////// LOCALSTORAGE-- original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/file__0.localstorage":@"file__0.localstorage"];- backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];- backup = [backup stringByAppendingPathComponent:(rename ? @"localstorage.appdata.db" : @"file__0.localstorage")];-- backupItem = [[CDVBackupInfo alloc] init];- backupItem.backup = backup;- backupItem.original = original;- backupItem.label = @"localStorage database";-- [backupInfo addObject:backupItem];-- // ////////// WEBSQL MAIN DB-- original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/Databases.db":@"Databases.db"];- backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];- backup = [backup stringByAppendingPathComponent:(rename ? @"websqlmain.appdata.db" : @"Databases.db")];-- backupItem = [[CDVBackupInfo alloc] init];- backupItem.backup = backup;- backupItem.original = original;- backupItem.label = @"websql main database";-- [backupInfo addObject:backupItem];-- // ////////// WEBSQL DATABASES-- original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/file__0":@"file__0"];- backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];- backup = [backup stringByAppendingPathComponent:(rename ? @"websqldbs.appdata.db" : @"file__0")];-- backupItem = [[CDVBackupInfo alloc] init];- backupItem.backup = backup;- backupItem.original = original;- backupItem.label = @"websql databases";-- [backupInfo addObject:backupItem];-- return backupInfo;-}--+ (NSMutableArray*)createBackupInfoWithCloudBackup:(BOOL)cloudBackup-{- // create backup info from backup folder to caches folder- NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];- NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];- NSString* cacheFolder = [appLibraryFolder stringByAppendingPathComponent:@"Caches"];- NSString* backupsFolder = [appDocumentsFolder stringByAppendingPathComponent:@"Backups"];-- // create the backups folder, if needed- [[NSFileManager defaultManager] createDirectoryAtPath:backupsFolder withIntermediateDirectories:YES attributes:nil error:nil];-- [self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:backupsFolder] skip:!cloudBackup];-- return [self createBackupInfoWithTargetDir:cacheFolder backupDir:backupsFolder targetDirNests:NO backupDirNests:NO rename:YES];-}--+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL*)URL skip:(BOOL)skip-{- NSError* error = nil;- BOOL success = [URL setResourceValue:[NSNumber numberWithBool:skip] forKey:NSURLIsExcludedFromBackupKey error:&error];-- if (!success) {- NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);- }- return success;-}--+ (BOOL)copyFrom:(NSString*)src to:(NSString*)dest error:(NSError* __autoreleasing*)error-{- NSFileManager* fileManager = [NSFileManager defaultManager];-- if (![fileManager fileExistsAtPath:src]) {- NSString* errorString = [NSString stringWithFormat:@"%@ file does not exist.", src];- if (error != NULL) {- (*error) = [NSError errorWithDomain:kCDVLocalStorageErrorDomain- code:kCDVLocalStorageFileOperationError- userInfo:[NSDictionary dictionaryWithObject:errorString- forKey:NSLocalizedDescriptionKey]];- }- return NO;- }-- // generate unique filepath in temp directory- CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);- CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef);- NSString* tempBackup = [[NSTemporaryDirectory() stringByAppendingPathComponent:(__bridge NSString*)uuidString] stringByAppendingPathExtension:@"bak"];- CFRelease(uuidString);- CFRelease(uuidRef);-- BOOL destExists = [fileManager fileExistsAtPath:dest];-- // backup the dest- if (destExists && ![fileManager copyItemAtPath:dest toPath:tempBackup error:error]) {- return NO;- }-- // remove the dest- if (destExists && ![fileManager removeItemAtPath:dest error:error]) {- return NO;- }-- // create path to dest- if (!destExists && ![fileManager createDirectoryAtPath:[dest stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:error]) {- return NO;- }-- // copy src to dest- if ([fileManager copyItemAtPath:src toPath:dest error:error]) {- // success - cleanup - delete the backup to the dest- if ([fileManager fileExistsAtPath:tempBackup]) {- [fileManager removeItemAtPath:tempBackup error:error];- }- return YES;- } else {- // failure - we restore the temp backup file to dest- [fileManager copyItemAtPath:tempBackup toPath:dest error:error];- // cleanup - delete the backup to the dest- if ([fileManager fileExistsAtPath:tempBackup]) {- [fileManager removeItemAtPath:tempBackup error:error];- }- return NO;- }-}--- (BOOL)shouldBackup-{- for (CDVBackupInfo* info in self.backupInfo) {- if ([info shouldBackup]) {- return YES;- }- }-- return NO;-}--- (BOOL)shouldRestore-{- for (CDVBackupInfo* info in self.backupInfo) {- if ([info shouldRestore]) {- return YES;- }- }-- return NO;-}--/* copy from webkitDbLocation to persistentDbLocation */-- (void)backup:(CDVInvokedUrlCommand*)command-{- NSString* callbackId = command.callbackId;-- NSError* __autoreleasing error = nil;- CDVPluginResult* result = nil;- NSString* message = nil;-- for (CDVBackupInfo* info in self.backupInfo) {- if ([info shouldBackup]) {- [[self class] copyFrom:info.original to:info.backup error:&error];-- if (callbackId) {- if (error == nil) {- message = [NSString stringWithFormat:@"Backed up: %@", info.label];- NSLog(@"%@", message);-- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];- [self.commandDelegate sendPluginResult:result callbackId:callbackId];- } else {- message = [NSString stringWithFormat:@"Error in CDVLocalStorage (%@) backup: %@", info.label, [error localizedDescription]];- NSLog(@"%@", message);-- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];- [self.commandDelegate sendPluginResult:result callbackId:callbackId];- }- }- }- }-}--/* copy from persistentDbLocation to webkitDbLocation */-- (void)restore:(CDVInvokedUrlCommand*)command-{- NSError* __autoreleasing error = nil;- CDVPluginResult* result = nil;- NSString* message = nil;-- for (CDVBackupInfo* info in self.backupInfo) {- if ([info shouldRestore]) {- [[self class] copyFrom:info.backup to:info.original error:&error];-- if (error == nil) {- message = [NSString stringWithFormat:@"Restored: %@", info.label];- NSLog(@"%@", message);-- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];- } else {- message = [NSString stringWithFormat:@"Error in CDVLocalStorage (%@) restore: %@", info.label, [error localizedDescription]];- NSLog(@"%@", message);-- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];- }- }- }-}--+ (void)__fixupDatabaseLocationsWithBackupType:(NSString*)backupType-{- [self __verifyAndFixDatabaseLocations];- [self __restoreLegacyDatabaseLocationsWithBackupType:backupType];-}--+ (void)__verifyAndFixDatabaseLocations-{- NSBundle* mainBundle = [NSBundle mainBundle];- NSString* bundlePath = [[mainBundle bundlePath] stringByDeletingLastPathComponent];- NSString* bundleIdentifier = [[mainBundle infoDictionary] objectForKey:@"CFBundleIdentifier"];- NSString* appPlistPath = [bundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"Library/Preferences/%@.plist", bundleIdentifier]];-- NSMutableDictionary* appPlistDict = [NSMutableDictionary dictionaryWithContentsOfFile:appPlistPath];- BOOL modified = [[self class] __verifyAndFixDatabaseLocationsWithAppPlistDict:appPlistDict- bundlePath:bundlePath- fileManager:[NSFileManager defaultManager]];-- if (modified) {- BOOL ok = [appPlistDict writeToFile:appPlistPath atomically:YES];- [[NSUserDefaults standardUserDefaults] synchronize];- NSLog(@"Fix applied for database locations?: %@", ok ? @"YES" : @"NO");- }-}--+ (BOOL)__verifyAndFixDatabaseLocationsWithAppPlistDict:(NSMutableDictionary*)appPlistDict- bundlePath:(NSString*)bundlePath- fileManager:(NSFileManager*)fileManager-{- NSString* libraryCaches = @"Library/Caches";- NSString* libraryWebKit = @"Library/WebKit";-- NSArray* keysToCheck = [NSArray arrayWithObjects:- @"WebKitLocalStorageDatabasePathPreferenceKey",- @"WebDatabaseDirectory",- nil];-- BOOL dirty = NO;-- for (NSString* key in keysToCheck) {- NSString* value = [appPlistDict objectForKey:key];- // verify key exists, and path is in app bundle, if not - fix- if ((value != nil) && ![value hasPrefix:bundlePath]) {- // the pathSuffix to use may be wrong - OTA upgrades from < 5.1 to 5.1 do keep the old path Library/WebKit,- // while Xcode synced ones do change the storage location to Library/Caches- NSString* newBundlePath = [bundlePath stringByAppendingPathComponent:libraryCaches];- if (![fileManager fileExistsAtPath:newBundlePath]) {- newBundlePath = [bundlePath stringByAppendingPathComponent:libraryWebKit];- }- [appPlistDict setValue:newBundlePath forKey:key];- dirty = YES;- }- }-- return dirty;-}--+ (void)__restoreLegacyDatabaseLocationsWithBackupType:(NSString*)backupType-{- // on iOS 6, if you toggle between cloud/local backup, you must move database locations. Default upgrade from iOS5.1 to iOS6 is like a toggle from local to cloud.- NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];- NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];-- NSMutableArray* backupInfo = [NSMutableArray arrayWithCapacity:0];-- if ([backupType isEqualToString:@"cloud"]) {-#ifdef DEBUG- NSLog(@"\n\nStarted backup to iCloud! Please be careful."- "\nYour application might be rejected by Apple if you store too much data."- "\nFor more information please read \"iOS Data Storage Guidelines\" at:"- "\nhttps://developer.apple.com/icloud/documentation/data-storage/"- "\nTo disable web storage backup to iCloud, set the BackupWebStorage preference to \"local\" in the Cordova config.xml file\n\n");-#endif- // We would like to restore old backups/caches databases to the new destination (nested in lib folder)- [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:appLibraryFolder backupDir:[appDocumentsFolder stringByAppendingPathComponent:@"Backups"] targetDirNests:YES backupDirNests:NO rename:YES]];- [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:appLibraryFolder backupDir:[appLibraryFolder stringByAppendingPathComponent:@"Caches"] targetDirNests:YES backupDirNests:NO rename:NO]];- } else {- // For ios6 local backups we also want to restore from Backups dir -- but we don't need to do that here, since the plugin will do that itself.- [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:[appLibraryFolder stringByAppendingPathComponent:@"Caches"] backupDir:appLibraryFolder targetDirNests:NO backupDirNests:YES rename:NO]];- }-- NSFileManager* manager = [NSFileManager defaultManager];-- for (CDVBackupInfo* info in backupInfo) {- if ([manager fileExistsAtPath:info.backup]) {- if ([info shouldRestore]) {- NSLog(@"Restoring old webstorage backup. From: '%@' To: '%@'.", info.backup, info.original);- [self copyFrom:info.backup to:info.original error:nil];- }- NSLog(@"Removing old webstorage backup: '%@'.", info.backup);- [manager removeItemAtPath:info.backup error:nil];- }- }-- [[NSUserDefaults standardUserDefaults] setBool:[backupType isEqualToString:@"cloud"] forKey:@"WebKitStoreWebDataForBackup"];-}--#pragma mark --#pragma mark Notification handlers--- (void)onResignActive-{- UIDevice* device = [UIDevice currentDevice];- NSNumber* exitsOnSuspend = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIApplicationExitsOnSuspend"];-- BOOL isMultitaskingSupported = [device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported];-- if (exitsOnSuspend == nil) { // if it's missing, it should be NO (i.e. multi-tasking on by default)- exitsOnSuspend = [NSNumber numberWithBool:NO];- }-- if (exitsOnSuspend) {- [self backup:nil];- } else if (isMultitaskingSupported) {- __block UIBackgroundTaskIdentifier backgroundTaskID = UIBackgroundTaskInvalid;-- backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{- [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];- backgroundTaskID = UIBackgroundTaskInvalid;- NSLog(@"Background task to backup WebSQL/LocalStorage expired.");- }];- CDVLocalStorage __weak* weakSelf = self;- [self.commandDelegate runInBackground:^{- [weakSelf backup:nil];-- [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];- backgroundTaskID = UIBackgroundTaskInvalid;- }];- }-}--- (void)onAppTerminate-{- [self onResignActive];-}--- (void)onReset-{- [self restore:nil];-}--@end--#pragma mark --#pragma mark CDVBackupInfo implementation--@implementation CDVBackupInfo--@synthesize original, backup, label;--- (BOOL)file:(NSString*)aPath isNewerThanFile:(NSString*)bPath-{- NSFileManager* fileManager = [NSFileManager defaultManager];- NSError* __autoreleasing error = nil;-- NSDictionary* aPathAttribs = [fileManager attributesOfItemAtPath:aPath error:&error];- NSDictionary* bPathAttribs = [fileManager attributesOfItemAtPath:bPath error:&error];-- NSDate* aPathModDate = [aPathAttribs objectForKey:NSFileModificationDate];- NSDate* bPathModDate = [bPathAttribs objectForKey:NSFileModificationDate];-- if ((nil == aPathModDate) && (nil == bPathModDate)) {- return NO;- }-- return [aPathModDate compare:bPathModDate] == NSOrderedDescending || bPathModDate == nil;-}--- (BOOL)item:(NSString*)aPath isNewerThanItem:(NSString*)bPath-{- NSFileManager* fileManager = [NSFileManager defaultManager];-- BOOL aPathIsDir = NO, bPathIsDir = NO;- BOOL aPathExists = [fileManager fileExistsAtPath:aPath isDirectory:&aPathIsDir];-- [fileManager fileExistsAtPath:bPath isDirectory:&bPathIsDir];-- if (!aPathExists) {- return NO;- }-- if (!(aPathIsDir && bPathIsDir)) { // just a file- return [self file:aPath isNewerThanFile:bPath];- }-- // essentially we want rsync here, but have to settle for our poor man's implementation- // we get the files in aPath, and see if it is newer than the file in bPath- // (it is newer if it doesn't exist in bPath) if we encounter the FIRST file that is newer,- // we return YES- NSDirectoryEnumerator* directoryEnumerator = [fileManager enumeratorAtPath:aPath];- NSString* path;-- while ((path = [directoryEnumerator nextObject])) {- NSString* aPathFile = [aPath stringByAppendingPathComponent:path];- NSString* bPathFile = [bPath stringByAppendingPathComponent:path];-- BOOL isNewer = [self file:aPathFile isNewerThanFile:bPathFile];- if (isNewer) {- return YES;- }- }-- return NO;-}--- (BOOL)shouldBackup-{- return [self item:self.original isNewerThanItem:self.backup];-}--- (BOOL)shouldRestore-{- return [self item:self.backup isNewerThanItem:self.original];-}--@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.hdeleted file mode 100644index 8118d5f04..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.h+++ /dev/null@@ -1,45 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#if !WK_WEB_VIEW_ONLY--#import <UIKit/UIKit.h>-#import <Cordova/CDVAvailability.h>--/**- * Distinguishes top-level navigations from sub-frame navigations.- * shouldStartLoadWithRequest is called for every request, but didStartLoad- * and didFinishLoad is called only for top-level navigations.- * Relevant bug: CB-2389- */-@interface CDVUIWebViewDelegate : NSObject <UIWebViewDelegate>{- __weak NSObject <UIWebViewDelegate>* _delegate;- NSInteger _loadCount;- NSInteger _state;- NSInteger _curLoadToken;- NSInteger _loadStartPollCount;-}--- (id)initWithDelegate:(NSObject <UIWebViewDelegate>*)delegate;--- (BOOL)request:(NSURLRequest*)newRequest isEqualToRequestAfterStrippingFragments:(NSURLRequest*)originalRequest;--@end--#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.mdeleted file mode 100644index ddef8be13..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewDelegate.m+++ /dev/null@@ -1,408 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--//-// Testing shows:-//-// In all cases, webView.request.URL is the previous page's URL (or empty) during the didStartLoad callback.-// When loading a page with a redirect:-// 1. shouldStartLoading (requestURL is target page)-// 2. didStartLoading-// 3. shouldStartLoading (requestURL is redirect target)-// 4. didFinishLoad (request.URL is redirect target)-//-// Note the lack of a second didStartLoading **-//-// When loading a page with iframes:-// 1. shouldStartLoading (requestURL is main page)-// 2. didStartLoading-// 3. shouldStartLoading (requestURL is one of the iframes)-// 4. didStartLoading-// 5. didFinishLoad-// 6. didFinishLoad-//-// Note there is no way to distinguish which didFinishLoad maps to which didStartLoad **-//-// Loading a page by calling window.history.go(-1):-// 1. didStartLoading-// 2. didFinishLoad-//-// Note the lack of a shouldStartLoading call **-// Actually - this is fixed on iOS6. iOS6 has a shouldStart. **-//-// Loading a page by calling location.reload()-// 1. shouldStartLoading-// 2. didStartLoading-// 3. didFinishLoad-//-// Loading a page with an iframe that fails to load:-// 1. shouldStart (main page)-// 2. didStart-// 3. shouldStart (iframe)-// 4. didStart-// 5. didFailWithError-// 6. didFinish-//-// Loading a page with an iframe that fails to load due to an invalid URL:-// 1. shouldStart (main page)-// 2. didStart-// 3. shouldStart (iframe)-// 5. didFailWithError-// 6. didFinish-//-// This case breaks our logic since there is a missing didStart. To prevent this,-// we check URLs in shouldStart and return NO if they are invalid.-//-// Loading a page with an invalid URL-// 1. shouldStart (main page)-// 2. didFailWithError-//-// TODO: Record order when page is re-navigated before the first navigation finishes.-//--#if !WK_WEB_VIEW_ONLY--#import "CDVUIWebViewDelegate.h"--// #define VerboseLog NSLog-#define VerboseLog(...) do { \-} while (0)--typedef enum {- STATE_IDLE = 0,- STATE_WAITING_FOR_LOAD_START = 1,- STATE_WAITING_FOR_LOAD_FINISH = 2,- STATE_IOS5_POLLING_FOR_LOAD_START = 3,- STATE_IOS5_POLLING_FOR_LOAD_FINISH = 4,- STATE_CANCELLED = 5-} State;--static NSString *stripFragment(NSString* url)-{- NSRange r = [url rangeOfString:@"#"];-- if (r.location == NSNotFound) {- return url;- }- return [url substringToIndex:r.location];-}--@implementation CDVUIWebViewDelegate--- (id)initWithDelegate:(NSObject <UIWebViewDelegate>*)delegate-{- self = [super init];- if (self != nil) {- _delegate = delegate;- _loadCount = -1;- _state = STATE_IDLE;- }- return self;-}--- (BOOL)request:(NSURLRequest*)newRequest isEqualToRequestAfterStrippingFragments:(NSURLRequest*)originalRequest-{- if (originalRequest.URL && newRequest.URL) {- NSString* originalRequestUrl = [originalRequest.URL absoluteString];- NSString* newRequestUrl = [newRequest.URL absoluteString];-- NSString* baseOriginalRequestUrl = stripFragment(originalRequestUrl);- NSString* baseNewRequestUrl = stripFragment(newRequestUrl);- return [baseOriginalRequestUrl isEqualToString:baseNewRequestUrl];- }-- return NO;-}--- (BOOL)isPageLoaded:(UIWebView*)webView-{- NSString* readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];-- return [readyState isEqualToString:@"loaded"] || [readyState isEqualToString:@"complete"];-}--- (BOOL)isJsLoadTokenSet:(UIWebView*)webView-{- NSString* loadToken = [webView stringByEvaluatingJavaScriptFromString:@"window.__cordovaLoadToken"];-- return [[NSString stringWithFormat:@"%ld", (long)_curLoadToken] isEqualToString:loadToken];-}--- (void)setLoadToken:(UIWebView*)webView-{- _curLoadToken += 1;- [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.__cordovaLoadToken=%ld", (long)_curLoadToken]];-}--- (NSString*)evalForCurrentURL:(UIWebView*)webView-{- return [webView stringByEvaluatingJavaScriptFromString:@"location.href"];-}--- (void)pollForPageLoadStart:(UIWebView*)webView-{- if (_state != STATE_IOS5_POLLING_FOR_LOAD_START) {- return;- }- if (![self isJsLoadTokenSet:webView]) {- VerboseLog(@"Polled for page load start. result = YES!");- _state = STATE_IOS5_POLLING_FOR_LOAD_FINISH;- [self setLoadToken:webView];- if ([_delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {- [_delegate webViewDidStartLoad:webView];- }- [self pollForPageLoadFinish:webView];- } else {- VerboseLog(@"Polled for page load start. result = NO");- // Poll only for 1 second, and then fall back on checking only when delegate methods are called.- ++_loadStartPollCount;- if (_loadStartPollCount < (1000 * .05)) {- [self performSelector:@selector(pollForPageLoadStart:) withObject:webView afterDelay:.05];- }- }-}--- (void)pollForPageLoadFinish:(UIWebView*)webView-{- if (_state != STATE_IOS5_POLLING_FOR_LOAD_FINISH) {- return;- }- if ([self isPageLoaded:webView]) {- VerboseLog(@"Polled for page load finish. result = YES!");- _state = STATE_IDLE;- if ([_delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {- [_delegate webViewDidFinishLoad:webView];- }- } else {- VerboseLog(@"Polled for page load finish. result = NO");- [self performSelector:@selector(pollForPageLoadFinish:) withObject:webView afterDelay:.05];- }-}--- (BOOL)shouldLoadRequest:(NSURLRequest*)request-{- NSString* scheme = [[request URL] scheme];- NSArray* allowedSchemes = [NSArray arrayWithObjects:@"mailto",@"tel",@"blob",@"sms",@"data", nil];- if([allowedSchemes containsObject:scheme]) {- return YES;- }- else {- return [NSURLConnection canHandleRequest:request];- }-}--- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType-{- BOOL shouldLoad = YES;-- if ([_delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {- shouldLoad = [_delegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];- }-- VerboseLog(@"webView shouldLoad=%d (before) state=%d loadCount=%d URL=%@", shouldLoad, _state, _loadCount, request.URL);-- if (shouldLoad) {- // When devtools refresh occurs, it blindly uses the same request object. If a history.replaceState() has occured, then- // mainDocumentURL != URL even though it's a top-level navigation.- BOOL isDevToolsRefresh = (request == webView.request);- BOOL isTopLevelNavigation = isDevToolsRefresh || [request.URL isEqual:[request mainDocumentURL]];- if (isTopLevelNavigation) {- // Ignore hash changes that don't navigate to a different page.- // webView.request does actually update when history.replaceState() gets called.- if ([self request:request isEqualToRequestAfterStrippingFragments:webView.request]) {- NSString* prevURL = [self evalForCurrentURL:webView];- if ([prevURL isEqualToString:[request.URL absoluteString]]) {- VerboseLog(@"Page reload detected.");- } else {- VerboseLog(@"Detected hash change shouldLoad");- return shouldLoad;- }- }-- switch (_state) {- case STATE_WAITING_FOR_LOAD_FINISH:- // Redirect case.- // We expect loadCount == 1.- if (_loadCount != 1) {- NSLog(@"CDVWebViewDelegate: Detected redirect when loadCount=%ld", (long)_loadCount);- }- break;-- case STATE_IDLE:- case STATE_IOS5_POLLING_FOR_LOAD_START:- case STATE_CANCELLED:- // Page navigation start.- _loadCount = 0;- _state = STATE_WAITING_FOR_LOAD_START;- break;-- default:- {- NSString* description = [NSString stringWithFormat:@"CDVWebViewDelegate: Navigation started when state=%ld", (long)_state];- NSLog(@"%@", description);- _loadCount = 0;- _state = STATE_WAITING_FOR_LOAD_START;-- NSDictionary* errorDictionary = @{NSLocalizedDescriptionKey : description};- NSError* error = [[NSError alloc] initWithDomain:@"CDVUIWebViewDelegate" code:1 userInfo:errorDictionary];- [self webView:webView didFailLoadWithError:error];- }- }- } else {- // Deny invalid URLs so that we don't get the case where we go straight from- // webViewShouldLoad -> webViewDidFailLoad (messes up _loadCount).- shouldLoad = shouldLoad && [self shouldLoadRequest:request];- }- VerboseLog(@"webView shouldLoad=%d (after) isTopLevelNavigation=%d state=%d loadCount=%d", shouldLoad, isTopLevelNavigation, _state, _loadCount);- }- return shouldLoad;-}--- (void)webViewDidStartLoad:(UIWebView*)webView-{- VerboseLog(@"webView didStartLoad (before). state=%d loadCount=%d", _state, _loadCount);- BOOL fireCallback = NO;- switch (_state) {- case STATE_IDLE:- break;-- case STATE_CANCELLED:- fireCallback = YES;- _state = STATE_WAITING_FOR_LOAD_FINISH;- _loadCount += 1;- break;-- case STATE_WAITING_FOR_LOAD_START:- if (_loadCount != 0) {- NSLog(@"CDVWebViewDelegate: Unexpected loadCount in didStart. count=%ld", (long)_loadCount);- }- fireCallback = YES;- _state = STATE_WAITING_FOR_LOAD_FINISH;- _loadCount = 1;- break;-- case STATE_WAITING_FOR_LOAD_FINISH:- _loadCount += 1;- break;-- case STATE_IOS5_POLLING_FOR_LOAD_START:- [self pollForPageLoadStart:webView];- break;-- case STATE_IOS5_POLLING_FOR_LOAD_FINISH:- [self pollForPageLoadFinish:webView];- break;-- default:- NSLog(@"CDVWebViewDelegate: Unexpected didStart with state=%ld loadCount=%ld", (long)_state, (long)_loadCount);- }- VerboseLog(@"webView didStartLoad (after). state=%d loadCount=%d fireCallback=%d", _state, _loadCount, fireCallback);- if (fireCallback && [_delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {- [_delegate webViewDidStartLoad:webView];- }-}--- (void)webViewDidFinishLoad:(UIWebView*)webView-{- VerboseLog(@"webView didFinishLoad (before). state=%d loadCount=%d", _state, _loadCount);- BOOL fireCallback = NO;- switch (_state) {- case STATE_IDLE:- break;-- case STATE_WAITING_FOR_LOAD_START:- NSLog(@"CDVWebViewDelegate: Unexpected didFinish while waiting for load start.");- break;-- case STATE_WAITING_FOR_LOAD_FINISH:- // fix call loadRequest multiple times just callback webViewDidFinishLoad once time in iOS 12- if (@available(iOS 12.0, *)) {- fireCallback = YES;- } else {- if (_loadCount == 1) {- fireCallback = YES;- _state = STATE_IDLE;- }- }- _loadCount -= 1;- break;-- case STATE_IOS5_POLLING_FOR_LOAD_START:- [self pollForPageLoadStart:webView];- break;-- case STATE_IOS5_POLLING_FOR_LOAD_FINISH:- [self pollForPageLoadFinish:webView];- break;- }- VerboseLog(@"webView didFinishLoad (after). state=%d loadCount=%d fireCallback=%d", _state, _loadCount, fireCallback);- if (fireCallback && [_delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {- [_delegate webViewDidFinishLoad:webView];- }-}--- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error-{- VerboseLog(@"webView didFailLoad (before). state=%d loadCount=%d", _state, _loadCount);- BOOL fireCallback = NO;-- switch (_state) {- case STATE_IDLE:- break;-- case STATE_WAITING_FOR_LOAD_START:- if ([error code] == NSURLErrorCancelled) {- _state = STATE_CANCELLED;- } else {- _state = STATE_IDLE;- }- fireCallback = YES;- break;-- case STATE_WAITING_FOR_LOAD_FINISH:- if ([error code] != NSURLErrorCancelled) {- if (_loadCount == 1) {- _state = STATE_IDLE;- fireCallback = YES;- }- _loadCount = -1;- } else {- fireCallback = YES;- _state = STATE_CANCELLED;- _loadCount -= 1;- }- break;-- case STATE_IOS5_POLLING_FOR_LOAD_START:- [self pollForPageLoadStart:webView];- break;-- case STATE_IOS5_POLLING_FOR_LOAD_FINISH:- [self pollForPageLoadFinish:webView];- break;- }- VerboseLog(@"webView didFailLoad (after). state=%d loadCount=%d, fireCallback=%d", _state, _loadCount, fireCallback);- if (fireCallback && [_delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {- [_delegate webView:webView didFailLoadWithError:error];- }-}--@end--#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.hdeleted file mode 100644index 9b4bf187a..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.h+++ /dev/null@@ -1,29 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#import <Cordova/CDVPlugin.h>-#import <Cordova/CDVWebViewEngineProtocol.h>--@interface CDVUIWebViewEngine : CDVPlugin <CDVWebViewEngineProtocol>--#if !WK_WEB_VIEW_ONLY-@property (nonatomic, strong, readonly) id <UIWebViewDelegate> uiWebViewDelegate;-#endif--@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.mdeleted file mode 100644index e5767b5be..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewEngine.m+++ /dev/null@@ -1,206 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#if !WK_WEB_VIEW_ONLY--#import "CDVUIWebViewEngine.h"-#import "CDVUIWebViewDelegate.h"-#import "CDVUIWebViewNavigationDelegate.h"-#import "NSDictionary+CordovaPreferences.h"--#import <objc/message.h>--@interface CDVUIWebViewEngine ()--@property (nonatomic, strong, readwrite) UIView* engineWebView;-@property (nonatomic, strong, readwrite) id <UIWebViewDelegate> uiWebViewDelegate;-@property (nonatomic, strong, readwrite) CDVUIWebViewNavigationDelegate* navWebViewDelegate;--@end--@implementation CDVUIWebViewEngine--@synthesize engineWebView = _engineWebView;--- (instancetype)initWithFrame:(CGRect)frame-{- self = [super init];- if (self) {- self.engineWebView = [[UIWebView alloc] initWithFrame:frame];- NSLog(@"Using UIWebView");- }-- return self;-}--- (void)pluginInitialize-{- // viewController would be available now. we attempt to set all possible delegates to it, by default-- UIWebView* uiWebView = (UIWebView*)_engineWebView;-- if ([self.viewController conformsToProtocol:@protocol(UIWebViewDelegate)]) {- self.uiWebViewDelegate = [[CDVUIWebViewDelegate alloc] initWithDelegate:(id <UIWebViewDelegate>)self.viewController];- uiWebView.delegate = self.uiWebViewDelegate;- } else {- self.navWebViewDelegate = [[CDVUIWebViewNavigationDelegate alloc] initWithEnginePlugin:self];- self.uiWebViewDelegate = [[CDVUIWebViewDelegate alloc] initWithDelegate:self.navWebViewDelegate];- uiWebView.delegate = self.uiWebViewDelegate;- }-- [self updateSettings:self.commandDelegate.settings];-}--- (void)evaluateJavaScript:(NSString*)javaScriptString completionHandler:(void (^)(id, NSError*))completionHandler-{- NSString* ret = [(UIWebView*)_engineWebView stringByEvaluatingJavaScriptFromString:javaScriptString];-- if (completionHandler) {- completionHandler(ret, nil);- }-}--- (id)loadRequest:(NSURLRequest*)request-{- [(UIWebView*)_engineWebView loadRequest:request];- return nil;-}--- (id)loadHTMLString:(NSString*)string baseURL:(NSURL*)baseURL-{- [(UIWebView*)_engineWebView loadHTMLString:string baseURL:baseURL];- return nil;-}--- (NSURL*)URL-{- return [[(UIWebView*)_engineWebView request] URL];-}--- (BOOL) canLoadRequest:(NSURLRequest*)request-{- return (request != nil);-}--- (void)updateSettings:(NSDictionary*)settings-{- UIWebView* uiWebView = (UIWebView*)_engineWebView;-- uiWebView.scalesPageToFit = [settings cordovaBoolSettingForKey:@"EnableViewportScale" defaultValue:NO];- uiWebView.allowsInlineMediaPlayback = [settings cordovaBoolSettingForKey:@"AllowInlineMediaPlayback" defaultValue:NO];- uiWebView.mediaPlaybackRequiresUserAction = [settings cordovaBoolSettingForKey:@"MediaPlaybackRequiresUserAction" defaultValue:YES];- uiWebView.mediaPlaybackAllowsAirPlay = [settings cordovaBoolSettingForKey:@"MediaPlaybackAllowsAirPlay" defaultValue:YES];- uiWebView.keyboardDisplayRequiresUserAction = [settings cordovaBoolSettingForKey:@"KeyboardDisplayRequiresUserAction" defaultValue:YES];- uiWebView.suppressesIncrementalRendering = [settings cordovaBoolSettingForKey:@"SuppressesIncrementalRendering" defaultValue:NO];- uiWebView.gapBetweenPages = [settings cordovaFloatSettingForKey:@"GapBetweenPages" defaultValue:0.0];- uiWebView.pageLength = [settings cordovaFloatSettingForKey:@"PageLength" defaultValue:0.0];-- id prefObj = nil;-- // By default, DisallowOverscroll is false (thus bounce is allowed)- BOOL bounceAllowed = !([settings cordovaBoolSettingForKey:@"DisallowOverscroll" defaultValue:NO]);-- // prevent webView from bouncing- if (!bounceAllowed) {- if ([uiWebView respondsToSelector:@selector(scrollView)]) {- ((UIScrollView*)[uiWebView scrollView]).bounces = NO;- } else {- for (id subview in self.webView.subviews) {- if ([[subview class] isSubclassOfClass:[UIScrollView class]]) {- ((UIScrollView*)subview).bounces = NO;- }- }- }- }-- NSString* decelerationSetting = [settings cordovaSettingForKey:@"UIWebViewDecelerationSpeed"];- if (![@"fast" isEqualToString:decelerationSetting]) {- [uiWebView.scrollView setDecelerationRate:UIScrollViewDecelerationRateNormal];- }-- NSInteger paginationBreakingMode = 0; // default - UIWebPaginationBreakingModePage- prefObj = [settings cordovaSettingForKey:@"PaginationBreakingMode"];- if (prefObj != nil) {- NSArray* validValues = @[@"page", @"column"];- NSString* prefValue = [validValues objectAtIndex:0];-- if ([prefObj isKindOfClass:[NSString class]]) {- prefValue = prefObj;- }-- paginationBreakingMode = [validValues indexOfObject:[prefValue lowercaseString]];- if (paginationBreakingMode == NSNotFound) {- paginationBreakingMode = 0;- }- }- uiWebView.paginationBreakingMode = paginationBreakingMode;-- NSInteger paginationMode = 0; // default - UIWebPaginationModeUnpaginated- prefObj = [settings cordovaSettingForKey:@"PaginationMode"];- if (prefObj != nil) {- NSArray* validValues = @[@"unpaginated", @"lefttoright", @"toptobottom", @"bottomtotop", @"righttoleft"];- NSString* prefValue = [validValues objectAtIndex:0];-- if ([prefObj isKindOfClass:[NSString class]]) {- prefValue = prefObj;- }-- paginationMode = [validValues indexOfObject:[prefValue lowercaseString]];- if (paginationMode == NSNotFound) {- paginationMode = 0;- }- }- uiWebView.paginationMode = paginationMode;-}--- (void)updateWithInfo:(NSDictionary*)info-{- UIWebView* uiWebView = (UIWebView*)_engineWebView;-- id <UIWebViewDelegate> uiWebViewDelegate = [info objectForKey:kCDVWebViewEngineUIWebViewDelegate];- NSDictionary* settings = [info objectForKey:kCDVWebViewEngineWebViewPreferences];-- if (uiWebViewDelegate &&- [uiWebViewDelegate conformsToProtocol:@protocol(UIWebViewDelegate)]) {- self.uiWebViewDelegate = [[CDVUIWebViewDelegate alloc] initWithDelegate:(id <UIWebViewDelegate>)uiWebViewDelegate];- uiWebView.delegate = self.uiWebViewDelegate;- }-- if (settings && [settings isKindOfClass:[NSDictionary class]]) {- [self updateSettings:settings];- }-}--// This forwards the methods that are in the header that are not implemented here.-// Both WKWebView and UIWebView implement the below:-// loadHTMLString:baseURL:-// loadRequest:-- (id)forwardingTargetForSelector:(SEL)aSelector-{- return _engineWebView;-}--- (UIView*)webView-{- return self.engineWebView;-}--@end--#endifdiff --git a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.mdeleted file mode 100644index a918e2d7b..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVUIWebViewEngine/CDVUIWebViewNavigationDelegate.m+++ /dev/null@@ -1,157 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#if !WK_WEB_VIEW_ONLY--#import "CDVUIWebViewNavigationDelegate.h"-#import <Cordova/CDVViewController.h>-#import <Cordova/CDVCommandDelegateImpl.h>-#import <Cordova/CDVUserAgentUtil.h>-#import <objc/message.h>--@implementation CDVUIWebViewNavigationDelegate--- (instancetype)initWithEnginePlugin:(CDVPlugin*)theEnginePlugin-{- self = [super init];- if (self) {- self.enginePlugin = theEnginePlugin;- }-- return self;-}--/**- When web application loads Add stuff to the DOM, mainly the user-defined settings from the Settings.plist file, and- the device's data such as device ID, platform version, etc.- */-- (void)webViewDidStartLoad:(UIWebView*)theWebView-{- NSLog(@"Resetting plugins due to page load.");- CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;-- [vc.commandQueue resetRequestId];- [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginResetNotification object:self.enginePlugin.webView]];-}--/**- Called when the webview finishes loading. This stops the activity view.- */-- (void)webViewDidFinishLoad:(UIWebView*)theWebView-{- NSLog(@"Finished load of: %@", theWebView.request.URL);- CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;-- // It's safe to release the lock even if this is just a sub-frame that's finished loading.- [CDVUserAgentUtil releaseLock:vc.userAgentLockToken];-- /*- * Hide the Top Activity THROBBER in the Battery Bar- */- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];-- [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPageDidLoadNotification object:self.enginePlugin.webView]];-}--- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error-{- CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;-- [CDVUserAgentUtil releaseLock:vc.userAgentLockToken];-- NSString* message = [NSString stringWithFormat:@"Failed to load webpage with error: %@", [error localizedDescription]];- NSLog(@"%@", message);-- NSURL* errorUrl = vc.errorURL;- if (errorUrl) {- errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [message stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]] relativeToURL:errorUrl];- NSLog(@"%@", [errorUrl absoluteString]);- if(error.code != NSURLErrorCancelled) {- [theWebView loadRequest:[NSURLRequest requestWithURL:errorUrl]];- }- }-}--- (BOOL)defaultResourcePolicyForURL:(NSURL*)url-{- /*- * If a URL is being loaded that's a file url, just load it internally- */- if ([url isFileURL]) {- return YES;- }-- return NO;-}--- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType-{- NSURL* url = [request URL];- CDVViewController* vc = (CDVViewController*)self.enginePlugin.viewController;-- /*- * Execute any commands queued with cordova.exec() on the JS side.- * The part of the URL after gap:// is irrelevant.- */- if ([[url scheme] isEqualToString:@"gap"]) {- [vc.commandQueue fetchCommandsFromJs];- // The delegate is called asynchronously in this case, so we don't have to use- // flushCommandQueueWithDelayedJs (setTimeout(0)) as we do with hash changes.- [vc.commandQueue executePending];- return NO;- }-- /*- * Give plugins the chance to handle the url- */- BOOL anyPluginsResponded = NO;- BOOL shouldAllowRequest = NO;-- for (NSString* pluginName in vc.pluginObjects) {- CDVPlugin* plugin = [vc.pluginObjects objectForKey:pluginName];- SEL selector = NSSelectorFromString(@"shouldOverrideLoadWithRequest:navigationType:");- if ([plugin respondsToSelector:selector]) {- anyPluginsResponded = YES;- shouldAllowRequest = (((BOOL (*)(id, SEL, id, int))objc_msgSend)(plugin, selector, request, navigationType));- if (!shouldAllowRequest) {- break;- }- }- }-- if (anyPluginsResponded) {- return shouldAllowRequest;- }-- /*- * Handle all other types of urls (tel:, sms:), and requests to load a url in the main webview.- */- BOOL shouldAllowNavigation = [self defaultResourcePolicyForURL:url];- if (shouldAllowNavigation) {- return YES;- } else {- [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];- }-- return NO;-}--@end--#endifdiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewEngine.hsimilarity index 89%rename from cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.hrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewEngine.hindex c71f4e21b..47e26d1e3 100644--- a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewEngine.h@@ -20,7 +20,7 @@#import <WebKit/WebKit.h>#import <Cordova/CDV.h>-@interface CDVWKWebViewEngine : CDVPlugin <CDVWebViewEngineProtocol, WKScriptMessageHandler, WKNavigationDelegate>+@interface CDVWebViewEngine : CDVPlugin <CDVWebViewEngineProtocol, WKScriptMessageHandler, WKNavigationDelegate>@property (nonatomic, strong, readonly) id <WKUIDelegate> uiDelegate;diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewEngine.msimilarity index 67%rename from cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.mrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewEngine.mindex 16a0cb7d6..251a73616 100644--- a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewEngine.m@@ -17,17 +17,18 @@under the License.*/-#import "CDVWKWebViewEngine.h"-#import "CDVWKWebViewUIDelegate.h"-#import "CDVWKProcessPoolFactory.h"+#import "CDVWebViewEngine.h"+#import "CDVWebViewUIDelegate.h"+#import "CDVWebViewProcessPoolFactory.h"#import <Cordova/NSDictionary+CordovaPreferences.h>+#import "CDVURLSchemeHandler.h"#import <objc/message.h>#define CDV_BRIDGE_NAME @"cordova"#define CDV_WKWEBVIEW_FILE_URL_LOAD_SELECTOR @"loadFileURL:allowingReadAccessToURL:"-@interface CDVWKWeakScriptMessageHandler : NSObject <WKScriptMessageHandler>+@interface CDVWebViewWeakScriptMessageHandler : NSObject <WKScriptMessageHandler>@property (nonatomic, weak, readonly) id<WKScriptMessageHandler>scriptMessageHandler;@@ -36,18 +37,21 @@@end-@interface CDVWKWebViewEngine ()+@interface CDVWebViewEngine ()@property (nonatomic, strong, readwrite) UIView* engineWebView;@property (nonatomic, strong, readwrite) id <WKUIDelegate> uiDelegate;@property (nonatomic, weak) id <WKScriptMessageHandler> weakScriptMessageHandler;+@property (nonatomic, strong) CDVURLSchemeHandler * schemeHandler;+@property (nonatomic, readwrite) NSString *CDV_ASSETS_URL;+@property (nonatomic, readwrite) Boolean cdvIsFileScheme;@end// see forwardingTargetForSelector: selector comment for the reason for this pragma#pragma clang diagnostic ignored "-Wprotocol"-@implementation CDVWKWebViewEngine+@implementation CDVWebViewEngine@synthesize engineWebView = _engineWebView;@@ -68,42 +72,149 @@- (WKWebViewConfiguration*) createConfigurationFromSettings:(NSDictionary*)settings{WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];- configuration.processPool = [[CDVWKProcessPoolFactory sharedFactory] sharedProcessPool];+ configuration.processPool = [[CDVWebViewProcessPoolFactory sharedFactory] sharedProcessPool];if (settings == nil) {return configuration;}configuration.allowsInlineMediaPlayback = [settings cordovaBoolSettingForKey:@"AllowInlineMediaPlayback" defaultValue:NO];- configuration.mediaPlaybackRequiresUserAction = [settings cordovaBoolSettingForKey:@"MediaPlaybackRequiresUserAction" defaultValue:YES];++ // Set the media types that are required for user action for playback+ WKAudiovisualMediaTypes mediaType = WKAudiovisualMediaTypeAll; // default++ // targetMediaType will always exist, either from user's "config.xml" or default ("defaults.xml").+ id targetMediaType = [settings cordovaSettingForKey:@"MediaTypesRequiringUserActionForPlayback"];+ if ([targetMediaType isEqualToString:@"none"]) {+ mediaType = WKAudiovisualMediaTypeNone;+ } else if ([targetMediaType isEqualToString:@"audio"]) {+ mediaType = WKAudiovisualMediaTypeAudio;+ } else if ([targetMediaType isEqualToString:@"video"]) {+ mediaType = WKAudiovisualMediaTypeVideo;+ } else if ([targetMediaType isEqualToString:@"all"]) {+ mediaType = WKAudiovisualMediaTypeAll;+ } else {+ NSLog(@"Invalid \"MediaTypesRequiringUserActionForPlayback\" was detected. Fallback to default value of \"all\" types.");+ }+ configuration.mediaTypesRequiringUserActionForPlayback = mediaType;+configuration.suppressesIncrementalRendering = [settings cordovaBoolSettingForKey:@"SuppressesIncrementalRendering" defaultValue:NO];- configuration.mediaPlaybackAllowsAirPlay = [settings cordovaBoolSettingForKey:@"MediaPlaybackAllowsAirPlay" defaultValue:YES];++ /*+ * If the old preference key "MediaPlaybackAllowsAirPlay" exists, use it or default to "YES".+ * Check if the new preference key "AllowsAirPlayForMediaPlayback" exists and overwrite the "MediaPlaybackAllowsAirPlay" value.+ */+ BOOL allowsAirPlayForMediaPlayback = [settings cordovaBoolSettingForKey:@"MediaPlaybackAllowsAirPlay" defaultValue:YES];+ if([settings cordovaSettingForKey:@"AllowsAirPlayForMediaPlayback"] != nil) {+ allowsAirPlayForMediaPlayback = [settings cordovaBoolSettingForKey:@"AllowsAirPlayForMediaPlayback" defaultValue:YES];+ }+ configuration.allowsAirPlayForMediaPlayback = allowsAirPlayForMediaPlayback;++ /*+ * Sets Custom User Agents+ * - (Default) "userAgent" is set the the clean user agent.+ * E.g.+ * UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"+ *+ * - If "OverrideUserAgent" is set, it will overwrite the entire "userAgent" value. The "AppendUserAgent" will be iggnored if set.+ * Notice: The override logic is handled in the "pluginInitialize" method.+ * E.g.+ * OverrideUserAgent = "foobar"+ * UserAgent = "foobar"+ *+ * - If "AppendUserAgent" is set and "OverrideUserAgent" is not set, the user defined "AppendUserAgent" will be appended to the "userAgent"+ * E.g.+ * AppendUserAgent = "foobar"+ * UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 foobar"+ */+ NSString *userAgent = configuration.applicationNameForUserAgent;+ if (+ [settings cordovaSettingForKey:@"OverrideUserAgent"] == nil &&+ [settings cordovaSettingForKey:@"AppendUserAgent"] != nil+ ) {+ userAgent = [NSString stringWithFormat:@"%@ %@", userAgent, [settings cordovaSettingForKey:@"AppendUserAgent"]];+ }+ configuration.applicationNameForUserAgent = userAgent;++ if (@available(iOS 13.0, *)) {+ NSString *contentMode = [settings cordovaSettingForKey:@"PreferredContentMode"];+ if ([contentMode isEqual: @"mobile"]) {+ configuration.defaultWebpagePreferences.preferredContentMode = WKContentModeMobile;+ } else if ([contentMode isEqual: @"desktop"]) {+ configuration.defaultWebpagePreferences.preferredContentMode = WKContentModeDesktop;+ }++ }+return configuration;}- (void)pluginInitialize{// viewController would be available now. we attempt to set all possible delegates to it, by default+ CDVViewController* vc = (CDVViewController*)self.viewController;NSDictionary* settings = self.commandDelegate.settings;- self.uiDelegate = [[CDVWKWebViewUIDelegate alloc] initWithTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]];+ NSString *scheme = [settings cordovaSettingForKey:@"scheme"];++ // If scheme is file or nil, then default to file scheme+ self.cdvIsFileScheme = [scheme isEqualToString: @"file"] || scheme == nil;++ NSString *hostname = @"";+ if(!self.cdvIsFileScheme) {+ if(scheme == nil || [WKWebView handlesURLScheme:scheme]){+ scheme = @"app";+ }+ vc.appScheme = scheme;++ hostname = [settings cordovaSettingForKey:@"hostname"];+ if(hostname == nil){+ hostname = @"localhost";+ }++ self.CDV_ASSETS_URL = [NSString stringWithFormat:@"%@://%@", scheme, hostname];+ }++ CDVWebViewUIDelegate* uiDelegate = [[CDVWebViewUIDelegate alloc] initWithTitle:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]];+ uiDelegate.allowNewWindows = [settings cordovaBoolSettingForKey:@"AllowNewWindows" defaultValue:NO];+ self.uiDelegate = uiDelegate;- CDVWKWeakScriptMessageHandler *weakScriptMessageHandler = [[CDVWKWeakScriptMessageHandler alloc] initWithScriptMessageHandler:self];+ CDVWebViewWeakScriptMessageHandler *weakScriptMessageHandler = [[CDVWebViewWeakScriptMessageHandler alloc] initWithScriptMessageHandler:self];WKUserContentController* userContentController = [[WKUserContentController alloc] init];[userContentController addScriptMessageHandler:weakScriptMessageHandler name:CDV_BRIDGE_NAME];+ if(self.CDV_ASSETS_URL) {+ NSString *scriptCode = [NSString stringWithFormat:@"window.CDV_ASSETS_URL = '%@';", self.CDV_ASSETS_URL];+ WKUserScript *wkScript = [[WKUserScript alloc] initWithSource:scriptCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];++ if (wkScript) {+ [userContentController addUserScript:wkScript];+ }+ }+WKWebViewConfiguration* configuration = [self createConfigurationFromSettings:settings];configuration.userContentController = userContentController;+ // Do not configure the scheme handler if the scheme is default (file)+ if(!self.cdvIsFileScheme) {+ self.schemeHandler = [[CDVURLSchemeHandler alloc] initWithVC:vc];+ [configuration setURLSchemeHandler:self.schemeHandler forURLScheme:scheme];+ }+// re-create WKWebView, since we need to update configurationWKWebView* wkWebView = [[WKWebView alloc] initWithFrame:self.engineWebView.frame configuration:configuration];wkWebView.UIDelegate = self.uiDelegate;- self.engineWebView = wkWebView;- if (IsAtLeastiOSVersion(@"9.0") && [self.viewController isKindOfClass:[CDVViewController class]]) {- wkWebView.customUserAgent = ((CDVViewController*) self.viewController).userAgent;+ /*+ * This is where the "OverrideUserAgent" is handled. This will replace the entire UserAgent+ * with the user defined custom UserAgent.+ */+ if ([settings cordovaSettingForKey:@"OverrideUserAgent"] != nil) {+ wkWebView.customUserAgent = [settings cordovaSettingForKey:@"OverrideUserAgent"];}+ self.engineWebView = wkWebView;+if ([self.viewController conformsToProtocol:@protocol(WKUIDelegate)]) {wkWebView.UIDelegate = (id <WKUIDelegate>)self.viewController;}@@ -121,7 +232,7 @@[self updateSettings:settings];// check if content thread has died on resume- NSLog(@"%@", @"CDVWKWebViewEngine will reload WKWebView if required on resume");+ NSLog(@"%@", @"CDVWebViewEngine will reload WKWebView if required on resume");[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(onAppWillEnterForeground:)@@ -158,7 +269,7 @@ static void * KVOContext = &KVOContext;- (void) onAppWillEnterForeground:(NSNotification*)notification {if ([self shouldReloadWebView]) {- NSLog(@"%@", @"CDVWKWebViewEngine reloading!");+ NSLog(@"%@", @"CDVWebViewEngine reloading!");[(WKWebView*)_engineWebView reload];}}@@ -177,10 +288,10 @@ static void * KVOContext = &KVOContext;BOOL reload = (title_is_nil || location_is_blank);#ifdef DEBUG- NSLog(@"%@", @"CDVWKWebViewEngine shouldReloadWebView::");- NSLog(@"CDVWKWebViewEngine shouldReloadWebView title: %@", title);- NSLog(@"CDVWKWebViewEngine shouldReloadWebView location: %@", [location absoluteString]);- NSLog(@"CDVWKWebViewEngine shouldReloadWebView reload: %u", reload);+ NSLog(@"%@", @"CDVWebViewEngine shouldReloadWebView::");+ NSLog(@"CDVWebViewEngine shouldReloadWebView title: %@", title);+ NSLog(@"CDVWebViewEngine shouldReloadWebView location: %@", [location absoluteString]);+ NSLog(@"CDVWebViewEngine shouldReloadWebView reload: %u", reload);#endifreturn reload;@@ -190,13 +301,25 @@ static void * KVOContext = &KVOContext;- (id)loadRequest:(NSURLRequest*)request{if ([self canLoadRequest:request]) { // can load, differentiate between file urls and other schemes- if (request.URL.fileURL) {- SEL wk_sel = NSSelectorFromString(CDV_WKWEBVIEW_FILE_URL_LOAD_SELECTOR);+ if(request.URL.fileURL && self.cdvIsFileScheme) {NSURL* readAccessUrl = [request.URL URLByDeletingLastPathComponent];- return ((id (*)(id, SEL, id, id))objc_msgSend)(_engineWebView, wk_sel, request.URL, readAccessUrl);- } else {- return [(WKWebView*)_engineWebView loadRequest:request];+ return [(WKWebView*)_engineWebView loadFileURL:request.URL allowingReadAccessToURL:readAccessUrl];+ } else if (request.URL.fileURL) {+ NSURL* startURL = [NSURL URLWithString:((CDVViewController *)self.viewController).startPage];+ NSString* startFilePath = [self.commandDelegate pathForResource:[startURL path]];+ NSURL *url = [[NSURL URLWithString:self.CDV_ASSETS_URL] URLByAppendingPathComponent:request.URL.path];+ if ([request.URL.path isEqualToString:startFilePath]) {+ url = [NSURL URLWithString:self.CDV_ASSETS_URL];+ }+ if(request.URL.query) {+ url = [NSURL URLWithString:[@"?" stringByAppendingString:request.URL.query] relativeToURL:url];+ }+ if(request.URL.fragment) {+ url = [NSURL URLWithString:[@"#" stringByAppendingString:request.URL.fragment] relativeToURL:url];+ }+ request = [NSURLRequest requestWithURL:url];}+ return [(WKWebView*)_engineWebView loadRequest:request];} else { // can't load, print out errorNSString* errorHtml = [NSString stringWithFormat:@"<!doctype html>"@@ -264,10 +387,6 @@ static void * KVOContext = &KVOContext;}NSString* decelerationSetting = [settings cordovaSettingForKey:@"WKWebViewDecelerationSpeed"];- if (!decelerationSetting) {- // Fallback to the UIWebView-named preference- decelerationSetting = [settings cordovaSettingForKey:@"UIWebViewDecelerationSpeed"];- }if (![@"fast" isEqualToString:decelerationSetting]) {[wkWebView.scrollView setDecelerationRate:UIScrollViewDecelerationRateNormal];@@ -313,7 +432,7 @@ static void * KVOContext = &KVOContext;}// This forwards the methods that are in the header that are not implemented here.-// Both WKWebView and UIWebView implement the below:+// Both WKWebView implement the below:// loadHTMLString:baseURL:// loadRequest:- (id)forwardingTargetForSelector:(SEL)aSelector@@ -371,9 +490,6 @@ static void * KVOContext = &KVOContext;- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation{- CDVViewController* vc = (CDVViewController*)self.viewController;- [CDVUserAgentUtil releaseLock:vc.userAgentLockToken];-[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPageDidLoadNotification object:webView]];}@@ -385,14 +501,14 @@ static void * KVOContext = &KVOContext;- (void)webView:(WKWebView*)theWebView didFailNavigation:(WKNavigation*)navigation withError:(NSError*)error{CDVViewController* vc = (CDVViewController*)self.viewController;- [CDVUserAgentUtil releaseLock:vc.userAgentLockToken];NSString* message = [NSString stringWithFormat:@"Failed to load webpage with error: %@", [error localizedDescription]];NSLog(@"%@", message);NSURL* errorUrl = vc.errorURL;if (errorUrl) {- errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [message stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] relativeToURL:errorUrl];+ NSCharacterSet *charSet = [NSCharacterSet URLFragmentAllowedCharacterSet];+ errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [message stringByAddingPercentEncodingWithAllowedCharacters:charSet]] relativeToURL:errorUrl];NSLog(@"%@", [errorUrl absoluteString]);[theWebView loadRequest:[NSURLRequest requestWithURL:errorUrl]];}@@ -431,9 +547,6 @@ static void * KVOContext = &KVOContext;anyPluginsResponded = YES;// https://issues.apache.org/jira/browse/CB-12497int navType = (int)navigationAction.navigationType;- if (WKNavigationTypeOther == navigationAction.navigationType) {- navType = (int)UIWebViewNavigationTypeOther;- }shouldAllowRequest = (((BOOL (*)(id, SEL, id, int))objc_msgSend)(plugin, selector, navigationAction.request, navType));if (!shouldAllowRequest) {break;@@ -473,9 +586,9 @@ static void * KVOContext = &KVOContext;@end-#pragma mark - CDVWKWeakScriptMessageHandler+#pragma mark - CDVWebViewWeakScriptMessageHandler-@implementation CDVWKWeakScriptMessageHandler+@implementation CDVWebViewWeakScriptMessageHandler- (instancetype)initWithScriptMessageHandler:(id<WKScriptMessageHandler>)scriptMessageHandler{diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewProcessPoolFactory.hsimilarity index 94%rename from cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.hrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewProcessPoolFactory.hindex f4f8816e0..2397efa3a 100644--- a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewProcessPoolFactory.h@@ -6,9 +6,9 @@to you under the Apache License, Version 2.0 (the"License"); you may not use this file except in compliancewith the License. You may obtain a copy of the License at-+http://www.apache.org/licenses/LICENSE-2.0-+Unless required by applicable law or agreed to in writing,software distributed under the License is distributed on an"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -19,7 +19,7 @@#import <WebKit/WebKit.h>-@interface CDVWKProcessPoolFactory : NSObject+@interface CDVWebViewProcessPoolFactory : NSObject@property (nonatomic, retain) WKProcessPool* sharedPool;+(instancetype) sharedFactory;diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewProcessPoolFactory.msimilarity index 85%rename from cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.mrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewProcessPoolFactory.mindex 48ac09e66..afda72509 100644--- a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewProcessPoolFactory.m@@ -6,9 +6,9 @@to you under the Apache License, Version 2.0 (the"License"); you may not use this file except in compliancewith the License. You may obtain a copy of the License at-+http://www.apache.org/licenses/LICENSE-2.0-+Unless required by applicable law or agreed to in writing,software distributed under the License is distributed on an"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY@@ -19,19 +19,19 @@#import <Foundation/Foundation.h>#import <WebKit/WebKit.h>-#import "CDVWKProcessPoolFactory.h"+#import "CDVWebViewProcessPoolFactory.h"-static CDVWKProcessPoolFactory *factory = nil;+static CDVWebViewProcessPoolFactory *factory = nil;-@implementation CDVWKProcessPoolFactory+@implementation CDVWebViewProcessPoolFactory+ (instancetype)sharedFactory{static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{- factory = [[CDVWKProcessPoolFactory alloc] init];+ factory = [[CDVWebViewProcessPoolFactory alloc] init];});-+return factory;}diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewUIDelegate.hsimilarity index 84%rename from cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.hrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewUIDelegate.hindex 33a179b0c..8ae39b67c 100644--- a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewUIDelegate.h@@ -19,9 +19,13 @@#import <WebKit/WebKit.h>-@interface CDVWKWebViewUIDelegate : NSObject <WKUIDelegate>+@interface CDVWebViewUIDelegate : NSObject <WKUIDelegate>+{+ NSMutableArray<UIViewController*>* windows;+}@property (nonatomic, copy) NSString* title;+@property (nonatomic, assign) BOOL allowNewWindows;- (instancetype)initWithTitle:(NSString*)title;diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.m b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewUIDelegate.msimilarity index 77%rename from cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.mrename to cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewUIDelegate.mindex a7a16f2c6..784af8dfa 100644--- a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewUIDelegate.m@@ -17,15 +17,16 @@under the License.*/-#import "CDVWKWebViewUIDelegate.h"+#import "CDVWebViewUIDelegate.h"-@implementation CDVWKWebViewUIDelegate+@implementation CDVWebViewUIDelegate- (instancetype)initWithTitle:(NSString*)title{self = [super init];if (self) {self.title = title;+ windows = [[NSMutableArray alloc] init];}return self;@@ -120,4 +121,43 @@[rootController presentViewController:alert animated:YES completion:nil];}+- (WKWebView*) webView:(WKWebView*)webView createWebViewWithConfiguration:(WKWebViewConfiguration*)configuration forNavigationAction:(WKNavigationAction*)navigationAction windowFeatures:(WKWindowFeatures*)windowFeatures+{+ if (!navigationAction.targetFrame.isMainFrame) {+ if (self.allowNewWindows) {+ WKWebView* v = [[WKWebView alloc] initWithFrame:webView.frame configuration:configuration];+ v.UIDelegate = webView.UIDelegate;+ v.navigationDelegate = webView.navigationDelegate;++ UIViewController* vc = [[UIViewController alloc] init];+ vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;+ vc.view = v;++ [windows addObject:vc];++ UIViewController* rootController = [UIApplication sharedApplication].delegate.window.rootViewController;+ [rootController presentViewController:vc animated:YES completion:nil];+ return v;+ } else {+ [webView loadRequest:navigationAction.request];+ }+ }++ return nil;+}++- (void)webViewDidClose:(WKWebView*)webView+{+ for (UIViewController* vc in windows) {+ if (vc.view == webView) {+ [vc dismissViewControllerAnimated:YES completion:nil];+ [windows removeObject:vc];+ break;+ }+ }++ // We do not allow closing the primary WebView+}++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDV.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDV.hindex 96d6efc8f..8706ef4aa 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDV.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDV.h@@ -24,9 +24,7 @@#import "CDVPluginResult.h"#import "CDVViewController.h"#import "CDVCommandDelegate.h"-#import "CDVURLProtocol.h"#import "CDVInvokedUrlCommand.h"#import "CDVWhitelist.h"#import "CDVScreenOrientationDelegate.h"#import "CDVTimer.h"-#import "CDVUserAgentUtil.h"diff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.mindex 6a339f43f..9188be79e 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAppDelegate.m@@ -25,18 +25,6 @@- (id)init{- /** If you need to do any extra app-specific initialization, you can do it here- * -jm- **/- NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];-- [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];-- int cacheSizeMemory = 8 * 1024 * 1024; // 8MB- int cacheSizeDisk = 32 * 1024 * 1024; // 32MB- NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];- [NSURLCache setSharedURLCache:sharedCache];-self = [super init];return self;}@@ -98,11 +86,7 @@return YES;}-#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000-- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window-#else //CB-12098. Defaults to UIInterfaceOrientationMask for iOS 9+- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window-#endif{// iPhone doesn't support upside down by default, while the iPad does. Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);@@ -110,9 +94,4 @@return supportedInterfaceOrientations;}-- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application-{- [[NSURLCache sharedURLCache] removeAllCachedResponses];-}-@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailability.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailability.hindex 00498ab5b..cec648d21 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailability.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVAvailability.h@@ -75,6 +75,8 @@#define __CORDOVA_5_0_1 50001#define __CORDOVA_5_1_0 50100#define __CORDOVA_5_1_1 50101+#define __CORDOVA_6_0_0 60000+#define __CORDOVA_6_1_0 60100/* coho:next-version,insert-before */#define __CORDOVA_NA 99999 /* not available */@@ -87,7 +89,7 @@*/#ifndef CORDOVA_VERSION_MIN_REQUIRED/* coho:next-version-min-required,replace-after */- #define CORDOVA_VERSION_MIN_REQUIRED __CORDOVA_5_1_1+ #define CORDOVA_VERSION_MIN_REQUIRED __CORDOVA_6_1_0#endif/*diff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegate.hindex efc9ad3f3..ac82727a9 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegate.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegate.h@@ -45,7 +45,5 @@ typedef NSURL* (^ UrlTransformerBlock)(NSURL*);- (void)evalJs:(NSString*)js scheduledOnRunLoop:(BOOL)scheduledOnRunLoop;// Runs the given block on a background thread using a shared thread-pool.- (void)runInBackground:(void (^)(void))block;-// Returns the User-Agent of the associated UIWebView.-- (NSString*)userAgent;@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.mindex effca6fd4..4ced59955 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVCommandDelegateImpl.m@@ -92,7 +92,7 @@// Cycle the run-loop before executing the JS.// For _delayResponses -// This ensures that we don't eval JS during the middle of an existing JS- // function (possible since UIWebViewDelegate callbacks can be synchronous).+ // function (possible since WKWebViewDelegate callbacks can be synchronous).// For !isMainThread -// It's a hard error to eval on the non-UI thread.// For !_commandQueue.currentlyExecuting -@@ -138,7 +138,7 @@BOOL keepCallback = [result.keepCallback boolValue];NSString* argumentsAsJSON = [result argumentsAsJSON];BOOL debug = NO;-+#ifdef DEBUGdebug = YES;#endif@@ -173,11 +173,6 @@dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);}-- (NSString*)userAgent-{- return [_viewController userAgent];-}-- (NSDictionary*)settings{return _viewController.settings;diff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.mindex 2f6f3a6cb..930aeaba7 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVPluginResult.m@@ -103,7 +103,7 @@ id messageFromMultipart(NSArray* theMessages){self = [super init];if (self) {- status = [NSNumber numberWithInt:statusOrdinal];+ status = @(statusOrdinal);message = theMessage;keepCallback = [NSNumber numberWithBool:NO];}diff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVScreenOrientationDelegate.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVScreenOrientationDelegate.hindex 519dd490c..49c3c2707 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVScreenOrientationDelegate.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVScreenOrientationDelegate.h@@ -21,13 +21,8 @@@protocol CDVScreenOrientationDelegate <NSObject>-#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000-- (NSUInteger)supportedInterfaceOrientations;-#else- (UIInterfaceOrientationMask)supportedInterfaceOrientations;-#endif-- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;- (BOOL)shouldAutorotate;@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.mdeleted file mode 100644index 7b2c5ce5b..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLProtocol.m+++ /dev/null@@ -1,113 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#import <AssetsLibrary/ALAsset.h>-#import <AssetsLibrary/ALAssetRepresentation.h>-#import <AssetsLibrary/ALAssetsLibrary.h>-#import <MobileCoreServices/MobileCoreServices.h>-#import "CDVURLProtocol.h"-#import "CDVCommandQueue.h"-#import "CDVViewController.h"--// Contains a set of NSNumbers of addresses of controllers. It doesn't store-// the actual pointer to avoid retaining.-static NSMutableSet* gRegisteredControllers = nil;--NSString* const kCDVAssetsLibraryPrefixes = @"assets-library://";--@implementation CDVURLProtocol---+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest-{- NSURL* theUrl = [theRequest URL];-- if ([[theUrl absoluteString] hasPrefix:kCDVAssetsLibraryPrefixes]) {- return YES;- }-- return NO;-}--+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request-{- // NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd));- return request;-}--- (void)startLoading-{- // NSLog(@"%@ received %@ - start", self, NSStringFromSelector(_cmd));- NSURL* url = [[self request] URL];-- if ([[url absoluteString] hasPrefix:kCDVAssetsLibraryPrefixes]) {- ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {- if (asset) {- // We have the asset! Get the data and send it along.- ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];- NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType);- Byte* buffer = (Byte*)malloc((unsigned long)[assetRepresentation size]);- NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:0.0 length:(NSUInteger)[assetRepresentation size] error:nil];- NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];- [self sendResponseWithResponseCode:200 data:data mimeType:MIMEType];- } else {- // Retrieving the asset failed for some reason. Send an error.- [self sendResponseWithResponseCode:404 data:nil mimeType:nil];- }- };- ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {- // Retrieving the asset failed for some reason. Send an error.- [self sendResponseWithResponseCode:401 data:nil mimeType:nil];- };-- ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];- [assetsLibrary assetForURL:url resultBlock:resultBlock failureBlock:failureBlock];- return;- }-- NSString* body = [NSString stringWithFormat:@"Access not allowed to URL: %@", url];- [self sendResponseWithResponseCode:401 data:[body dataUsingEncoding:NSASCIIStringEncoding] mimeType:nil];-}--- (void)stopLoading-{- // do any cleanup here-}--+ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB-{- return NO;-}--- (void)sendResponseWithResponseCode:(NSInteger)statusCode data:(NSData*)data mimeType:(NSString*)mimeType-{- if (mimeType == nil) {- mimeType = @"text/plain";- }-- NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL] statusCode:statusCode HTTPVersion:@"HTTP/1.1" headerFields:@{@"Content-Type" : mimeType}];-- [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];- if (data != nil) {- [[self client] URLProtocol:self didLoadData:data];- }- [[self client] URLProtocolDidFinishLoading:self];-}--@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLSchemeHandler.hsimilarity index 76%rename from cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.hrename to cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLSchemeHandler.hindex 4de382f0b..1cd84d09d 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLSchemeHandler.h@@ -18,10 +18,15 @@*/#import <Foundation/Foundation.h>+#import <WebKit/WebKit.h>+#import "CDVViewController.h"+++@interface CDVURLSchemeHandler : NSObject <WKURLSchemeHandler>++@property (nonatomic, strong) CDVViewController* viewController;++- (instancetype)initWithVC:(CDVViewController *)controller;+-@interface CDVUserAgentUtil : NSObject-+ (NSString*)originalUserAgent;-+ (void)acquireLock:(void (^)(NSInteger lockToken))block;-+ (void)releaseLock:(NSInteger*)lockToken;-+ (void)setUserAgent:(NSString*)value lockToken:(NSInteger)lockToken;@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLSchemeHandler.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLSchemeHandler.mnew file mode 100644index 000000000..6c88ceb69--- /dev/null+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVURLSchemeHandler.m@@ -0,0 +1,108 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+ */+++#import "CDVURLSchemeHandler.h"+#import <MobileCoreServices/MobileCoreServices.h>++@implementation CDVURLSchemeHandler+++- (instancetype)initWithVC:(CDVViewController *)controller+{+ self = [super init];+ if (self) {+ _viewController = controller;+ }+ return self;+}++- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask+{+ NSString * startPath = [[NSBundle mainBundle] pathForResource:self.viewController.wwwFolderName ofType: nil];+ NSURL * url = urlSchemeTask.request.URL;+ NSString * stringToLoad = url.path;+ NSString * scheme = url.scheme;++ if ([scheme isEqualToString:self.viewController.appScheme]) {+ if ([stringToLoad hasPrefix:@"/_app_file_"]) {+ startPath = [stringToLoad stringByReplacingOccurrencesOfString:@"/_app_file_" withString:@""];+ } else {+ if ([stringToLoad isEqualToString:@""] || [url.pathExtension isEqualToString:@""]) {+ startPath = [startPath stringByAppendingPathComponent:self.viewController.startPage];+ } else {+ startPath = [startPath stringByAppendingPathComponent:stringToLoad];+ }+ }+ }++ NSError * fileError = nil;+ NSData * data = nil;+ if ([self isMediaExtension:url.pathExtension]) {+ data = [NSData dataWithContentsOfFile:startPath options:NSDataReadingMappedIfSafe error:&fileError];+ }+ if (!data || fileError) {+ data = [[NSData alloc] initWithContentsOfFile:startPath];+ }+ NSInteger statusCode = 200;+ if (!data) {+ statusCode = 404;+ }+ NSURL * localUrl = [NSURL URLWithString:url.absoluteString];+ NSString * mimeType = [self getMimeType:url.pathExtension];+ id response = nil;+ if (data && [self isMediaExtension:url.pathExtension]) {+ response = [[NSURLResponse alloc] initWithURL:localUrl MIMEType:mimeType expectedContentLength:data.length textEncodingName:nil];+ } else {+ NSDictionary * headers = @{ @"Content-Type" : mimeType, @"Cache-Control": @"no-cache"};+ response = [[NSHTTPURLResponse alloc] initWithURL:localUrl statusCode:statusCode HTTPVersion:nil headerFields:headers];+ }++ [urlSchemeTask didReceiveResponse:response];+ [urlSchemeTask didReceiveData:data];+ [urlSchemeTask didFinish];++}++- (void)webView:(nonnull WKWebView *)webView stopURLSchemeTask:(nonnull id<WKURLSchemeTask>)urlSchemeTask+{++}++-(NSString *) getMimeType:(NSString *)fileExtension {+ if (fileExtension && ![fileExtension isEqualToString:@""]) {+ NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);+ NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);+ return contentType ? contentType : @"application/octet-stream";+ } else {+ return @"text/html";+ }+}++-(BOOL) isMediaExtension:(NSString *) pathExtension {+ NSArray * mediaExtensions = @[@"m4v", @"mov", @"mp4",+ @"aac", @"ac3", @"aiff", @"au", @"flac", @"m4a", @"mp3", @"wav"];+ if ([mediaExtensions containsObject:pathExtension.lowercaseString]) {+ return YES;+ }+ return NO;+}+++@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.mdeleted file mode 100644index c5e9e2bcd..000000000--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVUserAgentUtil.m+++ /dev/null@@ -1,162 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.- */--#import "CDVUserAgentUtil.h"--#import <UIKit/UIKit.h>--// #define VerboseLog NSLog-#define VerboseLog(...) do {} while (0)--static NSString* const kCdvUserAgentKey = @"Cordova-User-Agent";-static NSString* const kCdvUserAgentVersionKey = @"Cordova-User-Agent-Version";--static NSString* gOriginalUserAgent = nil;-static NSInteger gNextLockToken = 0;-static NSInteger gCurrentLockToken = 0;-static NSMutableArray* gPendingSetUserAgentBlocks = nil;--#if WK_WEB_VIEW_ONLY-#import <WebKit/WebKit.h>--@interface WKWebView(SynchronousEvaluateJavaScript)-- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;-@end--@implementation WKWebView(SynchronousEvaluateJavaScript)--- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script-{- __block NSString *resultString = nil;- __block BOOL finished = NO;-- [self evaluateJavaScript:script completionHandler:^(id result, NSError *error) {- if (error == nil) {- if (result != nil) {- resultString = [NSString stringWithFormat:@"%@", result];- }- } else {- NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);- }- finished = YES;- }];-- while (!finished) {- [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];- }-- return resultString;-}-@end-#endif--@implementation CDVUserAgentUtil--+ (NSString*)originalUserAgent-{- if (gOriginalUserAgent == nil) {- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppLocaleDidChange:)- name:NSCurrentLocaleDidChangeNotification object:nil];-- NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];- NSString* systemVersion = [[UIDevice currentDevice] systemVersion];- NSString* localeStr = [[NSLocale currentLocale] localeIdentifier];- // Record the model since simulator can change it without re-install (CB-5420).- NSString* model = [UIDevice currentDevice].model;- // Record the version of the app so that we can bust the cache when it changes (CB-10078)- NSString* appVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"];- NSString* systemAndLocale = [NSString stringWithFormat:@"%@ %@ %@ %@", appVersion, model, systemVersion, localeStr];-- NSString* cordovaUserAgentVersion = [userDefaults stringForKey:kCdvUserAgentVersionKey];- gOriginalUserAgent = [userDefaults stringForKey:kCdvUserAgentKey];- BOOL cachedValueIsOld = ![systemAndLocale isEqualToString:cordovaUserAgentVersion];-- if ((gOriginalUserAgent == nil) || cachedValueIsOld) {- #if WK_WEB_VIEW_ONLY- WKWebView* sampleWebView = [[WKWebView alloc] initWithFrame:CGRectZero];- #else- UIWebView* sampleWebView = [[UIWebView alloc] initWithFrame:CGRectZero];-#endif- gOriginalUserAgent = [sampleWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];-- [userDefaults setObject:gOriginalUserAgent forKey:kCdvUserAgentKey];- [userDefaults setObject:systemAndLocale forKey:kCdvUserAgentVersionKey];-- [userDefaults synchronize];- }- }- return gOriginalUserAgent;-}--+ (void)onAppLocaleDidChange:(NSNotification*)notification-{- // TODO: We should figure out how to update the user-agent of existing UIWebViews when this happens.- // Maybe use the PDF bug (noted in setUserAgent:).- gOriginalUserAgent = nil;-}--+ (void)acquireLock:(void (^)(NSInteger lockToken))block-{- if (gCurrentLockToken == 0) {- gCurrentLockToken = ++gNextLockToken;- VerboseLog(@"Gave lock %d", gCurrentLockToken);- block(gCurrentLockToken);- } else {- if (gPendingSetUserAgentBlocks == nil) {- gPendingSetUserAgentBlocks = [[NSMutableArray alloc] initWithCapacity:4];- }- VerboseLog(@"Waiting for lock");- [gPendingSetUserAgentBlocks addObject:block];- }-}--+ (void)releaseLock:(NSInteger*)lockToken-{- if (lockToken == nil || *lockToken == 0) {- return;- }- NSAssert(gCurrentLockToken == *lockToken, @"Got token %ld, expected %ld", (long)*lockToken, (long)gCurrentLockToken);-- VerboseLog(@"Released lock %d", *lockToken);- if ([gPendingSetUserAgentBlocks count] > 0) {- void (^block)(NSInteger lockToken) = [gPendingSetUserAgentBlocks objectAtIndex:0];- [gPendingSetUserAgentBlocks removeObjectAtIndex:0];- gCurrentLockToken = ++gNextLockToken;- NSLog(@"Gave lock %ld", (long)gCurrentLockToken);- block(gCurrentLockToken);- } else {- gCurrentLockToken = 0;- }- *lockToken = 0;-}--+ (void)setUserAgent:(NSString*)value lockToken:(NSInteger)lockToken-{- NSAssert(gCurrentLockToken == lockToken, @"Got token %ld, expected %ld", (long)lockToken, (long)gCurrentLockToken);- VerboseLog(@"User-Agent set to: %@", value);-- // Setting the UserAgent must occur before a UIWebView is instantiated.- // It is read per instantiation, so it does not affect previously created views.- // Except! When a PDF is loaded, all currently active UIWebViews reload their- // User-Agent from the NSUserDefaults some time after the DidFinishLoad of the PDF bah!- NSDictionary* dict = [[NSDictionary alloc] initWithObjectsAndKeys:value, @"UserAgent", nil];- [[NSUserDefaults standardUserDefaults] registerDefaults:dict];-}--@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.hindex 605dbbbfb..4b5e423a4 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.h@@ -34,7 +34,6 @@id <CDVCommandDelegate> _commandDelegate;@protectedCDVCommandQueue* _commandQueue;- NSString* _userAgent;}@property (nonatomic, readonly, weak) IBOutlet UIView* webView;@@ -44,6 +43,7 @@@property (nonatomic, readonly, strong) NSMutableDictionary* settings;@property (nonatomic, readonly, strong) NSXMLParser* configParser;+@property (nonatomic, readwrite, copy) NSString* appScheme;@property (nonatomic, readwrite, copy) NSString* configFile;@property (nonatomic, readwrite, copy) NSString* wwwFolderName;@property (nonatomic, readwrite, copy) NSString* startPage;@@ -51,35 +51,18 @@@property (nonatomic, readonly, strong) id <CDVWebViewEngineProtocol> webViewEngine;@property (nonatomic, readonly, strong) id <CDVCommandDelegate> commandDelegate;-/**- The complete user agent that Cordova will use when sending web requests.- */-@property (nonatomic, readonly) NSString* userAgent;--/**- The base user agent data that Cordova will use to build its user agent. If this- property isn't set, Cordova will use the standard web view user agent as its- base.- */-@property (nonatomic, readwrite, copy) NSString* baseUserAgent;-/**Takes/Gives an array of UIInterfaceOrientation (int) objectsex. UIInterfaceOrientationPortrait*/@property (nonatomic, readwrite, strong) NSArray* supportedOrientations;-/**- The address of the lock token used for controlling access to setting the user-agent- */-@property (nonatomic, readonly) NSInteger* userAgentLockToken;-- (UIView*)newCordovaViewWithFrame:(CGRect)bounds;- (NSString*)appURLScheme;- (NSURL*)errorURL;-- (UIColor*)colorFromColorString:(NSString*)colorString;+- (UIColor*)colorFromColorString:(NSString*)colorString CDV_DEPRECATED(7.0.0, "Use BackgroundColor in xcassets");- (NSArray*)parseInterfaceOrientations:(NSArray*)orientations;- (BOOL)supportsOrientation:(UIInterfaceOrientation)orientation;@@ -89,4 +72,6 @@- (void)parseSettingsWithParser:(NSObject <NSXMLParserDelegate>*)delegate;+- (void)showLaunchScreen:(BOOL)visible;+@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.m b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.mindex 75e74add0..0d7eb8b7b 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVViewController.m@@ -20,17 +20,14 @@#import <objc/message.h>#import "CDV.h"#import "CDVPlugin+Private.h"+#import "CDVWebViewUIDelegate.h"#import "CDVConfigParser.h"-#import "CDVUserAgentUtil.h"#import <AVFoundation/AVFoundation.h>#import "NSDictionary+CordovaPreferences.h"-#import "CDVLocalStorage.h"#import "CDVCommandDelegateImpl.h"#import <Foundation/NSCharacterSet.h>-@interface CDVViewController () {- NSInteger _userAgentLockToken;-}+@interface CDVViewController () { }@property (nonatomic, readwrite, strong) NSXMLParser* configParser;@property (nonatomic, readwrite, strong) NSMutableDictionary* settings;@@ -38,6 +35,7 @@@property (nonatomic, readwrite, strong) NSMutableArray* startupPluginNames;@property (nonatomic, readwrite, strong) NSDictionary* pluginsMap;@property (nonatomic, readwrite, strong) id <CDVWebViewEngineProtocol> webViewEngine;+@property (nonatomic, readwrite, strong) UIView* launchView;@property (readwrite, assign) BOOL initialized;@@ -50,7 +48,7 @@@synthesize supportedOrientations;@synthesize pluginObjects, pluginsMap, startupPluginNames;@synthesize configParser, settings;-@synthesize wwwFolderName, startPage, initialized, openURL, baseUserAgent;+@synthesize wwwFolderName, startPage, initialized, openURL;@synthesize commandDelegate = _commandDelegate;@synthesize commandQueue = _commandQueue;@synthesize webViewEngine = _webViewEngine;@@ -73,6 +71,9 @@[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackground:)name:UIApplicationDidEnterBackgroundNotification object:nil];+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onWebViewPageDidLoad:)+ name:CDVPageDidLoadNotification object:nil];+// read from UISupportedInterfaceOrientations (or UISupportedInterfaceOrientations~iPad, if its iPad) from -Info.plistself.supportedOrientations = [self parseInterfaceOrientations:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"]];@@ -284,7 +285,11 @@}[self.settings setCordovaSetting:backupWebStorageType forKey:@"BackupWebStorage"];- [CDVLocalStorage __fixupDatabaseLocationsWithBackupType:backupWebStorageType];+ // // Instantiate the Launch screen /////////++ if (!self.launchView) {+ [self createLaunchView];+ }// // Instantiate the WebView ///////////////@@ -294,17 +299,6 @@// /////////////////- /*- * Fire up CDVLocalStorage to work-around WebKit storage limitations: on all iOS 5.1+ versions for local-only backups, but only needed on iOS 5.1 for cloud backup.- With minimum iOS 7/8 supported, only first clause applies.- */- if ([backupWebStorageType isEqualToString:@"local"]) {- NSString* localStorageFeatureName = @"localstorage";- if ([self.pluginsMap objectForKey:localStorageFeatureName]) { // plugin specified in config- [self.startupPluginNames addObject:localStorageFeatureName];- }- }-if ([self.startupPluginNames count] > 0) {[CDVTimer start:@"TotalPluginStartup"];@@ -319,43 +313,31 @@// /////////////////NSURL* appURL = [self appUrl];- __weak __typeof__(self) weakSelf = self;-- [CDVUserAgentUtil acquireLock:^(NSInteger lockToken) {- // Fix the memory leak caused by the strong reference.- [weakSelf setLockToken:lockToken];- if (appURL) {- NSURLRequest* appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];- [self.webViewEngine loadRequest:appReq];++ if (appURL) {+ NSURLRequest* appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];+ [self.webViewEngine loadRequest:appReq];+ } else {+ NSString* loadErr = [NSString stringWithFormat:@"ERROR: Start Page at '%@/%@' was not found.", self.wwwFolderName, self.startPage];+ NSLog(@"%@", loadErr);++ NSURL* errorUrl = [self errorURL];+ if (errorUrl) {+ errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [loadErr stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]] relativeToURL:errorUrl];+ NSLog(@"%@", [errorUrl absoluteString]);+ [self.webViewEngine loadRequest:[NSURLRequest requestWithURL:errorUrl]];} else {- NSString* loadErr = [NSString stringWithFormat:@"ERROR: Start Page at '%@/%@' was not found.", self.wwwFolderName, self.startPage];- NSLog(@"%@", loadErr);-- NSURL* errorUrl = [self errorURL];- if (errorUrl) {- errorUrl = [NSURL URLWithString:[NSString stringWithFormat:@"?error=%@", [loadErr stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet]] relativeToURL:errorUrl];- NSLog(@"%@", [errorUrl absoluteString]);- [self.webViewEngine loadRequest:[NSURLRequest requestWithURL:errorUrl]];- } else {- NSString* html = [NSString stringWithFormat:@"<html><body> %@ </body></html>", loadErr];- [self.webViewEngine loadHTMLString:html baseURL:nil];- }+ NSString* html = [NSString stringWithFormat:@"<html><body> %@ </body></html>", loadErr];+ [self.webViewEngine loadHTMLString:html baseURL:nil];}- }];-+ }// /////////////////- NSString* bgColorString = [self.settings cordovaSettingForKey:@"BackgroundColor"];- UIColor* bgColor = [self colorFromColorString:bgColorString];+ UIColor* bgColor = [UIColor colorNamed:@"BackgroundColor"] ?: UIColor.whiteColor;+ [self.launchView setBackgroundColor:bgColor];[self.webView setBackgroundColor:bgColor];}-- (void)setLockToken:(NSInteger)lockToken-{- _userAgentLockToken = lockToken;- [CDVUserAgentUtil setUserAgent:self.userAgent lockToken:lockToken];-}--(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];@@ -478,12 +460,7 @@return YES;}-// CB-12098-#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000-- (NSUInteger)supportedInterfaceOrientations-#else- (UIInterfaceOrientationMask)supportedInterfaceOrientations-#endif{NSUInteger ret = 0;@@ -505,7 +482,7 @@- (BOOL)supportsOrientation:(UIInterfaceOrientation)orientation{- return [self.supportedOrientations containsObject:[NSNumber numberWithInt:orientation]];+ return [self.supportedOrientations containsObject:@(orientation)];}- (UIView*)newCordovaViewWithFrame:(CGRect)bounds@@ -514,7 +491,7 @@NSString* webViewEngineClass = [self.settings cordovaSettingForKey:@"CordovaWebViewEngine"];if (!defaultWebViewEngineClass) {- defaultWebViewEngineClass = @"CDVUIWebViewEngine";+ defaultWebViewEngineClass = @"CDVWebViewEngine";}if (!webViewEngineClass) {webViewEngineClass = defaultWebViewEngineClass;@@ -523,7 +500,7 @@// Find webViewEngineif (NSClassFromString(webViewEngineClass)) {self.webViewEngine = [[NSClassFromString(webViewEngineClass) alloc] initWithFrame:bounds];- // if a webView engine returns nil (not supported by the current iOS version) or doesn't conform to the protocol, or can't load the request, we use UIWebView+ // if a webView engine returns nil (not supported by the current iOS version) or doesn't conform to the protocol, or can't load the request, we use WKWebViewif (!self.webViewEngine || ![self.webViewEngine conformsToProtocol:@protocol(CDVWebViewEngineProtocol)] || ![self.webViewEngine canLoadRequest:[NSURLRequest requestWithURL:self.appUrl]]) {self.webViewEngine = [[NSClassFromString(defaultWebViewEngineClass) alloc] initWithFrame:bounds];}@@ -538,39 +515,34 @@return self.webViewEngine.engineWebView;}-- (NSString*)userAgent+- (void)createLaunchView{- if (_userAgent != nil) {- return _userAgent;- }+ CGRect webViewBounds = self.view.bounds;+ webViewBounds.origin = self.view.bounds.origin;- NSString* localBaseUserAgent;- if (self.baseUserAgent != nil) {- localBaseUserAgent = self.baseUserAgent;- } else if ([self.settings cordovaSettingForKey:@"OverrideUserAgent"] != nil) {- localBaseUserAgent = [self.settings cordovaSettingForKey:@"OverrideUserAgent"];- } else {- localBaseUserAgent = [CDVUserAgentUtil originalUserAgent];- }- NSString* appendUserAgent = [self.settings cordovaSettingForKey:@"AppendUserAgent"];- if (appendUserAgent) {- _userAgent = [NSString stringWithFormat:@"%@ %@", localBaseUserAgent, appendUserAgent];- } else {- // Use our address as a unique number to append to the User-Agent.- _userAgent = localBaseUserAgent;+ UIView* view = [[UIView alloc] initWithFrame:webViewBounds];++ NSString* launchStoryboardName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UILaunchStoryboardName"];+ if (launchStoryboardName != nil) {+ UIStoryboard* storyboard = [UIStoryboard storyboardWithName:launchStoryboardName bundle:[NSBundle mainBundle]];+ UIViewController* vc = [storyboard instantiateInitialViewController];++ [view addSubview:vc.view];}- return _userAgent;++ self.launchView = view;+ [self.view addSubview:view];}- (void)createGapView{CGRect webViewBounds = self.view.bounds;-webViewBounds.origin = self.view.bounds.origin;UIView* view = [self newCordovaViewWithFrame:webViewBounds];-+ view.hidden = YES;view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);+[self.view addSubview:view];[self.view sendSubviewToBack:view];}@@ -786,13 +758,49 @@[self.commandDelegate evalJs:@"cordova.fireDocumentEvent('pause', null, true);" scheduledOnRunLoop:NO];}+/**+ Show the webview and fade out the intermediary view+ This is to prevent the flashing of the mainViewController+ */+- (void)onWebViewPageDidLoad:(NSNotification*)notification+{+ self.webView.hidden = NO;++ if ([self.settings cordovaBoolSettingForKey:@"AutoHideSplashScreen" defaultValue:YES]) {+ [self showLaunchScreen:NO];+ }+}++/**+ Method to be called from the plugin JavaScript to show or hide the launch screen.+ */+- (void)showLaunchScreen:(BOOL)visible+{+ CGFloat splashScreenDelay = [self.settings cordovaFloatSettingForKey:@"SplashScreenDelay" defaultValue:0];++ // AnimateWithDuration takes seconds but cordova documentation specifies milliseconds+ CGFloat fadeSplashScreenDuration = [self.settings cordovaFloatSettingForKey:@"FadeSplashScreenDuration" defaultValue:250];++ // Setting minimum value for fade to 0.25 seconds+ fadeSplashScreenDuration = fadeSplashScreenDuration < 250 ? 250 : fadeSplashScreenDuration;++ // Divide by 1000 because config returns milliseconds and NSTimer takes seconds+ CGFloat delayToFade = (MAX(splashScreenDelay, fadeSplashScreenDuration) - fadeSplashScreenDuration)/1000;+ CGFloat fadeDuration = fadeSplashScreenDuration/1000;++ [NSTimer scheduledTimerWithTimeInterval:delayToFade repeats:NO block:^(NSTimer * _Nonnull timer) {+ [UIView animateWithDuration:fadeDuration animations:^{+ [self.launchView setAlpha:(visible ? 1 : 0)];+ }];+ }];+}+// ///////////////////////- (void)dealloc{[[NSNotificationCenter defaultCenter] removeObserver:self];- [CDVUserAgentUtil releaseLock:&_userAgentLockToken];[_commandQueue dispose];[[self.pluginObjects allValues] makeObjectsPerformSelector:@selector(dispose)];@@ -802,9 +810,4 @@self.webViewEngine = nil;}-- (NSInteger*)userAgentLockToken-{- return &_userAgentLockToken;-}-@enddiff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWebViewEngineProtocol.h b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWebViewEngineProtocol.hindex 34d07f3d0..e6126a4b4 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWebViewEngineProtocol.h+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/CDVWebViewEngineProtocol.h@@ -20,7 +20,6 @@#import <UIKit/UIKit.h>#define kCDVWebViewEngineScriptMessageHandlers @"kCDVWebViewEngineScriptMessageHandlers"-#define kCDVWebViewEngineUIWebViewDelegate @"kCDVWebViewEngineUIWebViewDelegate"#define kCDVWebViewEngineWKNavigationDelegate @"kCDVWebViewEngineWKNavigationDelegate"#define kCDVWebViewEngineWKUIDelegate @"kCDVWebViewEngineWKUIDelegate"#define kCDVWebViewEngineWebViewPreferences @"kCDVWebViewEngineWebViewPreferences"diff --git a/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.m b/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.mindex dcac40f12..1266ba20f 100644--- a/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.m+++ b/cordova/platforms/ios/CordovaLib/Classes/Public/NSDictionary+CordovaPreferences.m@@ -32,8 +32,37 @@BOOL value = defaultValue;id prefObj = [self cordovaSettingForKey:key];- if (prefObj != nil) {- value = [(NSNumber*)prefObj boolValue];+ if (prefObj == nil) {+ NSLog(@"The preference key \"%@\" is not defined and will default to \"%@\"",+ key,+ (defaultValue ? @"TRUE" : @"FALSE"));++ return value;+ }++ if ([prefObj isKindOfClass:NSString.class]) {+ prefObj = [prefObj lowercaseString];++ if (+ // True Case+ [prefObj isEqualToString:@"true"] ||+ [prefObj isEqualToString:@"1"] ||+ // False Case+ [prefObj isEqualToString:@"false"] ||+ [prefObj isEqualToString:@"0"]+ )+ {+ value = [prefObj isEqualToString:@"true"] || [prefObj isEqualToString:@"1"];+ }+ } else if (+ [prefObj isKindOfClass:NSNumber.class] &&+ (+ [prefObj isEqual: @YES] ||+ [prefObj isEqual: @NO]+ )+ )+ {+ value = [prefObj isEqual: @YES];}return value;diff --git a/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxprojindex 024a9e608..2ae1b42c8 100644--- a/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj+++ b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/project.pbxproj@@ -3,28 +3,33 @@archiveVersion = 1;classes = {};- objectVersion = 48;+ objectVersion = 52;objects = {/* Begin PBXBuildFile section */28BFF9141F355A4E00DDF01A /* CDVLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 28BFF9121F355A4E00DDF01A /* CDVLogger.h */; };28BFF9151F355A4E00DDF01A /* CDVLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 28BFF9131F355A4E00DDF01A /* CDVLogger.m */; };- 30193A501AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */; };- 30193A511AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */; };+ 2F4D42BC23F218BA00501999 /* CDVURLSchemeHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F4D42BA23F218BA00501999 /* CDVURLSchemeHandler.h */; };+ 2F4D42BD23F218BA00501999 /* CDVURLSchemeHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F4D42BB23F218BA00501999 /* CDVURLSchemeHandler.m */; };+ 2FCCEA17247E7366007276A8 /* CDVLaunchScreen.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E714D3423F535B500A321AF /* CDVLaunchScreen.m */; };+ 2FCCEA18247E7366007276A8 /* CDVLaunchScreen.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E714D3223F535B500A321AF /* CDVLaunchScreen.h */; };3093E2231B16D6A3003F381A /* CDVIntentAndNavigationFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */; };3093E2241B16D6A3003F381A /* CDVIntentAndNavigationFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */; };- 7E7F69B61ABA35D8007546F4 /* CDVLocalStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */; };- 7E7F69B81ABA368F007546F4 /* CDVUIWebViewEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */; };+ 4E23F8FB23E16E96006CD852 /* CDVWebViewProcessPoolFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E23F8F523E16E96006CD852 /* CDVWebViewProcessPoolFactory.m */; };+ 4E23F8FC23E16E96006CD852 /* CDVWebViewUIDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E23F8F623E16E96006CD852 /* CDVWebViewUIDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 4E23F8FD23E16E96006CD852 /* CDVWebViewUIDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E23F8F723E16E96006CD852 /* CDVWebViewUIDelegate.m */; };+ 4E23F8FE23E16E96006CD852 /* CDVWebViewEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E23F8F823E16E96006CD852 /* CDVWebViewEngine.m */; };+ 4E23F8FF23E16E96006CD852 /* CDVWebViewProcessPoolFactory.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E23F8F923E16E96006CD852 /* CDVWebViewProcessPoolFactory.h */; };+ 4E23F90023E16E96006CD852 /* CDVWebViewEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E23F8FA23E16E96006CD852 /* CDVWebViewEngine.h */; };+ 4E23F90323E17FFA006CD852 /* CDVWebViewUIDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E23F8F623E16E96006CD852 /* CDVWebViewUIDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };+ 4E714D3623F535B500A321AF /* CDVLaunchScreen.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E714D3223F535B500A321AF /* CDVLaunchScreen.h */; };+ 4E714D3823F535B500A321AF /* CDVLaunchScreen.m in Sources */ = {isa = PBXBuildFile; fileRef = 4E714D3423F535B500A321AF /* CDVLaunchScreen.m */; };7E7F69B91ABA3692007546F4 /* CDVHandleOpenURL.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF81AB9028C008C4574 /* CDVHandleOpenURL.h */; };7ED95D021AB9028C008C4574 /* CDVDebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF21AB9028C008C4574 /* CDVDebug.h */; };7ED95D031AB9028C008C4574 /* CDVJSON_private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF31AB9028C008C4574 /* CDVJSON_private.h */; };7ED95D041AB9028C008C4574 /* CDVJSON_private.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CF41AB9028C008C4574 /* CDVJSON_private.m */; };7ED95D051AB9028C008C4574 /* CDVPlugin+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF51AB9028C008C4574 /* CDVPlugin+Private.h */; };7ED95D071AB9028C008C4574 /* CDVHandleOpenURL.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CF91AB9028C008C4574 /* CDVHandleOpenURL.m */; };- 7ED95D091AB9028C008C4574 /* CDVLocalStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */; };- 7ED95D0A1AB9028C008C4574 /* CDVUIWebViewDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };- 7ED95D0B1AB9028C008C4574 /* CDVUIWebViewDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */; };- 7ED95D0D1AB9028C008C4574 /* CDVUIWebViewEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */; };7ED95D351AB9029B008C4574 /* CDV.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D0F1AB9029B008C4574 /* CDV.h */; settings = {ATTRIBUTES = (Public, ); }; };7ED95D361AB9029B008C4574 /* CDVAppDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D101AB9029B008C4574 /* CDVAppDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };7ED95D371AB9029B008C4574 /* CDVAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D111AB9029B008C4574 /* CDVAppDelegate.m */; };@@ -48,10 +53,6 @@7ED95D491AB9029B008C4574 /* CDVScreenOrientationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };7ED95D4A1AB9029B008C4574 /* CDVTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D241AB9029B008C4574 /* CDVTimer.h */; settings = {ATTRIBUTES = (Public, ); }; };7ED95D4B1AB9029B008C4574 /* CDVTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D251AB9029B008C4574 /* CDVTimer.m */; };- 7ED95D4C1AB9029B008C4574 /* CDVURLProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };- 7ED95D4D1AB9029B008C4574 /* CDVURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */; };- 7ED95D4E1AB9029B008C4574 /* CDVUserAgentUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */; settings = {ATTRIBUTES = (Public, ); }; };- 7ED95D4F1AB9029B008C4574 /* CDVUserAgentUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */; };7ED95D501AB9029B008C4574 /* CDVViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2A1AB9029B008C4574 /* CDVViewController.h */; settings = {ATTRIBUTES = (Public, ); }; };7ED95D511AB9029B008C4574 /* CDVViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D2B1AB9029B008C4574 /* CDVViewController.m */; };7ED95D521AB9029B008C4574 /* CDVWebViewEngineProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };@@ -70,8 +71,6 @@9052DE772150D040008E83D4 /* CDVPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D201AB9029B008C4574 /* CDVPlugin.m */; };9052DE782150D040008E83D4 /* CDVPluginResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D221AB9029B008C4574 /* CDVPluginResult.m */; };9052DE792150D040008E83D4 /* CDVTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D251AB9029B008C4574 /* CDVTimer.m */; };- 9052DE7A2150D040008E83D4 /* CDVURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */; };- 9052DE7B2150D040008E83D4 /* CDVUserAgentUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */; };9052DE7C2150D040008E83D4 /* CDVViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D2B1AB9029B008C4574 /* CDVViewController.m */; };9052DE7D2150D040008E83D4 /* CDVWhitelist.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D2E1AB9029B008C4574 /* CDVWhitelist.m */; };9052DE7E2150D040008E83D4 /* NSDictionary+CordovaPreferences.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D321AB9029B008C4574 /* NSDictionary+CordovaPreferences.m */; };@@ -81,10 +80,6 @@9052DE822150D040008E83D4 /* CDVGestureHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = A3B082D31BB15CEA00D8DC35 /* CDVGestureHandler.m */; };9052DE832150D040008E83D4 /* CDVIntentAndNavigationFilter.m in Sources */ = {isa = PBXBuildFile; fileRef = 3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */; };9052DE842150D040008E83D4 /* CDVHandleOpenURL.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CF91AB9028C008C4574 /* CDVHandleOpenURL.m */; };- 9052DE852150D040008E83D4 /* CDVLocalStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */; };- 9052DE862150D040008E83D4 /* CDVUIWebViewNavigationDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */; };- 9052DE872150D040008E83D4 /* CDVUIWebViewDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */; };- 9052DE882150D040008E83D4 /* CDVUIWebViewEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */; };9052DE892150D06B008E83D4 /* CDVDebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF21AB9028C008C4574 /* CDVDebug.h */; };9052DE8A2150D06B008E83D4 /* CDVJSON_private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF31AB9028C008C4574 /* CDVJSON_private.h */; };9052DE8B2150D06B008E83D4 /* CDVPlugin+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF51AB9028C008C4574 /* CDVPlugin+Private.h */; };@@ -92,9 +87,6 @@9052DE8D2150D06B008E83D4 /* CDVGestureHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = A3B082D21BB15CEA00D8DC35 /* CDVGestureHandler.h */; };9052DE8E2150D06B008E83D4 /* CDVIntentAndNavigationFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */; };9052DE8F2150D06B008E83D4 /* CDVHandleOpenURL.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CF81AB9028C008C4574 /* CDVHandleOpenURL.h */; };- 9052DE902150D06B008E83D4 /* CDVLocalStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */; };- 9052DE912150D06B008E83D4 /* CDVUIWebViewNavigationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */; };- 9052DE922150D06B008E83D4 /* CDVUIWebViewEngine.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */; };A3B082D41BB15CEA00D8DC35 /* CDVGestureHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = A3B082D21BB15CEA00D8DC35 /* CDVGestureHandler.h */; };A3B082D51BB15CEA00D8DC35 /* CDVGestureHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = A3B082D31BB15CEA00D8DC35 /* CDVGestureHandler.m */; };C0C01EB61E3911D50056E6CB /* Cordova.h in Headers */ = {isa = PBXBuildFile; fileRef = C0C01EB41E3911D50056E6CB /* Cordova.h */; settings = {ATTRIBUTES = (Public, ); }; };@@ -112,23 +104,28 @@C0C01EC61E39131A0056E6CB /* CDVPluginResult.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D211AB9029B008C4574 /* CDVPluginResult.h */; settings = {ATTRIBUTES = (Public, ); }; };C0C01EC71E39131A0056E6CB /* CDVScreenOrientationDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };C0C01EC81E39131A0056E6CB /* CDVTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D241AB9029B008C4574 /* CDVTimer.h */; settings = {ATTRIBUTES = (Public, ); }; };- C0C01EC91E39131A0056E6CB /* CDVURLProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };- C0C01ECA1E39131A0056E6CB /* CDVUserAgentUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */; settings = {ATTRIBUTES = (Public, ); }; };C0C01ECB1E39131A0056E6CB /* CDVViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2A1AB9029B008C4574 /* CDVViewController.h */; settings = {ATTRIBUTES = (Public, ); }; };C0C01ECC1E39131A0056E6CB /* CDVWebViewEngineProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; };C0C01ECD1E39131A0056E6CB /* CDVWhitelist.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D2D1AB9029B008C4574 /* CDVWhitelist.h */; settings = {ATTRIBUTES = (Public, ); }; };C0C01ECE1E39131A0056E6CB /* NSDictionary+CordovaPreferences.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D311AB9029B008C4574 /* NSDictionary+CordovaPreferences.h */; settings = {ATTRIBUTES = (Public, ); }; };C0C01ECF1E39131A0056E6CB /* NSMutableArray+QueueAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95D331AB9029B008C4574 /* NSMutableArray+QueueAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; };- C0C01ED01E3913610056E6CB /* CDVUIWebViewDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; };/* End PBXBuildFile section *//* Begin PBXFileReference section */28BFF9121F355A4E00DDF01A /* CDVLogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVLogger.h; sourceTree = "<group>"; };28BFF9131F355A4E00DDF01A /* CDVLogger.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVLogger.m; sourceTree = "<group>"; };- 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUIWebViewNavigationDelegate.m; sourceTree = "<group>"; };- 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUIWebViewNavigationDelegate.h; sourceTree = "<group>"; };+ 2F4D42BA23F218BA00501999 /* CDVURLSchemeHandler.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CDVURLSchemeHandler.h; sourceTree = "<group>"; };+ 2F4D42BB23F218BA00501999 /* CDVURLSchemeHandler.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CDVURLSchemeHandler.m; sourceTree = "<group>"; };3093E2211B16D6A3003F381A /* CDVIntentAndNavigationFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVIntentAndNavigationFilter.h; sourceTree = "<group>"; };3093E2221B16D6A3003F381A /* CDVIntentAndNavigationFilter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVIntentAndNavigationFilter.m; sourceTree = "<group>"; };+ 4E23F8F523E16E96006CD852 /* CDVWebViewProcessPoolFactory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVWebViewProcessPoolFactory.m; sourceTree = "<group>"; };+ 4E23F8F623E16E96006CD852 /* CDVWebViewUIDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVWebViewUIDelegate.h; sourceTree = "<group>"; };+ 4E23F8F723E16E96006CD852 /* CDVWebViewUIDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVWebViewUIDelegate.m; sourceTree = "<group>"; };+ 4E23F8F823E16E96006CD852 /* CDVWebViewEngine.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVWebViewEngine.m; sourceTree = "<group>"; };+ 4E23F8F923E16E96006CD852 /* CDVWebViewProcessPoolFactory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVWebViewProcessPoolFactory.h; sourceTree = "<group>"; };+ 4E23F8FA23E16E96006CD852 /* CDVWebViewEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVWebViewEngine.h; sourceTree = "<group>"; };+ 4E714D3223F535B500A321AF /* CDVLaunchScreen.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVLaunchScreen.h; sourceTree = "<group>"; };+ 4E714D3423F535B500A321AF /* CDVLaunchScreen.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVLaunchScreen.m; sourceTree = "<group>"; };68A32D7114102E1C006B237C /* libCordova.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libCordova.a; sourceTree = BUILT_PRODUCTS_DIR; };7ED95CF21AB9028C008C4574 /* CDVDebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVDebug.h; sourceTree = "<group>"; };7ED95CF31AB9028C008C4574 /* CDVJSON_private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVJSON_private.h; sourceTree = "<group>"; };@@ -136,12 +133,6 @@7ED95CF51AB9028C008C4574 /* CDVPlugin+Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CDVPlugin+Private.h"; sourceTree = "<group>"; };7ED95CF81AB9028C008C4574 /* CDVHandleOpenURL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVHandleOpenURL.h; sourceTree = "<group>"; };7ED95CF91AB9028C008C4574 /* CDVHandleOpenURL.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVHandleOpenURL.m; sourceTree = "<group>"; };- 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVLocalStorage.h; sourceTree = "<group>"; };- 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVLocalStorage.m; sourceTree = "<group>"; };- 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUIWebViewDelegate.h; sourceTree = "<group>"; };- 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUIWebViewDelegate.m; sourceTree = "<group>"; };- 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUIWebViewEngine.h; sourceTree = "<group>"; };- 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUIWebViewEngine.m; sourceTree = "<group>"; };7ED95D0F1AB9029B008C4574 /* CDV.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDV.h; sourceTree = "<group>"; };7ED95D101AB9029B008C4574 /* CDVAppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVAppDelegate.h; sourceTree = "<group>"; };7ED95D111AB9029B008C4574 /* CDVAppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVAppDelegate.m; sourceTree = "<group>"; };@@ -165,10 +156,6 @@7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVScreenOrientationDelegate.h; sourceTree = "<group>"; };7ED95D241AB9029B008C4574 /* CDVTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVTimer.h; sourceTree = "<group>"; };7ED95D251AB9029B008C4574 /* CDVTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVTimer.m; sourceTree = "<group>"; };- 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVURLProtocol.h; sourceTree = "<group>"; };- 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVURLProtocol.m; sourceTree = "<group>"; };- 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVUserAgentUtil.h; sourceTree = "<group>"; };- 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVUserAgentUtil.m; sourceTree = "<group>"; };7ED95D2A1AB9029B008C4574 /* CDVViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVViewController.h; sourceTree = "<group>"; };7ED95D2B1AB9029B008C4574 /* CDVViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDVViewController.m; sourceTree = "<group>"; };7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDVWebViewEngineProtocol.h; sourceTree = "<group>"; };@@ -241,6 +228,28 @@path = CDVIntentAndNavigationFilter;sourceTree = "<group>";};+ 4E23F8F423E16D30006CD852 /* CDVWebViewEngine */ = {+ isa = PBXGroup;+ children = (+ 4E23F8FA23E16E96006CD852 /* CDVWebViewEngine.h */,+ 4E23F8F823E16E96006CD852 /* CDVWebViewEngine.m */,+ 4E23F8F923E16E96006CD852 /* CDVWebViewProcessPoolFactory.h */,+ 4E23F8F523E16E96006CD852 /* CDVWebViewProcessPoolFactory.m */,+ 4E23F8F623E16E96006CD852 /* CDVWebViewUIDelegate.h */,+ 4E23F8F723E16E96006CD852 /* CDVWebViewUIDelegate.m */,+ );+ path = CDVWebViewEngine;+ sourceTree = "<group>";+ };+ 4E714D3123F5356700A321AF /* CDVLaunchScreen */ = {+ isa = PBXGroup;+ children = (+ 4E714D3223F535B500A321AF /* CDVLaunchScreen.h */,+ 4E714D3423F535B500A321AF /* CDVLaunchScreen.m */,+ );+ path = CDVLaunchScreen;+ sourceTree = "<group>";+ };7ED95CF11AB9028C008C4574 /* Private */ = {isa = PBXGroup;children = (@@ -258,12 +267,12 @@7ED95CF61AB9028C008C4574 /* Plugins */ = {isa = PBXGroup;children = (+ 4E714D3123F5356700A321AF /* CDVLaunchScreen */,+ 4E23F8F423E16D30006CD852 /* CDVWebViewEngine */,28BFF9111F355A1D00DDF01A /* CDVLogger */,A3B082D11BB15CEA00D8DC35 /* CDVGestureHandler */,3093E2201B16D6A3003F381A /* CDVIntentAndNavigationFilter */,7ED95CF71AB9028C008C4574 /* CDVHandleOpenURL */,- 7ED95CFA1AB9028C008C4574 /* CDVLocalStorage */,- 7ED95CFD1AB9028C008C4574 /* CDVUIWebViewEngine */,);path = Plugins;sourceTree = "<group>";@@ -277,28 +286,6 @@path = CDVHandleOpenURL;sourceTree = "<group>";};- 7ED95CFA1AB9028C008C4574 /* CDVLocalStorage */ = {- isa = PBXGroup;- children = (- 7ED95CFB1AB9028C008C4574 /* CDVLocalStorage.h */,- 7ED95CFC1AB9028C008C4574 /* CDVLocalStorage.m */,- );- path = CDVLocalStorage;- sourceTree = "<group>";- };- 7ED95CFD1AB9028C008C4574 /* CDVUIWebViewEngine */ = {- isa = PBXGroup;- children = (- 30193A4F1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h */,- 30193A4E1AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m */,- 7ED95CFE1AB9028C008C4574 /* CDVUIWebViewDelegate.h */,- 7ED95CFF1AB9028C008C4574 /* CDVUIWebViewDelegate.m */,- 7ED95D001AB9028C008C4574 /* CDVUIWebViewEngine.h */,- 7ED95D011AB9028C008C4574 /* CDVUIWebViewEngine.m */,- );- path = CDVUIWebViewEngine;- sourceTree = "<group>";- };7ED95D0E1AB9029B008C4574 /* Public */ = {isa = PBXGroup;children = (@@ -325,10 +312,6 @@7ED95D231AB9029B008C4574 /* CDVScreenOrientationDelegate.h */,7ED95D241AB9029B008C4574 /* CDVTimer.h */,7ED95D251AB9029B008C4574 /* CDVTimer.m */,- 7ED95D261AB9029B008C4574 /* CDVURLProtocol.h */,- 7ED95D271AB9029B008C4574 /* CDVURLProtocol.m */,- 7ED95D281AB9029B008C4574 /* CDVUserAgentUtil.h */,- 7ED95D291AB9029B008C4574 /* CDVUserAgentUtil.m */,7ED95D2A1AB9029B008C4574 /* CDVViewController.h */,7ED95D2B1AB9029B008C4574 /* CDVViewController.m */,7ED95D2C1AB9029B008C4574 /* CDVWebViewEngineProtocol.h */,@@ -338,6 +321,8 @@7ED95D321AB9029B008C4574 /* NSDictionary+CordovaPreferences.m */,7ED95D331AB9029B008C4574 /* NSMutableArray+QueueAdditions.h */,7ED95D341AB9029B008C4574 /* NSMutableArray+QueueAdditions.m */,+ 2F4D42BA23F218BA00501999 /* CDVURLSchemeHandler.h */,+ 2F4D42BB23F218BA00501999 /* CDVURLSchemeHandler.m */,);name = Public;path = Classes/Public;@@ -383,12 +368,11 @@C0C01EC61E39131A0056E6CB /* CDVPluginResult.h in Headers */,C0C01EC71E39131A0056E6CB /* CDVScreenOrientationDelegate.h in Headers */,C0C01EC81E39131A0056E6CB /* CDVTimer.h in Headers */,- C0C01EC91E39131A0056E6CB /* CDVURLProtocol.h in Headers */,- C0C01ECA1E39131A0056E6CB /* CDVUserAgentUtil.h in Headers */,C0C01ECB1E39131A0056E6CB /* CDVViewController.h in Headers */,C0C01ECC1E39131A0056E6CB /* CDVWebViewEngineProtocol.h in Headers */,C0C01ECD1E39131A0056E6CB /* CDVWhitelist.h in Headers */,C0C01ECE1E39131A0056E6CB /* NSDictionary+CordovaPreferences.h in Headers */,+ 4E23F90323E17FFA006CD852 /* CDVWebViewUIDelegate.h in Headers */,C0C01ECF1E39131A0056E6CB /* NSMutableArray+QueueAdditions.h in Headers */,9052DE892150D06B008E83D4 /* CDVDebug.h in Headers */,9052DE8A2150D06B008E83D4 /* CDVJSON_private.h in Headers */,@@ -397,10 +381,7 @@9052DE8D2150D06B008E83D4 /* CDVGestureHandler.h in Headers */,9052DE8E2150D06B008E83D4 /* CDVIntentAndNavigationFilter.h in Headers */,9052DE8F2150D06B008E83D4 /* CDVHandleOpenURL.h in Headers */,- 9052DE902150D06B008E83D4 /* CDVLocalStorage.h in Headers */,- 9052DE912150D06B008E83D4 /* CDVUIWebViewNavigationDelegate.h in Headers */,- C0C01ED01E3913610056E6CB /* CDVUIWebViewDelegate.h in Headers */,- 9052DE922150D06B008E83D4 /* CDVUIWebViewEngine.h in Headers */,+ 2FCCEA18247E7366007276A8 /* CDVLaunchScreen.h in Headers */,);runOnlyForDeploymentPostprocessing = 0;};@@ -415,17 +396,19 @@7ED95D3A1AB9029B008C4574 /* CDVCommandDelegate.h in Headers */,7ED95D3B1AB9029B008C4574 /* CDVCommandDelegateImpl.h in Headers */,7ED95D3D1AB9029B008C4574 /* CDVCommandQueue.h in Headers */,+ 4E23F8FF23E16E96006CD852 /* CDVWebViewProcessPoolFactory.h in Headers */,7ED95D3F1AB9029B008C4574 /* CDVConfigParser.h in Headers */,+ 2F4D42BC23F218BA00501999 /* CDVURLSchemeHandler.h in Headers */,7ED95D411AB9029B008C4574 /* CDVInvokedUrlCommand.h in Headers */,7ED95D431AB9029B008C4574 /* CDVPlugin+Resources.h in Headers */,7ED95D451AB9029B008C4574 /* CDVPlugin.h in Headers */,7ED95D471AB9029B008C4574 /* CDVPluginResult.h in Headers */,7ED95D491AB9029B008C4574 /* CDVScreenOrientationDelegate.h in Headers */,+ 4E23F8FC23E16E96006CD852 /* CDVWebViewUIDelegate.h in Headers */,7ED95D4A1AB9029B008C4574 /* CDVTimer.h in Headers */,- 7ED95D4C1AB9029B008C4574 /* CDVURLProtocol.h in Headers */,- 7ED95D4E1AB9029B008C4574 /* CDVUserAgentUtil.h in Headers */,7ED95D501AB9029B008C4574 /* CDVViewController.h in Headers */,7ED95D521AB9029B008C4574 /* CDVWebViewEngineProtocol.h in Headers */,+ 4E23F90023E16E96006CD852 /* CDVWebViewEngine.h in Headers */,7ED95D531AB9029B008C4574 /* CDVWhitelist.h in Headers */,7ED95D571AB9029B008C4574 /* NSDictionary+CordovaPreferences.h in Headers */,7ED95D591AB9029B008C4574 /* NSMutableArray+QueueAdditions.h in Headers */,@@ -436,10 +419,7 @@A3B082D41BB15CEA00D8DC35 /* CDVGestureHandler.h in Headers */,3093E2231B16D6A3003F381A /* CDVIntentAndNavigationFilter.h in Headers */,7E7F69B91ABA3692007546F4 /* CDVHandleOpenURL.h in Headers */,- 7E7F69B61ABA35D8007546F4 /* CDVLocalStorage.h in Headers */,- 30193A511AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.h in Headers */,- 7ED95D0A1AB9028C008C4574 /* CDVUIWebViewDelegate.h in Headers */,- 7E7F69B81ABA368F007546F4 /* CDVUIWebViewEngine.h in Headers */,+ 4E714D3623F535B500A321AF /* CDVLaunchScreen.h in Headers */,);runOnlyForDeploymentPostprocessing = 0;};@@ -453,6 +433,7 @@C0C01EAD1E3911D50056E6CB /* Sources */,C0C01EAE1E3911D50056E6CB /* Frameworks */,C0C01EAF1E3911D50056E6CB /* Headers */,+ CEDDBB5523948D4C00506451 /* ShellScript */,);buildRules = ();@@ -499,11 +480,12 @@};};buildConfigurationList = 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "CordovaLib" */;- compatibilityVersion = "Xcode 8.0";+ compatibilityVersion = "Xcode 11.0";developmentRegion = en;hasScannedForEncodings = 0;knownRegions = (en,+ Base,);mainGroup = 0867D691FE84028FC02AAC07;productRefGroup = 034768DFFF38A50411DB9C8B /* Products */;@@ -516,6 +498,26 @@};/* End PBXProject section */+/* Begin PBXShellScriptBuildPhase section */+ CEDDBB5523948D4C00506451 /* ShellScript */ = {+ isa = PBXShellScriptBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ inputFileListPaths = (+ );+ inputPaths = (+ );+ outputFileListPaths = (+ );+ outputPaths = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "\"${PROJECT_DIR}/../update_podspec.sh\" -s cordova\n";+ };+/* End PBXShellScriptBuildPhase section */+/* Begin PBXSourcesBuildPhase section */C0C01EAD1E3911D50056E6CB /* Sources */ = {isa = PBXSourcesBuildPhase;@@ -530,8 +532,6 @@9052DE772150D040008E83D4 /* CDVPlugin.m in Sources */,9052DE782150D040008E83D4 /* CDVPluginResult.m in Sources */,9052DE792150D040008E83D4 /* CDVTimer.m in Sources */,- 9052DE7A2150D040008E83D4 /* CDVURLProtocol.m in Sources */,- 9052DE7B2150D040008E83D4 /* CDVUserAgentUtil.m in Sources */,9052DE7C2150D040008E83D4 /* CDVViewController.m in Sources */,9052DE7D2150D040008E83D4 /* CDVWhitelist.m in Sources */,9052DE7E2150D040008E83D4 /* NSDictionary+CordovaPreferences.m in Sources */,@@ -541,10 +541,7 @@9052DE822150D040008E83D4 /* CDVGestureHandler.m in Sources */,9052DE832150D040008E83D4 /* CDVIntentAndNavigationFilter.m in Sources */,9052DE842150D040008E83D4 /* CDVHandleOpenURL.m in Sources */,- 9052DE852150D040008E83D4 /* CDVLocalStorage.m in Sources */,- 9052DE862150D040008E83D4 /* CDVUIWebViewNavigationDelegate.m in Sources */,- 9052DE872150D040008E83D4 /* CDVUIWebViewDelegate.m in Sources */,- 9052DE882150D040008E83D4 /* CDVUIWebViewEngine.m in Sources */,+ 2FCCEA17247E7366007276A8 /* CDVLaunchScreen.m in Sources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -558,24 +555,23 @@7ED95D401AB9029B008C4574 /* CDVConfigParser.m in Sources */,7ED95D421AB9029B008C4574 /* CDVInvokedUrlCommand.m in Sources */,7ED95D441AB9029B008C4574 /* CDVPlugin+Resources.m in Sources */,+ 2F4D42BD23F218BA00501999 /* CDVURLSchemeHandler.m in Sources */,7ED95D461AB9029B008C4574 /* CDVPlugin.m in Sources */,7ED95D481AB9029B008C4574 /* CDVPluginResult.m in Sources */,7ED95D4B1AB9029B008C4574 /* CDVTimer.m in Sources */,- 7ED95D4D1AB9029B008C4574 /* CDVURLProtocol.m in Sources */,- 7ED95D4F1AB9029B008C4574 /* CDVUserAgentUtil.m in Sources */,+ 4E23F8FE23E16E96006CD852 /* CDVWebViewEngine.m in Sources */,+ 4E23F8FB23E16E96006CD852 /* CDVWebViewProcessPoolFactory.m in Sources */,7ED95D511AB9029B008C4574 /* CDVViewController.m in Sources */,7ED95D541AB9029B008C4574 /* CDVWhitelist.m in Sources */,7ED95D581AB9029B008C4574 /* NSDictionary+CordovaPreferences.m in Sources */,7ED95D5A1AB9029B008C4574 /* NSMutableArray+QueueAdditions.m in Sources */,7ED95D041AB9028C008C4574 /* CDVJSON_private.m in Sources */,+ 4E23F8FD23E16E96006CD852 /* CDVWebViewUIDelegate.m in Sources */,28BFF9151F355A4E00DDF01A /* CDVLogger.m in Sources */,A3B082D51BB15CEA00D8DC35 /* CDVGestureHandler.m in Sources */,3093E2241B16D6A3003F381A /* CDVIntentAndNavigationFilter.m in Sources */,7ED95D071AB9028C008C4574 /* CDVHandleOpenURL.m in Sources */,- 7ED95D091AB9028C008C4574 /* CDVLocalStorage.m in Sources */,- 30193A501AE6350A0069A75F /* CDVUIWebViewNavigationDelegate.m in Sources */,- 7ED95D0B1AB9028C008C4574 /* CDVUIWebViewDelegate.m in Sources */,- 7ED95D0D1AB9028C008C4574 /* CDVUIWebViewEngine.m in Sources */,+ 4E714D3823F535B500A321AF /* CDVLaunchScreen.m in Sources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -587,7 +583,6 @@buildSettings = {PUBLIC_HEADERS_FOLDER_PATH = include/Cordova;TARGETED_DEVICE_FAMILY = "1,2";- WK_WEB_VIEW_ONLY = 1;};name = Debug;};@@ -596,7 +591,6 @@buildSettings = {PUBLIC_HEADERS_FOLDER_PATH = include/Cordova;TARGETED_DEVICE_FAMILY = "1,2";- WK_WEB_VIEW_ONLY = 1;};name = Release;};@@ -645,7 +639,6 @@GCC_PREFIX_HEADER = CordovaLib_Prefix.pch;GCC_PREPROCESSOR_DEFINITIONS = ("DEBUG=1",- "WK_WEB_VIEW_ONLY=$(WK_WEB_VIEW_ONLY)","$(inherited)",);GCC_WARN_64_TO_32_BIT_CONVERSION = YES;@@ -654,7 +647,7 @@GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;GCC_WARN_UNUSED_FUNCTION = YES;GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ IPHONEOS_DEPLOYMENT_TARGET = 11.0;MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;MTL_FAST_MATH = YES;ONLY_ACTIVE_ARCH = YES;@@ -662,7 +655,6 @@PRODUCT_NAME = Cordova;SDKROOT = iphoneos;SKIP_INSTALL = YES;- WK_WEB_VIEW_ONLY = 1;};name = Debug;};@@ -707,17 +699,14 @@GCC_NO_COMMON_BLOCKS = YES;GCC_PRECOMPILE_PREFIX_HEADER = YES;GCC_PREFIX_HEADER = CordovaLib_Prefix.pch;- GCC_PREPROCESSOR_DEFINITIONS = (- "WK_WEB_VIEW_ONLY=$(WK_WEB_VIEW_ONLY)",- "$(inherited)",- );+ GCC_PREPROCESSOR_DEFINITIONS = "$(inherited)";GCC_WARN_64_TO_32_BIT_CONVERSION = YES;GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;GCC_WARN_UNDECLARED_SELECTOR = YES;GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;GCC_WARN_UNUSED_FUNCTION = YES;GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ IPHONEOS_DEPLOYMENT_TARGET = 11.0;MTL_ENABLE_DEBUG_INFO = NO;MTL_FAST_MATH = YES;OTHER_LDFLAGS = "-ObjC";@@ -725,7 +714,6 @@SDKROOT = iphoneos;SKIP_INSTALL = YES;VALIDATE_PRODUCT = YES;- WK_WEB_VIEW_ONLY = 1;};name = Release;};@@ -736,12 +724,15 @@DYLIB_INSTALL_NAME_BASE = "@rpath";INFOPLIST_FILE = Cordova/Info.plist;INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ "@loader_path/Frameworks",+ );PRODUCT_BUNDLE_IDENTIFIER = org.apache.cordova.Cordova;TARGETED_DEVICE_FAMILY = "1,2";VERSIONING_SYSTEM = "apple-generic";VERSION_INFO_PREFIX = "";- WK_WEB_VIEW_ONLY = 1;};name = Debug;};@@ -752,12 +743,15 @@DYLIB_INSTALL_NAME_BASE = "@rpath";INFOPLIST_FILE = Cordova/Info.plist;INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";- LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ "@loader_path/Frameworks",+ );PRODUCT_BUNDLE_IDENTIFIER = org.apache.cordova.Cordova;TARGETED_DEVICE_FAMILY = "1,2";VERSIONING_SYSTEM = "apple-generic";VERSION_INFO_PREFIX = "";- WK_WEB_VIEW_ONLY = 1;};name = Release;};diff --git a/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plistindex e3071f032..33ba33c28 100644--- a/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist+++ b/cordova/platforms/ios/CordovaLib/CordovaLib.xcodeproj/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist@@ -7,12 +7,12 @@<key>Cordova.xcscheme_^#shared#^_</key><dict><key>orderHint</key>- <integer>1</integer>+ <integer>2</integer></dict><key>CordovaLib.xcscheme_^#shared#^_</key><dict><key>orderHint</key>- <integer>2</integer>+ <integer>1</integer></dict></dict></dict>diff --git a/cordova/platforms/ios/CordovaLib/VERSION b/cordova/platforms/ios/CordovaLib/VERSIONindex ac14c3dfa..dfda3e0b4 100644--- a/cordova/platforms/ios/CordovaLib/VERSION+++ b/cordova/platforms/ios/CordovaLib/VERSION@@ -1 +1 @@-5.1.1+6.1.0diff --git a/cordova/platforms/ios/CordovaLib/cordova.js b/cordova/platforms/ios/CordovaLib/cordova.jsindex 9813b231f..464244fed 100644--- a/cordova/platforms/ios/CordovaLib/cordova.js+++ b/cordova/platforms/ios/CordovaLib/cordova.js@@ -1,5 +1,5 @@// Platform: ios-// 9c79667cd175f51fd2edf2dc91ac8be98b89076a+// 538a985db128858c0a0eb4dd40fb9c8e5433fc94/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,7 +19,7 @@under the License.*/;(function() {-var PLATFORM_VERSION_BUILD_LABEL = '5.1.1';+var PLATFORM_VERSION_BUILD_LABEL = '6.1.0';// file: src/scripts/require.jsvar require;var define;@@ -50,10 +50,10 @@ var define;require = function (id) {if (!modules[id]) {- throw 'module ' + id + ' not found';+ throw new Error('module ' + id + ' not found');} else if (id in inProgressModules) {var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;- throw 'Cycle in require graph: ' + cycle;+ throw new Error('Cycle in require graph: ' + cycle);}if (modules[id].factory) {try {@@ -70,7 +70,7 @@ var define;define = function (id, factory) {if (Object.prototype.hasOwnProperty.call(modules, id)) {- throw 'module ' + id + ' already defined';+ throw new Error('module ' + id + ' already defined');}modules[id] = {@@ -162,7 +162,7 @@ function createEvent (type, data) {event.initEvent(type, false, false);if (data) {for (var i in data) {- if (data.hasOwnProperty(i)) {+ if (Object.prototype.hasOwnProperty.call(data, i)) {event[i] = data[i];}}@@ -310,9 +310,7 @@ var cordova = {}} catch (err) {var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;- console && console.log && console.log(msg);- console && console.log && err.stack && console.log(err.stack);- cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ cordova.fireWindowEvent('cordovacallbackerror', { message: msg, error: err });throw err;}},@@ -340,12 +338,12 @@ var utils = require('cordova/utils');var moduleExports = module.exports;var typeMap = {- 'A': 'Array',- 'D': 'Date',- 'N': 'Number',- 'S': 'String',- 'F': 'Function',- 'O': 'Object'+ A: 'Array',+ D: 'Date',+ N: 'Number',+ S: 'String',+ F: 'Function',+ O: 'Object'};function extractParamName (callee, argIndex) {@@ -498,7 +496,7 @@ var utils = require('cordova/utils');function each (objects, func, context) {for (var prop in objects) {- if (objects.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(objects, prop)) {func.apply(context, [objects[prop], prop]);}}@@ -578,7 +576,7 @@ function include (parent, objects, clobber, merge) {*/function recursiveMerge (target, src) {for (var prop in src) {- if (src.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(src, prop)) {if (target.prototype && target.prototype.constructor === target) {// If the target object is a constructor override off prototype.clobber(target.prototype, prop, src[prop]);@@ -871,19 +869,13 @@ module.exports = channel;// file: ../cordova-ios/cordova-js-src/exec.jsdefine("cordova/exec", function(require, exports, module) {-/* global require, module, atob, document */-/**- * Creates a gap bridge iframe used to notify the native code about queued+ * Creates the exec bridge used to notify the native code of* commands.*/var cordova = require('cordova');var utils = require('cordova/utils');var base64 = require('cordova/base64');-var execIframe;-var commandQueue = []; // Contains pending JS->Native messages.-var isInContextOfEvalJs = 0;-var failSafeTimerId = 0;function massageArgsJsToNative (args) {if (!args || utils.typeName(args) !== 'Array') {@@ -893,8 +885,8 @@ function massageArgsJsToNative (args) {args.forEach(function (arg, i) {if (utils.typeName(arg) === 'ArrayBuffer') {ret.push({- 'CDVType': 'ArrayBuffer',- 'data': base64.fromArrayBuffer(arg)+ CDVType: 'ArrayBuffer',+ data: base64.fromArrayBuffer(arg)});} else {ret.push(arg);@@ -913,7 +905,7 @@ function massageMessageNativeToJs (message) {return ret.buffer;};var base64ToArrayBuffer = function (b64) {- return stringToArrayBuffer(atob(b64));+ return stringToArrayBuffer(atob(b64)); // eslint-disable-line no-undef};message = base64ToArrayBuffer(message.data);}@@ -922,7 +914,7 @@ function massageMessageNativeToJs (message) {function convertMessageToArgsNativeToJs (message) {var args = [];- if (!message || !message.hasOwnProperty('CDVType')) {+ if (!message || !Object.prototype.hasOwnProperty.call(message, 'CDVType')) {args.push(message);} else if (message.CDVType === 'MultiPart') {message.messages.forEach(function (e) {@@ -934,8 +926,7 @@ function convertMessageToArgsNativeToJs (message) {return args;}-function iOSExec () {-+var iOSExec = function () {var successCallback, failCallback, service, action, actionArgs;var callbackId = null;if (typeof arguments[0] !== 'string') {@@ -952,9 +943,8 @@ function iOSExec () {// an invalid callbackId and passes it even if no callbacks were given.callbackId = 'INVALID';} else {- throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' +- 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'- );+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + // eslint-disable-line+ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);');}// If actionArgs is not provided, default to an empty array@@ -970,120 +960,25 @@ function iOSExec () {actionArgs = massageArgsJsToNative(actionArgs);- var command = [callbackId, service, action, actionArgs];-- // Stringify and queue the command. We stringify to command now to- // effectively clone the command arguments in case they are mutated before- // the command is executed.- commandQueue.push(JSON.stringify(command));-- // If we're in the context of a stringByEvaluatingJavaScriptFromString call,- // then the queue will be flushed when it returns; no need for a poke.- // Also, if there is already a command in the queue, then we've already- // poked the native side, so there is no reason to do so again.- if (!isInContextOfEvalJs && commandQueue.length === 1) {- pokeNative();- }-}--// CB-10530-function proxyChanged () {- var cexec = cordovaExec();-- return (execProxy !== cexec && // proxy objects are different- iOSExec !== cexec // proxy object is not the current iOSExec- );-}--// CB-10106-function handleBridgeChange () {- if (proxyChanged()) {- var commandString = commandQueue.shift();- while (commandString) {- var command = JSON.parse(commandString);- var callbackId = command[0];- var service = command[1];- var action = command[2];- var actionArgs = command[3];- var callbacks = cordova.callbacks[callbackId] || {};-- execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);-- commandString = commandQueue.shift();- }- return true;- }-- return false;-}--function pokeNative () {- // CB-5488 - Don't attempt to create iframe before document.body is available.- if (!document.body) {- setTimeout(pokeNative);- return;- }-- // Check if they've removed it from the DOM, and put it back if so.- if (execIframe && execIframe.contentWindow) {- execIframe.contentWindow.location = 'gap://ready';- } else {- execIframe = document.createElement('iframe');- execIframe.style.display = 'none';- execIframe.src = 'gap://ready';- document.body.appendChild(execIframe);- }- // Use a timer to protect against iframe being unloaded during the poke (CB-7735).- // This makes the bridge ~ 7% slower, but works around the poke getting lost- // when the iframe is removed from the DOM.- // An onunload listener could be used in the case where the iframe has just been- // created, but since unload events fire only once, it doesn't work in the normal- // case of iframe reuse (where unload will have already fired due to the attempted- // navigation of the page).- failSafeTimerId = setTimeout(function () {- if (commandQueue.length) {- // CB-10106 - flush the queue on bridge change- if (!handleBridgeChange()) {- pokeNative();- }- }- }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).-}--iOSExec.nativeFetchMessages = function () {- // Stop listing for window detatch once native side confirms poke.- if (failSafeTimerId) {- clearTimeout(failSafeTimerId);- failSafeTimerId = 0;- }- // Each entry in commandQueue is a JSON string already.- if (!commandQueue.length) {- return '';- }- var json = '[' + commandQueue.join(',') + ']';- commandQueue.length = 0;- return json;+ // CB-10133 DataClone DOM Exception 25 guard (fast function remover)+ var command = [callbackId, service, action, JSON.parse(JSON.stringify(actionArgs))];+ window.webkit.messageHandlers.cordova.postMessage(command);};iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {- return iOSExec.nativeEvalAndFetch(function () {- var success = status === 0 || status === 1;- var args = convertMessageToArgsNativeToJs(message);- function nc2 () {- cordova.callbackFromNative(callbackId, success, status, args, keepCallback);- }- setTimeout(nc2, 0);+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ Promise.resolve().then(function () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback); // eslint-disable-line});};+// for backwards compatibilityiOSExec.nativeEvalAndFetch = function (func) {- // This shouldn't be nested, but better to be safe.- isInContextOfEvalJs++;try {func();- return iOSExec.nativeFetchMessages();- } finally {- isInContextOfEvalJs--;+ } catch (e) {+ console.log(e);}};@@ -1153,7 +1048,6 @@ var cordova = require('cordova');var modulemapper = require('cordova/modulemapper');var platform = require('cordova/platform');var pluginloader = require('cordova/pluginloader');-var utils = require('cordova/utils');var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];@@ -1173,34 +1067,6 @@ window.setTimeout(function () {}}, 5000);-// Replace navigator before any modules are required(), to ensure it happens as soon as possible.-// We replace it so that properties that can't be clobbered can instead be overridden.-function replaceNavigator (origNavigator) {- var CordovaNavigator = function () {};- CordovaNavigator.prototype = origNavigator;- var newNavigator = new CordovaNavigator();- // This work-around really only applies to new APIs that are newer than Function.bind.- // Without it, APIs such as getGamepads() break.- if (CordovaNavigator.bind) {- for (var key in origNavigator) {- if (typeof origNavigator[key] === 'function') {- newNavigator[key] = origNavigator[key].bind(origNavigator);- } else {- (function (k) {- utils.defineGetterSetter(newNavigator, key, function () {- return origNavigator[k];- });- })(key);- }- }- }- return newNavigator;-}--if (window.navigator) {- window.navigator = replaceNavigator(window.navigator);-}-if (!window.console) {window.console = {log: function () {}@@ -1266,7 +1132,6 @@ channel.join(function () {channel.join(function () {require('cordova').fireDocumentEvent('deviceready');}, channel.deviceReadyChannelsArray);-}, platformInitChannelsArray);});@@ -1378,6 +1243,14 @@ module.exports = {// see the file under plugin/ios/console.jsrequire('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');+ // Attach the wkwebkit utility to window.WkWebView+ // see the file under plugin/ios/wkwebkit.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/wkwebkit', 'window.WkWebView');++ // Attach the splashscreen utility to window.navigator.splashscreen+ // see the file under plugin/ios/launchscreen.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/launchscreen', 'navigator.splashscreen');+require('cordova/channel').onNativeReady.fire();}};@@ -1555,6 +1428,24 @@ for (var key in console) {});+// file: ../cordova-ios/cordova-js-src/plugin/ios/launchscreen.js+define("cordova/plugin/ios/launchscreen", function(require, exports, module) {++var exec = require('cordova/exec');++var launchscreen = {+ show: function () {+ exec(null, null, 'LaunchScreen', 'show', []);+ },+ hide: function () {+ exec(null, null, 'LaunchScreen', 'hide', []);+ }+};++module.exports = launchscreen;++});+// file: ../cordova-ios/cordova-js-src/plugin/ios/logger.jsdefine("cordova/plugin/ios/logger", function(require, exports, module) {@@ -1851,7 +1742,6 @@ function __format (formatString, args) {}function __formatted (object, formatChar) {-try {switch (formatChar) {case 'j':@@ -1889,6 +1779,33 @@ document.addEventListener('deviceready', logger.__onDeviceReady, false);});+// file: ../cordova-ios/cordova-js-src/plugin/ios/wkwebkit.js+define("cordova/plugin/ios/wkwebkit", function(require, exports, module) {++var exec = require('cordova/exec');++var WkWebKit = {+ allowsBackForwardNavigationGestures: function (allow) {+ exec(null, null, 'CDVWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);+ },+ convertFilePath: function (path) {+ if (!path || !window.CDV_ASSETS_URL) {+ return path;+ }+ if (path.startsWith('/')) {+ return window.CDV_ASSETS_URL + '/_app_file_' + path;+ }+ if (path.startsWith('file://')) {+ return window.CDV_ASSETS_URL + path.replace('file://', '/_app_file_');+ }+ return path;+ }+};++module.exports = WkWebKit;++});+// file: src/common/pluginloader.jsdefine("cordova/pluginloader", function(require, exports, module) {@@ -2160,7 +2077,6 @@ utils.extend = (function () {var F = function () {};// extend Child from Parentreturn function (Child, Parent) {-F.prototype = Parent.prototype;Child.prototype = new F();Child.__super__ = Parent.prototype;diff --git a/cordova/platforms/ios/Podfile b/cordova/platforms/ios/Podfileindex 2fcf677c5..9316786cb 100644--- a/cordova/platforms/ios/Podfile+++ b/cordova/platforms/ios/Podfile@@ -1,6 +1,6 @@# DO NOT MODIFY -- auto-generated by Apache Cordova-platform :ios, '10.0'+platform :ios, '11.0'target 'TagSpaces Beta' doproject 'TagSpaces Beta.xcodeproj'diff --git a/cordova/platforms/ios/TagSpaces Beta.xcodeproj/project.pbxproj b/cordova/platforms/ios/TagSpaces Beta.xcodeproj/project.pbxprojindex 08b915c5c..10156b0f7 100755--- a/cordova/platforms/ios/TagSpaces Beta.xcodeproj/project.pbxproj+++ b/cordova/platforms/ios/TagSpaces Beta.xcodeproj/project.pbxproj@@ -3,35 +3,38 @@archiveVersion = 1;classes = {};- objectVersion = 46;+ objectVersion = 52;objects = {/* Begin PBXBuildFile section */0207DA581B56EA530066E2B4 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0207DA571B56EA530066E2B4 /* Images.xcassets */; };- 16B2D55C46694FAB859B04D1 /* CDVFile.m in Sources */ = {isa = PBXBuildFile; fileRef = B8464A38DD2D4F7FADA4A05D /* CDVFile.m */; };1D3623260D0F684500981E51 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D3623250D0F684500981E51 /* AppDelegate.m */; };1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; };+ 2ECBCFEFA8A14C0EB682FAB0 /* appbeep.wav in Resources */ = {isa = PBXBuildFile; fileRef = 856852A9946B4DA7BF4EDC62 /* appbeep.wav */; };301BF552109A68D80062928A /* libCordova.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 301BF535109A57CC0062928A /* libCordova.a */; settings = {ATTRIBUTES = (Required, ); }; };302D95F114D2391D003F00A1 /* MainViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 302D95EF14D2391D003F00A1 /* MainViewController.m */; };302D95F214D2391D003F00A1 /* MainViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 302D95F014D2391D003F00A1 /* MainViewController.xib */; };- 3419DFF8E26C40049D27FEF9 /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 40A26423D0AF4AE598297D25 /* ImageIO.framework */; settings = {ATTRIBUTES = (Weak, ); }; };- 44ACB9D58C8147E2AECFD8E3 /* CDVJpegHeaderWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 1EC446528AF448AB9C17958C /* CDVJpegHeaderWriter.m */; };- 5330031C98004A548A04FB04 /* UIImage+CropScaleOrientation.m in Sources */ = {isa = PBXBuildFile; fileRef = 49D060970246496597C22CAD /* UIImage+CropScaleOrientation.m */; };- 53F98373E0254B50ADFC7482 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 720D38A8FC114FB9860E24F1 /* AVFoundation.framework */; };- 55E6C374E3FD4A4CABBDF7A2 /* APPBackgroundMode.m in Sources */ = {isa = PBXBuildFile; fileRef = 4A95936F2A674A518C47DC9D /* APPBackgroundMode.m */; };- 68EEB8A986134A178EACDC51 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0C212A0B05B3406590A5DE1A /* CoreLocation.framework */; };+ 3912058EB13E485BB506E071 /* CDVJpegHeaderWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 4923C134A48F48CF8E8EC47F /* CDVJpegHeaderWriter.m */; };+ 41C0872421BD4657B31F7C60 /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E73A2C7396C94680B1CFF239 /* ImageIO.framework */; settings = {ATTRIBUTES = (Weak, ); }; };+ 4C912013458B4E34A6BEBFDF /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 92C5D5470BCB43B191A3755E /* AVFoundation.framework */; };+ 4ED540FB26504C7EBC5F2310 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3A8061B9E2584C6F9BFA435B /* CoreLocation.framework */; };+ 6A47B1C2D9D5498C92FD79A4 /* FileOpener2.m in Sources */ = {isa = PBXBuildFile; fileRef = 38DE4A52BF3A428CB85A01D3 /* FileOpener2.m */; };6AFF5BF91D6E424B00AB3073 /* CDVLaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6AFF5BF81D6E424B00AB3073 /* CDVLaunchScreen.storyboard */; };- 721F0E8CD32D41C399A0407B /* appbeep.wav in Resources */ = {isa = PBXBuildFile; fileRef = 101925A545E94A63B15DB828 /* appbeep.wav */; };- 9160B31B3A944071B00DBEAA /* FileOpener2.m in Sources */ = {isa = PBXBuildFile; fileRef = 4B5AE9F692F74481BC1E0C86 /* FileOpener2.m */; };- 93C68FEC56FE482C8A4A2E86 /* CDVLocalFilesystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 476A44F1A9C44535A0A00615 /* CDVLocalFilesystem.m */; };- CDBEA11FAD00489CAAD7BCB3 /* CDVCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 93FC43CFD33C4C9B89754A11 /* CDVCamera.m */; };- D542412872474BA08645A2B6 /* APPMethodMagic.m in Sources */ = {isa = PBXBuildFile; fileRef = D68F7DFBF1BD4A08A2CA9BB5 /* APPMethodMagic.m */; };- ED2346D5DC534F0E8A5C4B72 /* CDVAssetLibraryFilesystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 0B70DBAD7A3346F4A04BEB0D /* CDVAssetLibraryFilesystem.m */; };- FD08D10174C049C9B2AF1045 /* CDVDevice.m in Sources */ = {isa = PBXBuildFile; fileRef = 3D4B8429E3AA4CCABA3483C2 /* CDVDevice.m */; };- FD813F4BF3564D7286CEC694 /* CDVWKWebViewEngine.m in Sources */ = {isa = PBXBuildFile; fileRef = 1BAE8F2712124FE9A9CA0C3F /* CDVWKWebViewEngine.m */; };- FC3FD5B10EE249F8BCAE2897 /* CDVWKWebViewUIDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1FE0EEB88E3548539E8DB7BF /* CDVWKWebViewUIDelegate.m */; };- F0EF40AA3831439690728A0F /* CDVWKProcessPoolFactory.m in Sources */ = {isa = PBXBuildFile; fileRef = B559D10CCDB7435DB450FCE8 /* CDVWKProcessPoolFactory.m */; };- 8EA0B645CECC433081B8E848 /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1785AEC413494EC89B548B1E /* WebKit.framework */; settings = {ATTRIBUTES = (Weak, ); }; };+ 71C228DE9D4F41FF8AFBC4F6 /* CDVLocalFilesystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 98D2D7F7AB794421990E8FC5 /* CDVLocalFilesystem.m */; };+ 78B9CD3FBED74924A25196E2 /* Downloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9963CE05D2C745349F080238 /* Downloader.swift */; };+ 7C6065AB08F9429A8C4E974C /* CDVFile.m in Sources */ = {isa = PBXBuildFile; fileRef = 2D9B854200814AE3A9C2E770 /* CDVFile.m */; };+ 90B55385075445E8AFF6E723 /* UIImage+CropScaleOrientation.m in Sources */ = {isa = PBXBuildFile; fileRef = 834C76EB13ED4B4D9F0E6F5C /* UIImage+CropScaleOrientation.m */; };+ 98F6A5526062497CB73A1B0A /* CDVDevice.m in Sources */ = {isa = PBXBuildFile; fileRef = A0CD0395A4C34F10BAAB0237 /* CDVDevice.m */; };+ DA515680F8F14C71B59F498F /* APPBackgroundMode.m in Sources */ = {isa = PBXBuildFile; fileRef = 671C10DB25DA4F2AA5974527 /* APPBackgroundMode.m */; };+ DA68256931E643F9A3BF0909 /* CDVCamera.m in Sources */ = {isa = PBXBuildFile; fileRef = 27B78C661E5A48FE99AB7230 /* CDVCamera.m */; };+ DCC01C38133C46BBA9BFE8C6 /* CDVAssetLibraryFilesystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 37F82A6CC29C4503B5AB6765 /* CDVAssetLibraryFilesystem.m */; };+ F0E7F6EF3B734A7094F48E3F /* APPMethodMagic.m in Sources */ = {isa = PBXBuildFile; fileRef = A242041FBB71452BA3630292 /* APPMethodMagic.m */; };+ 11837AAE46E24B8DA394DF19 /* NSString+SSURLEncoding.m in Sources */ = {isa = PBXBuildFile; fileRef = 91D46E5FC6B44B8796CD0432 /* NSString+SSURLEncoding.m */; };+ 4451916358BD49A8A7644D56 /* SocialSharing.m in Sources */ = {isa = PBXBuildFile; fileRef = B3ED20DEF712481D94438616 /* SocialSharing.m */; };+ A452553E07F64C0CAA35D96C /* Social.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E7E61147BE1945D5A406B430 /* Social.framework */; settings = {ATTRIBUTES = (Weak, ); }; };+ 64DF0AC9557C494C80C9B7B4 /* MessageUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 374D90B51F7945D892F3EF98 /* MessageUI.framework */; settings = {ATTRIBUTES = (Weak, ); }; };+ EE38F8704D0B42B7A525EF73 /* CDVWKWebViewFileXhr.m in Sources */ = {isa = PBXBuildFile; fileRef = 20B409CCA31946F6A58ECC19 /* CDVWKWebViewFileXhr.m */; };+ 2C8E5B76AA29404A99E9CACD /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0A5FDD2F614B465AB09E339E /* WebKit.framework */; settings = {ATTRIBUTES = (Weak, ); }; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */@@ -59,17 +62,15 @@/* End PBXContainerItemProxy section *//* Begin PBXFileReference section */- 00BBD8B96CA64BC19D7F67BE /* CDVExif.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVExif.h; path = "cordova-plugin-camera/CDVExif.h"; sourceTree = "<group>"; };0207DA571B56EA530066E2B4 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = "TagSpaces Beta/Images.xcassets"; sourceTree = SOURCE_ROOT; };- 032B343EF5F94282A58A7531 /* FileOpener2.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = FileOpener2.h; path = "cordova-plugin-file-opener2/FileOpener2.h"; sourceTree = "<group>"; };- 0B70DBAD7A3346F4A04BEB0D /* CDVAssetLibraryFilesystem.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVAssetLibraryFilesystem.m; path = "cordova-plugin-file/CDVAssetLibraryFilesystem.m"; sourceTree = "<group>"; };- 0C212A0B05B3406590A5DE1A /* CoreLocation.framework */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; };- 101925A545E94A63B15DB828 /* appbeep.wav */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; path = appbeep.wav; sourceTree = "<group>"; };1D3623240D0F684500981E51 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };1D3623250D0F684500981E51 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };1D6058910D05DD3D006BFB54 /* TagSpaces Beta.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "TagSpaces Beta.app"; sourceTree = BUILT_PRODUCTS_DIR; };- 1EC446528AF448AB9C17958C /* CDVJpegHeaderWriter.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVJpegHeaderWriter.m; path = "cordova-plugin-camera/CDVJpegHeaderWriter.m"; sourceTree = "<group>"; };+ 21B8ADFA4658428FBB1F7958 /* CDVAssetLibraryFilesystem.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVAssetLibraryFilesystem.h; path = "cordova-plugin-file/CDVAssetLibraryFilesystem.h"; sourceTree = "<group>"; };+ 25E8D9BCF59A432CB579644E /* FileOpener2.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = FileOpener2.h; path = "cordova-plugin-file-opener2/FileOpener2.h"; sourceTree = "<group>"; };+ 27B78C661E5A48FE99AB7230 /* CDVCamera.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVCamera.m; path = "cordova-plugin-camera/CDVCamera.m"; sourceTree = "<group>"; };29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };+ 2D9B854200814AE3A9C2E770 /* CDVFile.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVFile.m; path = "cordova-plugin-file/CDVFile.m"; sourceTree = "<group>"; };301BF52D109A57CC0062928A /* CordovaLib.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = CordovaLib.xcodeproj; path = CordovaLib/CordovaLib.xcodeproj; sourceTree = "<group>"; };301BF56E109A69640062928A /* www */ = {isa = PBXFileReference; lastKnownFileType = folder; path = www; sourceTree = SOURCE_ROOT; };302D95EE14D2391D003F00A1 /* MainViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MainViewController.h; sourceTree = "<group>"; };@@ -79,38 +80,43 @@3047A5101AB8059700498E2A /* build-release.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = "build-release.xcconfig"; path = "cordova/build-release.xcconfig"; sourceTree = SOURCE_ROOT; };3047A5111AB8059700498E2A /* build.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = build.xcconfig; path = cordova/build.xcconfig; sourceTree = SOURCE_ROOT; };32CA4F630368D1EE00C91783 /* TagSpaces Beta-Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "TagSpaces Beta-Prefix.pch"; sourceTree = "<group>"; };- 3D4B8429E3AA4CCABA3483C2 /* CDVDevice.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVDevice.m; path = "cordova-plugin-device/CDVDevice.m"; sourceTree = "<group>"; };- 3F8642D53B1A40708D0784D1 /* CDVCamera.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVCamera.h; path = "cordova-plugin-camera/CDVCamera.h"; sourceTree = "<group>"; };- 40A26423D0AF4AE598297D25 /* ImageIO.framework */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = System/Library/Frameworks/ImageIO.framework; sourceTree = SDKROOT; };- 450308C53A3E4D278EC4286B /* APPMethodMagic.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = APPMethodMagic.h; path = "cordova-plugin-background-mode/APPMethodMagic.h"; sourceTree = "<group>"; };- 476A44F1A9C44535A0A00615 /* CDVLocalFilesystem.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVLocalFilesystem.m; path = "cordova-plugin-file/CDVLocalFilesystem.m"; sourceTree = "<group>"; };- 49D060970246496597C22CAD /* UIImage+CropScaleOrientation.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = "UIImage+CropScaleOrientation.m"; path = "cordova-plugin-camera/UIImage+CropScaleOrientation.m"; sourceTree = "<group>"; };- 4A95936F2A674A518C47DC9D /* APPBackgroundMode.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = APPBackgroundMode.m; path = "cordova-plugin-background-mode/APPBackgroundMode.m"; sourceTree = "<group>"; };- 4B5AE9F692F74481BC1E0C86 /* FileOpener2.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = FileOpener2.m; path = "cordova-plugin-file-opener2/FileOpener2.m"; sourceTree = "<group>"; };+ 37F82A6CC29C4503B5AB6765 /* CDVAssetLibraryFilesystem.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVAssetLibraryFilesystem.m; path = "cordova-plugin-file/CDVAssetLibraryFilesystem.m"; sourceTree = "<group>"; };+ 38DE4A52BF3A428CB85A01D3 /* FileOpener2.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = FileOpener2.m; path = "cordova-plugin-file-opener2/FileOpener2.m"; sourceTree = "<group>"; };+ 3A8061B9E2584C6F9BFA435B /* CoreLocation.framework */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; };+ 43DBA31C36DC40A29CDE164C /* APPMethodMagic.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = APPMethodMagic.h; path = "cordova-plugin-background-mode/APPMethodMagic.h"; sourceTree = "<group>"; };+ 4923C134A48F48CF8E8EC47F /* CDVJpegHeaderWriter.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVJpegHeaderWriter.m; path = "cordova-plugin-camera/CDVJpegHeaderWriter.m"; sourceTree = "<group>"; };+ 5CBE442109A44548BFA1204B /* CDVFile.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVFile.h; path = "cordova-plugin-file/CDVFile.h"; sourceTree = "<group>"; };+ 5F5B13AA0E7A45928786E136 /* APPBackgroundMode.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = APPBackgroundMode.h; path = "cordova-plugin-background-mode/APPBackgroundMode.h"; sourceTree = "<group>"; };+ 671C10DB25DA4F2AA5974527 /* APPBackgroundMode.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = APPBackgroundMode.m; path = "cordova-plugin-background-mode/APPBackgroundMode.m"; sourceTree = "<group>"; };6AFF5BF81D6E424B00AB3073 /* CDVLaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = CDVLaunchScreen.storyboard; path = "TagSpaces Beta/CDVLaunchScreen.storyboard"; sourceTree = SOURCE_ROOT; };- 720D38A8FC114FB9860E24F1 /* AVFoundation.framework */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; };- 7FD56FBDFA8B4E0A906A97B0 /* UIImage+CropScaleOrientation.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = "UIImage+CropScaleOrientation.h"; path = "cordova-plugin-camera/UIImage+CropScaleOrientation.h"; sourceTree = "<group>"; };+ 6B1891CB1153452DB5F33F33 /* UIImage+CropScaleOrientation.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = "UIImage+CropScaleOrientation.h"; path = "cordova-plugin-camera/UIImage+CropScaleOrientation.h"; sourceTree = "<group>"; };+ 834C76EB13ED4B4D9F0E6F5C /* UIImage+CropScaleOrientation.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = "UIImage+CropScaleOrientation.m"; path = "cordova-plugin-camera/UIImage+CropScaleOrientation.m"; sourceTree = "<group>"; };+ 856852A9946B4DA7BF4EDC62 /* appbeep.wav */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; path = appbeep.wav; sourceTree = "<group>"; };8D1107310486CEB800E47090 /* TagSpaces Beta-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "TagSpaces Beta-Info.plist"; path = "TagSpaces Beta/TagSpaces Beta-Info.plist"; plistStructureDefinitionIdentifier = "com.apple.xcode.plist.structure-definition.iphone.info-plist"; sourceTree = SOURCE_ROOT; };- 93FC43CFD33C4C9B89754A11 /* CDVCamera.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVCamera.m; path = "cordova-plugin-camera/CDVCamera.m"; sourceTree = "<group>"; };- B1E38A50DE384D2BB20890EB /* CDVDevice.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVDevice.h; path = "cordova-plugin-device/CDVDevice.h"; sourceTree = "<group>"; };- B8464A38DD2D4F7FADA4A05D /* CDVFile.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVFile.m; path = "cordova-plugin-file/CDVFile.m"; sourceTree = "<group>"; };- BBE6D0DB8D0C48C3A48B5D6A /* CDVLocalFilesystem.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVLocalFilesystem.h; path = "cordova-plugin-file/CDVLocalFilesystem.h"; sourceTree = "<group>"; };- D68F7DFBF1BD4A08A2CA9BB5 /* APPMethodMagic.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = APPMethodMagic.m; path = "cordova-plugin-background-mode/APPMethodMagic.m"; sourceTree = "<group>"; };+ 92C5D5470BCB43B191A3755E /* AVFoundation.framework */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; };+ 943EE43957C44D10AE8DF7E2 /* CDVDevice.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVDevice.h; path = "cordova-plugin-device/CDVDevice.h"; sourceTree = "<group>"; };+ 98D2D7F7AB794421990E8FC5 /* CDVLocalFilesystem.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVLocalFilesystem.m; path = "cordova-plugin-file/CDVLocalFilesystem.m"; sourceTree = "<group>"; };+ 9963CE05D2C745349F080238 /* Downloader.swift */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.swift; name = Downloader.swift; path = com.whebcraft.cordova.plugin.downloader/Downloader.swift; sourceTree = "<group>"; };+ 9D58C635D56F4E4FA8361ABD /* CDVExif.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVExif.h; path = "cordova-plugin-camera/CDVExif.h"; sourceTree = "<group>"; };+ A0CD0395A4C34F10BAAB0237 /* CDVDevice.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = CDVDevice.m; path = "cordova-plugin-device/CDVDevice.m"; sourceTree = "<group>"; };+ A242041FBB71452BA3630292 /* APPMethodMagic.m */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.objc; name = APPMethodMagic.m; path = "cordova-plugin-background-mode/APPMethodMagic.m"; sourceTree = "<group>"; };+ BB314C1742724790963463E2 /* CDVLocalFilesystem.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVLocalFilesystem.h; path = "cordova-plugin-file/CDVLocalFilesystem.h"; sourceTree = "<group>"; };+ D0D35D8448024980B5C3FC47 /* CDVCamera.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVCamera.h; path = "cordova-plugin-camera/CDVCamera.h"; sourceTree = "<group>"; };+ E73A2C7396C94680B1CFF239 /* ImageIO.framework */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = System/Library/Frameworks/ImageIO.framework; sourceTree = SDKROOT; };EB87FDF31871DA8E0020F90C /* www */ = {isa = PBXFileReference; lastKnownFileType = folder; name = www; path = ../../www; sourceTree = "<group>"; };EB87FDF41871DAF40020F90C /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = ../../config.xml; sourceTree = "<group>"; };ED33DF2A687741AEAF9F8254 /* Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bridging-Header.h"; sourceTree = "<group>"; };- F0F164CAE6E346428F43D0C9 /* APPBackgroundMode.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = APPBackgroundMode.h; path = "cordova-plugin-background-mode/APPBackgroundMode.h"; sourceTree = "<group>"; };- F69E9D0C17334829B9EA3A3F /* CDVAssetLibraryFilesystem.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVAssetLibraryFilesystem.h; path = "cordova-plugin-file/CDVAssetLibraryFilesystem.h"; sourceTree = "<group>"; };F840E1F0165FE0F500CFE078 /* config.xml */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = config.xml; path = "TagSpaces Beta/config.xml"; sourceTree = "<group>"; };- FDB5379162244D3F92106617 /* CDVJpegHeaderWriter.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVJpegHeaderWriter.h; path = "cordova-plugin-camera/CDVJpegHeaderWriter.h"; sourceTree = "<group>"; };- FFEEE9F8C3654B1D80D32A88 /* CDVFile.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVFile.h; path = "cordova-plugin-file/CDVFile.h"; sourceTree = "<group>"; };- 1BAE8F2712124FE9A9CA0C3F /* CDVWKWebViewEngine.m */ = {isa = PBXFileReference; name = "CDVWKWebViewEngine.m"; path = "cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };- 1FE0EEB88E3548539E8DB7BF /* CDVWKWebViewUIDelegate.m */ = {isa = PBXFileReference; name = "CDVWKWebViewUIDelegate.m"; path = "cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };- B559D10CCDB7435DB450FCE8 /* CDVWKProcessPoolFactory.m */ = {isa = PBXFileReference; name = "CDVWKProcessPoolFactory.m"; path = "cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };- 4E41725864554075A3FC52DE /* CDVWKWebViewEngine.h */ = {isa = PBXFileReference; name = "CDVWKWebViewEngine.h"; path = "cordova-plugin-wkwebview-engine/CDVWKWebViewEngine.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };- E777FC5C974D4356A3FD36CD /* CDVWKWebViewUIDelegate.h */ = {isa = PBXFileReference; name = "CDVWKWebViewUIDelegate.h"; path = "cordova-plugin-wkwebview-engine/CDVWKWebViewUIDelegate.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };- 52525C431A294171B3CC274C /* CDVWKProcessPoolFactory.h */ = {isa = PBXFileReference; name = "CDVWKProcessPoolFactory.h"; path = "cordova-plugin-wkwebview-engine/CDVWKProcessPoolFactory.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };- 1785AEC413494EC89B548B1E /* WebKit.framework */ = {isa = PBXFileReference; name = "WebKit.framework"; path = "System/Library/Frameworks/WebKit.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };+ FE4894ACD2AC49A5B929D1D4 /* CDVJpegHeaderWriter.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = CDVJpegHeaderWriter.h; path = "cordova-plugin-camera/CDVJpegHeaderWriter.h"; sourceTree = "<group>"; };+ 91D46E5FC6B44B8796CD0432 /* NSString+SSURLEncoding.m */ = {isa = PBXFileReference; name = "NSString+SSURLEncoding.m"; path = "cordova-plugin-x-socialsharing/NSString+SSURLEncoding.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ B3ED20DEF712481D94438616 /* SocialSharing.m */ = {isa = PBXFileReference; name = "SocialSharing.m"; path = "cordova-plugin-x-socialsharing/SocialSharing.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ 16D856FDFCB74CA28463BBDD /* NSString+SSURLEncoding.h */ = {isa = PBXFileReference; name = "NSString+SSURLEncoding.h"; path = "cordova-plugin-x-socialsharing/NSString+SSURLEncoding.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ A74406C0855A4EB68DD2005B /* SocialSharing.h */ = {isa = PBXFileReference; name = "SocialSharing.h"; path = "cordova-plugin-x-socialsharing/SocialSharing.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ E7E61147BE1945D5A406B430 /* Social.framework */ = {isa = PBXFileReference; name = "Social.framework"; path = "System/Library/Frameworks/Social.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };+ 374D90B51F7945D892F3EF98 /* MessageUI.framework */ = {isa = PBXFileReference; name = "MessageUI.framework"; path = "System/Library/Frameworks/MessageUI.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };+ 20B409CCA31946F6A58ECC19 /* CDVWKWebViewFileXhr.m */ = {isa = PBXFileReference; name = "CDVWKWebViewFileXhr.m"; path = "cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.m"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; explicitFileType = undefined; includeInIndex = 0; };+ E9C631D5858F46CE9E086CB1 /* CDVWKWebViewFileXhr.h */ = {isa = PBXFileReference; name = "CDVWKWebViewFileXhr.h"; path = "cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.h"; sourceTree = "<group>"; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; explicitFileType = undefined; includeInIndex = 0; };+ 0A5FDD2F614B465AB09E339E /* WebKit.framework */ = {isa = PBXFileReference; name = "WebKit.framework"; path = "System/Library/Frameworks/WebKit.framework"; sourceTree = SDKROOT; fileEncoding = undefined; lastKnownFileType = wrapper.framework; explicitFileType = undefined; includeInIndex = 0; };/* End PBXFileReference section *//* Begin PBXFrameworksBuildPhase section */@@ -119,10 +125,12 @@buildActionMask = 2147483647;files = (301BF552109A68D80062928A /* libCordova.a in Frameworks */,- 3419DFF8E26C40049D27FEF9 /* ImageIO.framework in Frameworks */,- 68EEB8A986134A178EACDC51 /* CoreLocation.framework in Frameworks */,- 53F98373E0254B50ADFC7482 /* AVFoundation.framework in Frameworks */,- 8EA0B645CECC433081B8E848 /* WebKit.framework in Frameworks */,+ 41C0872421BD4657B31F7C60 /* ImageIO.framework in Frameworks */,+ 4ED540FB26504C7EBC5F2310 /* CoreLocation.framework in Frameworks */,+ 4C912013458B4E34A6BEBFDF /* AVFoundation.framework in Frameworks */,+ A452553E07F64C0CAA35D96C /* Social.framework in Frameworks */,+ 64DF0AC9557C494C80C9B7B4 /* MessageUI.framework in Frameworks */,+ 2C8E5B76AA29404A99E9CACD /* WebKit.framework in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};@@ -185,7 +193,7 @@3047A50E1AB8057F00498E2A /* config */,8D1107310486CEB800E47090 /* TagSpaces Beta-Info.plist */,6AFF5BF81D6E424B00AB3073 /* CDVLaunchScreen.storyboard */,- 101925A545E94A63B15DB828 /* appbeep.wav */,+ 856852A9946B4DA7BF4EDC62 /* appbeep.wav */,);name = Resources;path = "TagSpaces Beta/Resources";@@ -194,10 +202,12 @@29B97323FDCFA39411CA2CEA /* Frameworks */ = {isa = PBXGroup;children = (- 40A26423D0AF4AE598297D25 /* ImageIO.framework */,- 0C212A0B05B3406590A5DE1A /* CoreLocation.framework */,- 720D38A8FC114FB9860E24F1 /* AVFoundation.framework */,- 1785AEC413494EC89B548B1E /* WebKit.framework */,+ E73A2C7396C94680B1CFF239 /* ImageIO.framework */,+ 3A8061B9E2584C6F9BFA435B /* CoreLocation.framework */,+ 92C5D5470BCB43B191A3755E /* AVFoundation.framework */,+ E7E61147BE1945D5A406B430 /* Social.framework */,+ 374D90B51F7945D892F3EF98 /* MessageUI.framework */,+ 0A5FDD2F614B465AB09E339E /* WebKit.framework */,);name = Frameworks;sourceTree = "<group>";@@ -224,33 +234,34 @@307C750510C5A3420062BCA9 /* Plugins */ = {isa = PBXGroup;children = (- 3D4B8429E3AA4CCABA3483C2 /* CDVDevice.m */,- B1E38A50DE384D2BB20890EB /* CDVDevice.h */,- 4A95936F2A674A518C47DC9D /* APPBackgroundMode.m */,- D68F7DFBF1BD4A08A2CA9BB5 /* APPMethodMagic.m */,- F0F164CAE6E346428F43D0C9 /* APPBackgroundMode.h */,- 450308C53A3E4D278EC4286B /* APPMethodMagic.h */,- 49D060970246496597C22CAD /* UIImage+CropScaleOrientation.m */,- 93FC43CFD33C4C9B89754A11 /* CDVCamera.m */,- 1EC446528AF448AB9C17958C /* CDVJpegHeaderWriter.m */,- 7FD56FBDFA8B4E0A906A97B0 /* UIImage+CropScaleOrientation.h */,- 3F8642D53B1A40708D0784D1 /* CDVCamera.h */,- FDB5379162244D3F92106617 /* CDVJpegHeaderWriter.h */,- 00BBD8B96CA64BC19D7F67BE /* CDVExif.h */,- B8464A38DD2D4F7FADA4A05D /* CDVFile.m */,- 476A44F1A9C44535A0A00615 /* CDVLocalFilesystem.m */,- 0B70DBAD7A3346F4A04BEB0D /* CDVAssetLibraryFilesystem.m */,- FFEEE9F8C3654B1D80D32A88 /* CDVFile.h */,- BBE6D0DB8D0C48C3A48B5D6A /* CDVLocalFilesystem.h */,- F69E9D0C17334829B9EA3A3F /* CDVAssetLibraryFilesystem.h */,- 4B5AE9F692F74481BC1E0C86 /* FileOpener2.m */,- 032B343EF5F94282A58A7531 /* FileOpener2.h */,- 1BAE8F2712124FE9A9CA0C3F /* CDVWKWebViewEngine.m */,- 1FE0EEB88E3548539E8DB7BF /* CDVWKWebViewUIDelegate.m */,- B559D10CCDB7435DB450FCE8 /* CDVWKProcessPoolFactory.m */,- 4E41725864554075A3FC52DE /* CDVWKWebViewEngine.h */,- E777FC5C974D4356A3FD36CD /* CDVWKWebViewUIDelegate.h */,- 52525C431A294171B3CC274C /* CDVWKProcessPoolFactory.h */,+ A0CD0395A4C34F10BAAB0237 /* CDVDevice.m */,+ 943EE43957C44D10AE8DF7E2 /* CDVDevice.h */,+ 671C10DB25DA4F2AA5974527 /* APPBackgroundMode.m */,+ A242041FBB71452BA3630292 /* APPMethodMagic.m */,+ 5F5B13AA0E7A45928786E136 /* APPBackgroundMode.h */,+ 43DBA31C36DC40A29CDE164C /* APPMethodMagic.h */,+ 834C76EB13ED4B4D9F0E6F5C /* UIImage+CropScaleOrientation.m */,+ 27B78C661E5A48FE99AB7230 /* CDVCamera.m */,+ 4923C134A48F48CF8E8EC47F /* CDVJpegHeaderWriter.m */,+ 6B1891CB1153452DB5F33F33 /* UIImage+CropScaleOrientation.h */,+ D0D35D8448024980B5C3FC47 /* CDVCamera.h */,+ FE4894ACD2AC49A5B929D1D4 /* CDVJpegHeaderWriter.h */,+ 9D58C635D56F4E4FA8361ABD /* CDVExif.h */,+ 2D9B854200814AE3A9C2E770 /* CDVFile.m */,+ 98D2D7F7AB794421990E8FC5 /* CDVLocalFilesystem.m */,+ 37F82A6CC29C4503B5AB6765 /* CDVAssetLibraryFilesystem.m */,+ 5CBE442109A44548BFA1204B /* CDVFile.h */,+ BB314C1742724790963463E2 /* CDVLocalFilesystem.h */,+ 21B8ADFA4658428FBB1F7958 /* CDVAssetLibraryFilesystem.h */,+ 38DE4A52BF3A428CB85A01D3 /* FileOpener2.m */,+ 25E8D9BCF59A432CB579644E /* FileOpener2.h */,+ 9963CE05D2C745349F080238 /* Downloader.swift */,+ 91D46E5FC6B44B8796CD0432 /* NSString+SSURLEncoding.m */,+ B3ED20DEF712481D94438616 /* SocialSharing.m */,+ 16D856FDFCB74CA28463BBDD /* NSString+SSURLEncoding.h */,+ A74406C0855A4EB68DD2005B /* SocialSharing.h */,+ 20B409CCA31946F6A58ECC19 /* CDVWKWebViewFileXhr.m */,+ E9C631D5858F46CE9E086CB1 /* CDVWKWebViewFileXhr.h */,);name = Plugins;path = "TagSpaces Beta/Plugins";@@ -293,20 +304,19 @@29B97313FDCFA39411CA2CEA /* Project object */ = {isa = PBXProject;attributes = {- LastUpgradeCheck = 510;+ LastUpgradeCheck = 1130;TargetAttributes = {1D6058900D05DD3D006BFB54 = {- DevelopmentTeam = DLK22E2679;+ LastSwiftMigration = 1160;ProvisioningStyle = Automatic;};};};buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "TagSpaces Beta" */;- compatibilityVersion = "Xcode 3.2";- developmentRegion = English;+ compatibilityVersion = "Xcode 11.0";+ developmentRegion = en;hasScannedForEncodings = 1;knownRegions = (- English,en,Base,);@@ -350,7 +360,7 @@302D95F214D2391D003F00A1 /* MainViewController.xib in Resources */,0207DA581B56EA530066E2B4 /* Images.xcassets in Resources */,6AFF5BF91D6E424B00AB3073 /* CDVLaunchScreen.storyboard in Resources */,- 721F0E8CD32D41C399A0407B /* appbeep.wav in Resources */,+ 2ECBCFEFA8A14C0EB682FAB0 /* appbeep.wav in Resources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -382,19 +392,20 @@1D60589B0D05DD56006BFB54 /* main.m in Sources */,1D3623260D0F684500981E51 /* AppDelegate.m in Sources */,302D95F114D2391D003F00A1 /* MainViewController.m in Sources */,- FD08D10174C049C9B2AF1045 /* CDVDevice.m in Sources */,- 55E6C374E3FD4A4CABBDF7A2 /* APPBackgroundMode.m in Sources */,- D542412872474BA08645A2B6 /* APPMethodMagic.m in Sources */,- 5330031C98004A548A04FB04 /* UIImage+CropScaleOrientation.m in Sources */,- CDBEA11FAD00489CAAD7BCB3 /* CDVCamera.m in Sources */,- 44ACB9D58C8147E2AECFD8E3 /* CDVJpegHeaderWriter.m in Sources */,- 16B2D55C46694FAB859B04D1 /* CDVFile.m in Sources */,- 93C68FEC56FE482C8A4A2E86 /* CDVLocalFilesystem.m in Sources */,- ED2346D5DC534F0E8A5C4B72 /* CDVAssetLibraryFilesystem.m in Sources */,- 9160B31B3A944071B00DBEAA /* FileOpener2.m in Sources */,- FD813F4BF3564D7286CEC694 /* CDVWKWebViewEngine.m in Sources */,- FC3FD5B10EE249F8BCAE2897 /* CDVWKWebViewUIDelegate.m in Sources */,- F0EF40AA3831439690728A0F /* CDVWKProcessPoolFactory.m in Sources */,+ 98F6A5526062497CB73A1B0A /* CDVDevice.m in Sources */,+ DA515680F8F14C71B59F498F /* APPBackgroundMode.m in Sources */,+ F0E7F6EF3B734A7094F48E3F /* APPMethodMagic.m in Sources */,+ 90B55385075445E8AFF6E723 /* UIImage+CropScaleOrientation.m in Sources */,+ DA68256931E643F9A3BF0909 /* CDVCamera.m in Sources */,+ 3912058EB13E485BB506E071 /* CDVJpegHeaderWriter.m in Sources */,+ 7C6065AB08F9429A8C4E974C /* CDVFile.m in Sources */,+ 71C228DE9D4F41FF8AFBC4F6 /* CDVLocalFilesystem.m in Sources */,+ DCC01C38133C46BBA9BFE8C6 /* CDVAssetLibraryFilesystem.m in Sources */,+ 6A47B1C2D9D5498C92FD79A4 /* FileOpener2.m in Sources */,+ 78B9CD3FBED74924A25196E2 /* Downloader.swift in Sources */,+ 11837AAE46E24B8DA394DF19 /* NSString+SSURLEncoding.m in Sources */,+ 4451916358BD49A8A7644D56 /* SocialSharing.m in Sources */,+ EE38F8704D0B42B7A525EF73 /* CDVWKWebViewFileXhr.m in Sources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -415,11 +426,9 @@buildSettings = {ALWAYS_SEARCH_USER_PATHS = NO;ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;CLANG_ENABLE_MODULES = YES;CLANG_ENABLE_OBJC_ARC = YES;COPY_PHASE_STRIP = NO;- DEVELOPMENT_TEAM = DLK22E2679;GCC_DYNAMIC_NO_PIC = NO;GCC_OPTIMIZATION_LEVEL = 0;GCC_PRECOMPILE_PREFIX_HEADER = YES;@@ -427,12 +436,12 @@GCC_THUMB_SUPPORT = NO;GCC_VERSION = "";INFOPLIST_FILE = "TagSpaces Beta/TagSpaces Beta-Info.plist";- IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ IPHONEOS_DEPLOYMENT_TARGET = 11.0;LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";- PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.iosn;+ PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";- WK_WEB_VIEW_ONLY = 1;};name = Debug;};@@ -442,7 +451,6 @@buildSettings = {ALWAYS_SEARCH_USER_PATHS = NO;ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;CLANG_ENABLE_MODULES = YES;CLANG_ENABLE_OBJC_ARC = YES;COPY_PHASE_STRIP = YES;@@ -451,12 +459,12 @@GCC_THUMB_SUPPORT = NO;GCC_VERSION = "";INFOPLIST_FILE = "TagSpaces Beta/TagSpaces Beta-Info.plist";- IPHONEOS_DEPLOYMENT_TARGET = 10.0;+ IPHONEOS_DEPLOYMENT_TARGET = 11.0;LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";- WK_WEB_VIEW_ONLY = 1;};name = Release;};@@ -464,6 +472,7 @@isa = XCBuildConfiguration;baseConfigurationReference = 3047A5111AB8059700498E2A /* build.xcconfig */;buildSettings = {+ CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;CLANG_ENABLE_MODULES = YES;CLANG_ENABLE_OBJC_ARC = YES;CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;@@ -496,10 +505,11 @@GCC_WARN_UNUSED_FUNCTION = YES;GCC_WARN_UNUSED_VARIABLE = YES;ONLY_ACTIVE_ARCH = YES;- PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;SDKROOT = iphoneos;SKIP_INSTALL = NO;+ SWIFT_VERSION = 4.0;WK_WEB_VIEW_ONLY = 1;+ IPHONEOS_DEPLOYMENT_TARGET = 11.0;};name = Debug;};@@ -507,6 +517,7 @@isa = XCBuildConfiguration;baseConfigurationReference = 3047A5111AB8059700498E2A /* build.xcconfig */;buildSettings = {+ CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;CLANG_ENABLE_MODULES = YES;CLANG_ENABLE_OBJC_ARC = YES;CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;@@ -537,10 +548,11 @@GCC_WARN_UNINITIALIZED_AUTOS = YES;GCC_WARN_UNUSED_FUNCTION = YES;GCC_WARN_UNUSED_VARIABLE = YES;- PRODUCT_BUNDLE_IDENTIFIER = org.tagspaces.mobile;SDKROOT = iphoneos;SKIP_INSTALL = NO;+ SWIFT_VERSION = 4.0;WK_WEB_VIEW_ONLY = 1;+ IPHONEOS_DEPLOYMENT_TARGET = 11.0;};name = Release;};diff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/xcschemes/TagSpaces Beta.xcscheme b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/xcschemes/TagSpaces Beta.xcschemeindex ea8c0e532..7ae666f35 100644--- a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/xcschemes/TagSpaces Beta.xcscheme+++ b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcshareddata/xcschemes/TagSpaces Beta.xcscheme@@ -27,6 +27,8 @@selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"shouldUseLaunchSchemeArgsEnv = "YES">+ <Testables>+ </Testables><MacroExpansion><BuildableReferenceBuildableIdentifier = "primary"@@ -36,8 +38,8 @@ReferencedContainer = "container:TagSpaces Beta.xcodeproj"></BuildableReference></MacroExpansion>- <Testables>- </Testables>+ <AdditionalOptions>+ </AdditionalOptions></TestAction><LaunchActionbuildConfiguration = "Debug"@@ -59,6 +61,8 @@ReferencedContainer = "container:TagSpaces Beta.xcodeproj"></BuildableReference></BuildableProductRunnable>+ <AdditionalOptions>+ </AdditionalOptions></LaunchAction><ProfileActionbuildConfiguration = "Release"@@ -81,7 +85,7 @@buildConfiguration = "Debug"></AnalyzeAction><ArchiveAction- buildConfiguration = "Debug"+ buildConfiguration = "Release"revealArchiveInOrganizer = "YES"></ArchiveAction></Scheme>diff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/UserInterfaceState.xcuserstate b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/UserInterfaceState.xcuserstateindex 52b072422..b8fec3dc1 100644Binary files a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/UserInterfaceState.xcuserstate and b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/UserInterfaceState.xcuserstate differdiff --git a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plistindex ebb89c9a7..06a18638c 100644--- a/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist+++ b/cordova/platforms/ios/TagSpaces Beta.xcworkspace/xcuserdata/sytolk.xcuserdatad/xcschemes/xcschememanagement.plist@@ -6,8 +6,6 @@<dict><key>TagSpaces Beta.xcscheme_^#shared#^_</key><dict>- <key>isShown</key>- <true/><key>orderHint</key><integer>0</integer></dict>diff --git a/cordova/platforms/ios/TagSpaces Beta/CDVLaunchScreen.storyboard b/cordova/platforms/ios/TagSpaces Beta/CDVLaunchScreen.storyboardindex ffc1d1d65..924392e34 100644--- a/cordova/platforms/ios/TagSpaces Beta/CDVLaunchScreen.storyboard+++ b/cordova/platforms/ios/TagSpaces Beta/CDVLaunchScreen.storyboard@@ -1,4 +1,4 @@-<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<?xml version="1.0" encoding="UTF-8"?><!--Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -17,11 +17,13 @@specific language governing permissions and limitationsunder the License.-->-<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G1004" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15705" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">+ <device id="retina6_1" orientation="portrait" appearance="light"/><dependencies><deployment identifier="iOS"/>- <development version="6100" identifier="xcode"/>- <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15706"/>+ <capability name="Named colors" minToolsVersion="9.0"/>+ <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/></dependencies><scenes><!--View Controller-->@@ -33,14 +35,14 @@<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/></layoutGuides><view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">- <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>+ <rect key="frame" x="0.0" y="0.0" width="414" height="896"/><autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/><subviews><imageView userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchStoryboard" translatesAutoresizingMaskIntoConstraints="NO" id="2ns-9I-Qjs">- <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>+ <rect key="frame" x="0.0" y="0.0" width="414" height="896"/></imageView></subviews>- <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>+ <color key="backgroundColor" name="BackgroundColor"/><constraints><constraint firstAttribute="trailing" secondItem="2ns-9I-Qjs" secondAttribute="trailing" id="FZL-3Z-NFz"/><constraint firstItem="2ns-9I-Qjs" firstAttribute="bottom" secondItem="Ze5-6b-2t3" secondAttribute="bottom" id="L9l-pw-wXj"/>@@ -56,5 +58,8 @@</scenes><resources><image name="LaunchStoryboard" width="1366" height="1366"/>+ <namedColor name="BackgroundColor">+ <color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>+ </namedColor></resources></document>diff --git a/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.m b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.mindex 633d184f6..2d6ddd7c7 100644--- a/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.m+++ b/cordova/platforms/ios/TagSpaces Beta/Classes/MainViewController.m@@ -77,42 +77,6 @@// Do any additional setup after loading the view from its nib.}-- (void)viewDidUnload-{- [super viewDidUnload];- // Release any retained subviews of the main view.- // e.g. self.myOutlet = nil;-}--/* Comment out the block below to over-ride */--/*-- (UIWebView*) newCordovaViewWithFrame:(CGRect)bounds-{- return[super newCordovaViewWithFrame:bounds];-}--// CB-12098-#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000-- (NSUInteger)supportedInterfaceOrientations-#else-- (UIInterfaceOrientationMask)supportedInterfaceOrientations-#endif-{- return [super supportedInterfaceOrientations];-}--- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation-{- return [super shouldAutorotateToInterfaceOrientation:interfaceOrientation];-}--- (BOOL)shouldAutorotate-{- return [super shouldAutorotate];-}-*/-@end@implementation MainCommandDelegatediff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/BackgroundColor.colorset/Contents.json b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/BackgroundColor.colorset/Contents.jsonnew file mode 100644index 000000000..38ce5e7c7--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/BackgroundColor.colorset/Contents.json@@ -0,0 +1,15 @@+{+ "colors": [+ {+ "idiom": "universal",+ "color": {+ "platform": "ios",+ "reference": "systemBackgroundColor"+ }+ }+ ],+ "info": {+ "author": "Xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Contents.json b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Contents.jsondeleted file mode 100644index 58735deb7..000000000--- a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Contents.json+++ /dev/null@@ -1,176 +0,0 @@-{- "images" : [- {- "extent": "full-screen",- "idiom": "iphone",- "subtype": "2436h",- "filename": "Default-2436h.png",- "minimum-system-version": "11.0",- "orientation": "portrait",- "scale": "3x"- },- {- "extent": "full-screen",- "idiom": "iphone",- "subtype": "2436h",- "filename": "Default-Landscape-2436h.png",- "minimum-system-version": "11.0",- "orientation": "landscape",- "scale": "3x"- },- {- "extent" : "full-screen",- "idiom" : "iphone",- "subtype" : "736h",- "filename" : "Default-736h.png",- "minimum-system-version" : "8.0",- "orientation" : "portrait",- "scale" : "3x"- },- {- "extent" : "full-screen",- "idiom" : "iphone",- "subtype" : "736h",- "filename" : "Default-Landscape-736h.png",- "minimum-system-version" : "8.0",- "orientation" : "landscape",- "scale" : "3x"- },- {- "extent" : "full-screen",- "idiom" : "iphone",- "subtype" : "667h",- "filename" : "Default-667h.png",- "minimum-system-version" : "8.0",- "orientation" : "portrait",- "scale" : "2x"- },- {- "orientation" : "portrait",- "idiom" : "iphone",- "filename" : "Default@2x~iphone.png",- "extent" : "full-screen",- "minimum-system-version" : "7.0",- "scale" : "2x"- },- {- "extent" : "full-screen",- "idiom" : "iphone",- "subtype" : "retina4",- "filename" : "Default-568h@2x~iphone.png",- "minimum-system-version" : "7.0",- "orientation" : "portrait",- "scale" : "2x"- },- {- "orientation" : "portrait",- "idiom" : "ipad",- "filename" : "Default-Portrait~ipad.png",- "extent" : "full-screen",- "minimum-system-version" : "7.0",- "scale" : "1x"- },- {- "orientation" : "landscape",- "idiom" : "ipad",- "filename" : "Default-Landscape~ipad.png",- "extent" : "full-screen",- "minimum-system-version" : "7.0",- "scale" : "1x"- },- {- "orientation" : "portrait",- "idiom" : "ipad",- "filename" : "Default-Portrait@2x~ipad.png",- "extent" : "full-screen",- "minimum-system-version" : "7.0",- "scale" : "2x"- },- {- "orientation" : "landscape",- "idiom" : "ipad",- "filename" : "Default-Landscape@2x~ipad.png",- "extent" : "full-screen",- "minimum-system-version" : "7.0",- "scale" : "2x"- },- {- "orientation" : "portrait",- "idiom" : "iphone",- "filename" : "Default~iphone.png",- "extent" : "full-screen",- "scale" : "1x"- },- {- "orientation" : "portrait",- "idiom" : "iphone",- "filename" : "Default@2x~iphone.png",- "extent" : "full-screen",- "scale" : "2x"- },- {- "orientation" : "portrait",- "idiom" : "iphone",- "filename" : "Default-568h@2x~iphone.png",- "extent" : "full-screen",- "subtype" : "retina4",- "scale" : "2x"- },- {- "orientation" : "portrait",- "idiom" : "ipad",- "extent" : "to-status-bar",- "scale" : "1x"- },- {- "orientation" : "portrait",- "idiom" : "ipad",- "filename" : "Default-Portrait~ipad.png",- "extent" : "full-screen",- "scale" : "1x"- },- {- "orientation" : "landscape",- "idiom" : "ipad",- "extent" : "to-status-bar",- "scale" : "1x"- },- {- "orientation" : "landscape",- "idiom" : "ipad",- "filename": "Default-Landscape~ipad.png",- "extent" : "full-screen",- "scale" : "1x"- },- {- "orientation" : "portrait",- "idiom" : "ipad",- "extent" : "to-status-bar",- "scale" : "2x"- },- {- "orientation" : "portrait",- "idiom" : "ipad",- "filename" : "Default-Portrait@2x~ipad.png",- "extent" : "full-screen",- "scale" : "2x"- },- {- "orientation" : "landscape",- "idiom" : "ipad",- "extent" : "to-status-bar",- "scale" : "2x"- },- {- "orientation" : "landscape",- "idiom" : "ipad",- "filename": "Default-Landscape@2x~ipad.png",- "extent" : "full-screen",- "scale" : "2x"- }- ],- "info" : {- "version" : 1,- "author" : "xcode"- }-}diff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-2436h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-2436h.pngdeleted file mode 100644index b124dcf05..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-2436h.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-568h@2x~iphone.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-568h@2x~iphone.pngdeleted file mode 100644index f353b070f..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-568h@2x~iphone.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-667h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-667h.pngdeleted file mode 100644index d5f371857..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-667h.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-736h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-736h.pngdeleted file mode 100644index f70767a2c..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-736h.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-2436h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-2436h.pngdeleted file mode 100644index c062b2acc..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-2436h.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h.pngdeleted file mode 100644index 321ca2ea3..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape@2x~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape@2x~ipad.pngdeleted file mode 100644index 62b212ebc..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape@2x~ipad.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape~ipad.pngdeleted file mode 100644index 00169cbf3..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Landscape~ipad.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait@2x~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait@2x~ipad.pngdeleted file mode 100644index e4a8a1971..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait@2x~ipad.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait~ipad.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait~ipad.pngdeleted file mode 100644index d9597f4e3..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default-Portrait~ipad.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default@2x~iphone.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default@2x~iphone.pngdeleted file mode 100644index e01371585..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default@2x~iphone.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default~iphone.png b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default~iphone.pngdeleted file mode 100644index 0266273a2..000000000Binary files a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchImage.launchimage/Default~iphone.png and /dev/null differdiff --git a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchStoryboard.imageset/Contents.json b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchStoryboard.imageset/Contents.jsonindex 621019de2..c0ac4835b 100644--- a/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchStoryboard.imageset/Contents.json+++ b/cordova/platforms/ios/TagSpaces Beta/Images.xcassets/LaunchStoryboard.imageset/Contents.json@@ -6,159 +6,863 @@"width-class": "compact","height-class": "compact"},+ {+ "idiom": "universal",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "1x","width-class": "compact"},+ {+ "idiom": "universal",+ "scale": "1x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "1x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "1x","height-class": "compact"},+ {+ "idiom": "universal",+ "scale": "1x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "1x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "1x"},+ {+ "idiom": "universal",+ "scale": "1x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "1x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "2x","width-class": "compact","height-class": "compact"},+ {+ "idiom": "universal",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "2x","width-class": "compact"},+ {+ "idiom": "universal",+ "scale": "2x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "2x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "2x","height-class": "compact"},+ {+ "idiom": "universal",+ "scale": "2x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "2x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "2x"},+ {+ "idiom": "universal",+ "scale": "2x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "2x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "3x","width-class": "compact","height-class": "compact"},+ {+ "idiom": "universal",+ "scale": "3x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "3x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "3x","width-class": "compact"},+ {+ "idiom": "universal",+ "scale": "3x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "3x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "3x","height-class": "compact"},+ {+ "idiom": "universal",+ "scale": "3x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "3x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "universal","scale": "3x"},+ {+ "idiom": "universal",+ "scale": "3x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "universal",+ "scale": "3x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "1x","width-class": "compact","height-class": "compact"},+ {+ "idiom": "ipad",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "1x","width-class": "compact"},+ {+ "idiom": "ipad",+ "scale": "1x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "1x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "1x","height-class": "compact"},+ {+ "idiom": "ipad",+ "scale": "1x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "1x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "1x"},+ {+ "idiom": "ipad",+ "scale": "1x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "1x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "2x","width-class": "compact","height-class": "compact"},+ {+ "idiom": "ipad",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "2x","width-class": "compact"},+ {+ "idiom": "ipad",+ "scale": "2x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "2x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "2x","height-class": "compact"},+ {+ "idiom": "ipad",+ "scale": "2x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "2x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "ipad","scale": "2x"},+ {+ "idiom": "ipad",+ "scale": "2x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "ipad",+ "scale": "2x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "1x","width-class": "compact","height-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "1x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "1x","width-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "1x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "1x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "1x","height-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "1x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "1x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "1x"},+ {+ "idiom": "iphone",+ "scale": "1x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "1x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "2x","width-class": "compact","height-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "2x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "2x","width-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "2x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "2x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "2x","height-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "2x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "2x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "2x"},+ {+ "idiom": "iphone",+ "scale": "2x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "2x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "3x","width-class": "compact","height-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "3x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "width-class": "compact",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "3x","width-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "3x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "width-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "3x","height-class": "compact"},+ {+ "idiom": "iphone",+ "scale": "3x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "height-class": "compact",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]+ },{"idiom": "iphone","scale": "3x"+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ]+ },+ {+ "idiom": "iphone",+ "scale": "3x",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "light"+ }+ ]}],"info": {diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/com.whebcraft.cordova.plugin.downloader/Downloader.swift b/cordova/platforms/ios/TagSpaces Beta/Plugins/com.whebcraft.cordova.plugin.downloader/Downloader.swiftnew file mode 100644index 000000000..3e30eda66--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/com.whebcraft.cordova.plugin.downloader/Downloader.swift@@ -0,0 +1,64 @@+import Foundation++@objc(Downloader) class Downloader : CDVPlugin {+ func download(_ command: CDVInvokedUrlCommand) {+ var pluginResult = CDVPluginResult(+ status: CDVCommandStatus_ERROR+ )++ var isError = false++ let args = command.arguments[0] as! NSDictionary+ let url = URL(string: args["url"] as! String)+ let targetFile = args["path"] as! String++ let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?+ let destinationUrl = documentsUrl?.appendingPathComponent(targetFile)++ if FileManager().fileExists(atPath: destinationUrl!.path) {+ print("file already exists [\(destinationUrl?.path)]")+ do {+ try FileManager().removeItem(atPath: destinationUrl!.path)+ }+ catch let error as NSError {+ pluginResult = CDVPluginResult(+ status: CDVCommandStatus_ERROR,+ messageAs: error.localizedDescription+ )++ self.commandDelegate!.send(+ pluginResult,+ callbackId: command.callbackId+ )++ isError = true+ }+ }+ if !(isError) {+ let sessionConfig = URLSessionConfiguration.default+ let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)+ var request = URLRequest(url: url!)+ request.httpMethod = "GET"+ let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in+ if (error == nil) {+ if let response = response as? HTTPURLResponse {+ if response.statusCode == 200 {+ if (try? data!.write(to: destinationUrl!, options: [.atomic])) != nil {+ pluginResult = CDVPluginResult(+ status: CDVCommandStatus_OK,+ messageAs: documentsUrl?.path+ )++ self.commandDelegate!.send(+ pluginResult,+ callbackId: command.callbackId+ )+ }+ }+ }+ }+ })+ task.resume()+ }+ }+}diff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.hnew file mode 100644index 000000000..0a729e6e5--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.h@@ -0,0 +1,57 @@+/*+ * Copyright (c) 2016, 2017 Oracle and/or its affiliates.+ *+ * The Universal Permissive License (UPL), Version 1.0+ *+ * Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this+ * software, associated documentation and/or data (collectively the "Software"), free of charge and under any and+ * all copyright rights in the Software, and any and all patent rights owned or freely licensable by each+ * licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor,+ * or (ii) the Larger Works (as defined below), to deal in both+ *+ *+ * (a) the Software, and+ *+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software+ * (each a “Larger Work” to which the Software is contributed by such licensors),+ *+ * without restriction, including without limitation the rights to copy, create derivative works of, display,+ * perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and+ * have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other+ * terms.+ *+ * This license is subject to the following condition:+ *+ * The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL+ * must be included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ * DEALINGS IN THE SOFTWARE.+ */++#import <Foundation/Foundation.h>+#import <Cordova/CDVPlugin.h>+#import <WebKit/WebKit.h>++NS_ASSUME_NONNULL_BEGIN++@interface CDVWKWebViewFileXhr : CDVPlugin<WKScriptMessageHandler, NSURLSessionDelegate>++/* Exec API */+- (void)readAsText:(CDVInvokedUrlCommand*)command;+- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command;+- (void) getConfig:(CDVInvokedUrlCommand*)command;++@property (nonatomic, assign) BOOL allowsInsecureLoads;+@property (nonatomic, strong) NSString * interceptRemoteRequests;+//added+@property (nonatomic, assign) BOOL allowFileAccessFromFileURLs;+@property (nonatomic, assign) BOOL allowUniversalAccessFromFileURLs;+++@end++NS_ASSUME_NONNULL_ENDdiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.mnew file mode 100644index 000000000..bbfea8ad6--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-ios-xhr/CDVWKWebViewFileXhr.m@@ -0,0 +1,443 @@+/*+ * Copyright (c) 2016, 2017 Oracle and/or its affiliates.+ *+ * The Universal Permissive License (UPL), Version 1.0+ *+ * Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this+ * software, associated documentation and/or data (collectively the "Software"), free of charge and under any and+ * all copyright rights in the Software, and any and all patent rights owned or freely licensable by each+ * licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor,+ * or (ii) the Larger Works (as defined below), to deal in both+ *+ *+ * (a) the Software, and+ *+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software+ * (each a “Larger Work” to which the Software is contributed by such licensors),+ *+ * without restriction, including without limitation the rights to copy, create derivative works of, display,+ * perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and+ * have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other+ * terms.+ *+ * This license is subject to the following condition:+ *+ * The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL+ * must be included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ * DEALINGS IN THE SOFTWARE.+ */++#import "CDVWKWebViewFileXhr.h"+#import <Cordova/CDV.h>++NS_ASSUME_NONNULL_BEGIN+++@implementation NSDictionary(CDVWKWebViewFileXhr)++/**+ Convenience method to return a NSString from a dictionary++ @param key The key to return+ @return The value as a String, or nil+ */+- (nullable NSString *) cdvwkStringForKey:(NSString *)key+{+ NSObject* val = self[key];+ if (val == nil)+ return nil;+ if ([val isKindOfClass:NSString.class])+ return (NSString *)val;+ return [NSString stringWithFormat:@"%@",val];+}+@end++@interface CDVWKWebViewFileXhr()++@property (nonatomic, retain) NSURLSession *urlSession;+@property (nonatomic, retain) NSString *nativeXHRLogging;++@end++++@implementation CDVWKWebViewFileXhr++-(void) pluginInitialize {+ [super pluginInitialize];++ if (![self.webView isKindOfClass:WKWebView.class])+ return;++ WKWebView *wkWebView = (WKWebView *) self.webView;++ // added : allowFileAccessFromFileURLs allowUniversalAccessFromFileURLs+ NSString *value = [self.commandDelegate.settings cdvwkStringForKey:@"allowfileaccessfromfileurls"];++ if (value != nil && [value isEqualToString:@"true"]){+ _allowFileAccessFromFileURLs = YES;+ NSLog(@"WARNING: File access allowed due to preference allowFileAccessFromFileURLs=true");+ }else{+ _allowFileAccessFromFileURLs = NO;+ }+ [wkWebView.configuration.preferences setValue:@(_allowFileAccessFromFileURLs) forKey:@"allowFileAccessFromFileURLs"];++ value = [self.commandDelegate.settings cdvwkStringForKey:@"allowuniversalaccessfromfileurls"];+ if (value != nil && [value isEqualToString:@"true"]){+ _allowUniversalAccessFromFileURLs = YES;+ NSLog(@"WARNING: Universal access allowed due to preference allowUniversalAccessFromFileURLs=true");+ }else{+ _allowUniversalAccessFromFileURLs = NO;+ }+ [wkWebView.configuration setValue:@(_allowUniversalAccessFromFileURLs) forKey:@"allowUniversalAccessFromFileURLs"];++ // note: settings translates all preferences to lower case+ value = [self.commandDelegate.settings cdvwkStringForKey:@"allowuntrustedcerts"];+ if (value != nil && [value compare:@"on" options:NSCaseInsensitiveSearch] == NSOrderedSame) {+ _allowsInsecureLoads = YES;+ NSLog(@"WARNING: NativeXHR is allowing untrusted certificates due to preference AllowUntrustedCerts=on");+ }++ value = [self.commandDelegate.settings cdvwkStringForKey:@"interceptremoterequests"];+ if (value != nil &&+ ([value compare:@"all" options:NSCaseInsensitiveSearch] == NSOrderedSame ||+ [value compare:@"secureOnly" options:NSCaseInsensitiveSearch] == NSOrderedSame ||+ [value compare:@"none" options:NSCaseInsensitiveSearch] == NSOrderedSame)) {+ _interceptRemoteRequests = value;+ } else {+ _interceptRemoteRequests = @"secureOnly";+ }++ value = [self.commandDelegate.settings cdvwkStringForKey:@"nativexhrlogging"];+ if (value != nil &&+ ([value compare:@"none" options:NSCaseInsensitiveSearch] == NSOrderedSame ||+ [value compare:@"full" options:NSCaseInsensitiveSearch] == NSOrderedSame)) {+ _nativeXHRLogging = value;+ } else {+ _nativeXHRLogging = @"none";+ }+++ if ([_interceptRemoteRequests compare:@"all" options:NSCaseInsensitiveSearch] == NSOrderedSame ||+ [_interceptRemoteRequests compare:@"secureOnly" options:NSCaseInsensitiveSearch] == NSOrderedSame) {++ NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];+ [sessionConfiguration setRequestCachePolicy:NSURLRequestReloadIgnoringCacheData];+ self.urlSession = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; // FortityFalsePositive+ [wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"nativeXHR"];++ }+}++- (void) dispose {++ if ([self.webView isKindOfClass:WKWebView.class]) {++ WKWebView *wkWebView = (WKWebView *) self.webView;+ [wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"nativeXHR"];+ }+ [super dispose];++}+/*!+ * @param uri target relative file from the XMLHttpRequest polyfill+ * @return URL relative to the main bundle's www folder if no file:// prefix is provided. Otherwise the file url is used as is to support /Library paths+ */+-(NSURL*)getWebContentResourceURL: (NSString*) uri+{+ NSURL *targetURL = nil;++ if ([uri hasPrefix: @"file://"] || [uri hasPrefix: @"FILE://"])+ {+ targetURL = [NSURL URLWithString:uri];+ }+ else+ {+ NSURL *baseURL = [[NSBundle mainBundle] resourceURL];+ NSString *wwwuri = [NSString stringWithFormat:@"www/%@", uri];+ targetURL = [NSURL URLWithString:wwwuri relativeToURL:baseURL];+ }++ return targetURL;+}++/*!+ * @discussion Verifying the standardized path of the target URL is under the www+ * folder of the main bundle or under the application /Library folder+ *+ * @param targetURL target file under either the www folder of the main bundle or under the application /Library folder+ * @return true if the targetURL is within the www folder in the main bundle or under the application /Library folder+ */+-(BOOL)isWebContentResourceSecure: (NSURL*) targetURL+{+ NSURL *baseURL = [NSURL URLWithString:@"www" relativeToURL:[[NSBundle mainBundle] resourceURL]];+ NSString *basePath = [baseURL absoluteString];+ NSString *targetPath = [[targetURL standardizedURL] absoluteString];++ return [targetPath hasPrefix:basePath] ||+ [targetPath hasPrefix:[[NSURL fileURLWithPath:+ [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]] absoluteString]];+}++/*!+ * @discussion Cordova API command impl that reads and return file data as a javascript string+ * @param command NSArray* arguments[0] - NSString* uri+ */+- (void)readAsText:(CDVInvokedUrlCommand*)command+{+ NSString *uri = [command.arguments.firstObject isKindOfClass: NSString.class] ? command.arguments.firstObject : nil;+ if (uri.length == 0) {+ // this catches nil value or empty string+ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:404] callbackId:command.callbackId];+ return;+ }++ NSURL *targetURL = [self getWebContentResourceURL:uri];++ if (![self isWebContentResourceSecure:targetURL]) {++ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION messageAsInt:404];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];++ } else {++ __weak CDVWKWebViewFileXhr* weakSelf = self;+ [self.commandDelegate runInBackground:^ {++ NSData* data = [[NSData alloc] initWithContentsOfURL:targetURL];+ CDVPluginResult* result = nil;++ if (data != nil) {+ NSString* str = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSUTF8StringEncoding freeWhenDone:NO];++ // Check that UTF8 conversion did not fail.+ if (str != nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:str];+ result.associatedObject = data;+ }+ }++ if (result == nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:404];+ }++ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+ }+}++/*!+ * @discussion Cordova API command impl that reads and return file data as a javascript arraybuffer+ * @param command NSArray* arguments[0] - NSString* uri+ */+- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command+{+ NSString *uri = [command.arguments.firstObject isKindOfClass: NSString.class] ? command.arguments.firstObject : nil;+ if (uri.length == 0) {+ // this catches nil value or empty string+ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:404] callbackId:command.callbackId];+ return;+ }+ NSURL *targetURL = [self getWebContentResourceURL:uri];++ if (![self isWebContentResourceSecure:targetURL]) {++ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION messageAsInt:404];+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];++ } else {++ __weak CDVWKWebViewFileXhr* weakSelf = self;+ [self.commandDelegate runInBackground:^ {++ NSData* data = [[NSData alloc] initWithContentsOfURL:targetURL];++ CDVPluginResult* result = nil;+ if (data != nil) {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArrayBuffer:data];+ } else {+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:404];+ }++ [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];+ }];+ }+}++- (void)getConfig:(CDVInvokedUrlCommand*)command {++ NSDictionary *dict = @{+ @"InterceptRemoteRequests" : _interceptRemoteRequests,+ @"NativeXHRLogging" : _nativeXHRLogging+ };++ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dict] callbackId:command.callbackId];+}+++- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge+ completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {++ if (_allowsInsecureLoads) {+ SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;+ if (serverTrust) {+ CFDataRef exceptions = SecTrustCopyExceptions (serverTrust);+ SecTrustSetExceptions (serverTrust, exceptions);+ CFRelease (exceptions);+ completionHandler (NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:serverTrust]); // FortityFalsePositive++ return;+ }+ }+ completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);+}+++// MARK: - WKScriptMessageHandler++/**+ * Performs an asynchronous network load of the requested resource using native networking routines.+ *+ * The request is described in the body parameter as a dictionary. The supported keys are outlined below+ *+ * Name | Kind | Required | Description | Allowed Values+ * --- | --- | --- | --- | ---+ * id | string | true | A unique id used for callbacks | any valid non-empty string+ * callback | string | true | a javascript function that will be invoked on callbacks | any valid javascript function+ * url | string | true | The URL to load | A valid URL+ * method | string | false | The http method | Valid HTTP method. Defaults to GET+ * headers | object {string, string} | false | Additional request headers |+ * body | string (base 64 encoded) | false | The http request body |+ * timeout | number | false | Request timeout (seconds) | any positive value+ *+ * The callback function takes two arguments. The first argument is the unique identifier supplied in the request+ * object. The second argument is a java object defining the HTTP result.+ */+- (void) performNativeXHR:(NSDictionary<NSString *, id> *) body inWebView:(WKWebView *) webView {++ NSString *requestId = [body cdvwkStringForKey:@"id"];+ NSString *callbackFunction = [body cdvwkStringForKey:@"callback"];+ NSString *urlString = [body cdvwkStringForKey:@"url"];+ NSString *method = [body cdvwkStringForKey:@"method"];++ __weak WKWebView* weakWebView = webView;++ void(^sendResult)(NSDictionary *) = ^void(NSDictionary *result) {+ dispatch_async(dispatch_get_main_queue(), ^{++ NSError *jsonError;+ NSData* json = [NSJSONSerialization dataWithJSONObject:result options:0 error:&jsonError];++ if (jsonError != nil) {+ NSLog(@"NativeXHR: Failed to encode response to json: %@", jsonError.localizedDescription); // FortityFalsePositive++ NSString *script = [NSString stringWithFormat:@"try { %@('%@', {'error' : 'json serialization failed'}) } catch (e) { }", callbackFunction, requestId];+ [weakWebView evaluateJavaScript:script completionHandler:nil];+ return;+ }++ NSString *script = [NSString stringWithFormat:@"try { %@('%@', %@) } catch (e) { }", callbackFunction, requestId, [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]];+ [weakWebView evaluateJavaScript:script completionHandler:nil];++ });+ };+++ if (requestId.length == 0 || callbackFunction.length == 0 ) {+ NSLog(@"NativeXHR: Required parameters id and callback url were not supplied.");+ return;+ }++ if (urlString.length == 0) {+ return sendResult( @{ @"error" : @"Invalid url"});+ }++ NSURL *url = [NSURL URLWithString:urlString];++ if (![url.scheme.lowercaseString isEqualToString:@"http"] && ![url.scheme.lowercaseString isEqualToString:@"https"]) {+ NSString *msg = [NSString stringWithFormat:@"NativeXHR: Invalid url scheme '%@'; only http and https are supported by NativeXHR", url.scheme];+ return sendResult( @{ @"error" : msg});+ }++ __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];+ if (method.length)+ request.HTTPMethod = [method uppercaseString];++ id val = [body objectForKey:@"timeout"];+ if ([val isKindOfClass:NSNumber.class]) {+ request.timeoutInterval = [(NSNumber *) val doubleValue];+ }+++ val = [body objectForKey:@"headers"];+ if ([val isKindOfClass:NSDictionary.class]) {+ [(NSDictionary *) val enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {+ if (![key isKindOfClass:NSString.class] || ![obj isKindOfClass:NSString.class])+ return;+ [request setValue:(NSString *)obj forHTTPHeaderField:(NSString *)key];+ }];+ }++ NSString *body64 = [body cdvwkStringForKey:@"body"];+ if (body64.length) {+ request.HTTPBody = [[NSData alloc] initWithBase64EncodedString:body64 options:0];+ }++ NSURLSessionDataTask *task = [self.urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // FortityFalsePositive++ NSMutableDictionary* result = [NSMutableDictionary dictionary];++ if (data != nil) {+ result[@"data"] = [[NSString alloc] initWithData:[data base64EncodedDataWithOptions:0] encoding:NSUTF8StringEncoding];+ }+ if (response != nil) {+ NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];+ dictionary[@"expectedContentLength"] = @(response.expectedContentLength);+ dictionary[@"suggestedFileName"] = response.suggestedFilename;+ dictionary[@"mimeType"] = response.MIMEType;+ dictionary[@"url"] = response.URL.absoluteString;+ dictionary[@"textEncodingName"] = response.textEncodingName;+ if ([response isKindOfClass:NSHTTPURLResponse.class]) {+ NSHTTPURLResponse* urlResponse = (NSHTTPURLResponse *) response;+ dictionary[@"allHeaderFields"] = urlResponse.allHeaderFields;+ dictionary[@"statusCode"] = @(urlResponse.statusCode);+ dictionary[@"localizedStatusCode"] = [NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode];+ }++ result[@"response"] = dictionary;+ }++ if (error != nil) {+ result[@"error"] = [error localizedDescription];+ result[@"underlyingErrorCode"] = @(error.code);+ }+ sendResult(result);+ }];++ task.taskDescription = requestId;+ [task resume];+}++- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {++ if (![message.name isEqualToString:@"nativeXHR"] || ![message.body isKindOfClass:NSDictionary.class]) {+ NSLog(@"NativeXHR: Invalid script message '%@' with body '%@' received. Ignoring.", message.name, message.body);+ return;+ }+ __weak __typeof(message.webView) weakWebView = message.webView;+ NSDictionary<NSString *, id> *body = message.body;++ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{+ [self performNativeXHR:body inWebView:weakWebView];+ });++}++@end++NS_ASSUME_NONNULL_ENDdiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/NSString+SSURLEncoding.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/NSString+SSURLEncoding.hnew file mode 100644index 000000000..696bac338--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/NSString+SSURLEncoding.h@@ -0,0 +1,5 @@+#import <Foundation/Foundation.h>++@interface NSString (SSURLEncoding)+@property (readonly) NSString *SSURLEncodedString;+@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/NSString+SSURLEncoding.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/NSString+SSURLEncoding.mnew file mode 100644index 000000000..15c8f6fd4--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/NSString+SSURLEncoding.m@@ -0,0 +1,30 @@+#import "NSString+SSURLEncoding.h"++@implementation NSString (SSURLEncoding)+- (NSString*)SSURLEncodedString+{+ NSString* result = (NSString *)CFBridgingRelease(+ CFURLCreateStringByAddingPercentEscapes(+ kCFAllocatorDefault,+ (CFStringRef)self,+ CFSTR("#%"), // don't escape these+ NULL, // allow escaping these+ kCFStringEncodingUTF8+ )+ );++ // we may have a URL with more than one '#' now - which iOS doesn't allow, so escape all but the first one+ NSArray *parts = [result componentsSeparatedByString:@"#"];+ NSString *finalResult = parts[0];+ for (int i=1; i<parts.count; i++) {+ NSString *part = [parts objectAtIndex:i];+ if (i==1) {+ finalResult = [finalResult stringByAppendingString:@"#"];+ } else {+ finalResult = [finalResult stringByAppendingString:@"%23"];+ }+ finalResult = [finalResult stringByAppendingString:part];+ }+ return finalResult;+}+@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/SocialSharing.h b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/SocialSharing.hnew file mode 100644index 000000000..0c7314505--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/SocialSharing.h@@ -0,0 +1,28 @@+#import <Cordova/CDV.h>+#import <MessageUI/MFMailComposeViewController.h>++@interface SocialSharing : CDVPlugin <UIPopoverControllerDelegate, MFMailComposeViewControllerDelegate, UIDocumentInteractionControllerDelegate>++@property (nonatomic, strong) MFMailComposeViewController *globalMailComposer;+@property (nonatomic, strong) UIDocumentInteractionController * documentInteractionController;+@property (retain) NSString * tempStoredFile;+@property (retain) CDVInvokedUrlCommand * command;++- (void)available:(CDVInvokedUrlCommand*)command;+- (void)setIPadPopupCoordinates:(CDVInvokedUrlCommand*)command;+- (void)share:(CDVInvokedUrlCommand*)command;+- (void)shareWithOptions:(CDVInvokedUrlCommand*)command;+- (void)canShareVia:(CDVInvokedUrlCommand*)command;+- (void)canShareViaEmail:(CDVInvokedUrlCommand*)command;+- (void)shareVia:(CDVInvokedUrlCommand*)command;+- (void)shareViaTwitter:(CDVInvokedUrlCommand*)command;+- (void)shareViaFacebook:(CDVInvokedUrlCommand*)command;+- (void)shareViaFacebookWithPasteMessageHint:(CDVInvokedUrlCommand*)command;+- (void)shareViaWhatsApp:(CDVInvokedUrlCommand*)command;+- (void)shareViaSMS:(CDVInvokedUrlCommand*)command;+- (void)shareViaEmail:(CDVInvokedUrlCommand*)command;+- (void)shareViaInstagram:(CDVInvokedUrlCommand*)command;++- (void)saveToPhotoAlbum:(CDVInvokedUrlCommand*)command;++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/SocialSharing.m b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/SocialSharing.mnew file mode 100644index 000000000..75c8b41bb--- /dev/null+++ b/cordova/platforms/ios/TagSpaces Beta/Plugins/cordova-plugin-x-socialsharing/SocialSharing.m@@ -0,0 +1,868 @@+#import "SocialSharing.h"+#import "NSString+SSURLEncoding.h"+#import <Cordova/CDV.h>+#import <Social/Social.h>+#import <Foundation/NSException.h>+#import <MessageUI/MFMessageComposeViewController.h>+#import <MessageUI/MFMailComposeViewController.h>+#import <MobileCoreServices/MobileCoreServices.h>++static NSString *const kShareOptionMessage = @"message";+static NSString *const kShareOptionSubject = @"subject";+static NSString *const kShareOptionFiles = @"files";+static NSString *const kShareOptionUrl = @"url";+static NSString *const kShareOptionIPadCoordinates = @"iPadCoordinates";++@implementation SocialSharing {+ UIPopoverController *_popover;+ NSString *_popupCoordinates;+}++- (void)pluginInitialize {+}++- (void)available:(CDVInvokedUrlCommand*)command {+ BOOL avail = NO;+ if (NSClassFromString(@"UIActivityViewController")) {+ avail = YES;+ }+ CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:avail];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+}++- (NSString*)getIPadPopupCoordinates {+ // see https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin/issues/1052+ return nil;+ /*+ if (_popupCoordinates != nil) {+ return _popupCoordinates;+ }+ if ([self.webView respondsToSelector:@selector(stringByEvaluatingJavaScriptFromString:)]) {+ return [(UIWebView*)self.webView stringByEvaluatingJavaScriptFromString:@"window.plugins.socialsharing.iPadPopupCoordinates();"];+ } else {+ // prolly a wkwebview, ignoring for now+ return nil;+ }+ */+}++- (void)setIPadPopupCoordinates:(CDVInvokedUrlCommand*)command {+ _popupCoordinates = [command.arguments objectAtIndex:0];+}++- (CGRect)getPopupRectFromIPadPopupCoordinates:(NSArray*)comps {+ CGRect rect = CGRectZero;+ if ([comps count] == 4) {+ rect = CGRectMake([[comps objectAtIndex:0] integerValue], [[comps objectAtIndex:1] integerValue], [[comps objectAtIndex:2] integerValue], [[comps objectAtIndex:3] integerValue]);+ }+ return rect;+}++- (void)share:(CDVInvokedUrlCommand*)command {+ [self shareInternal:command+ withOptions:@{+ kShareOptionMessage: [command.arguments objectAtIndex:0],+ kShareOptionSubject: [command.arguments objectAtIndex:1],+ kShareOptionFiles: [command.arguments objectAtIndex:2],+ kShareOptionUrl: [command.arguments objectAtIndex:3],+ kShareOptionIPadCoordinates: [command.arguments objectAtIndex:4]+ }+ isBooleanResponse:YES+];+}++- (void)shareWithOptions:(CDVInvokedUrlCommand*)command {+ NSDictionary* options = [command.arguments objectAtIndex:0];+ [self shareInternal:command+ withOptions:options+ isBooleanResponse:NO+ ];+}++- (void)shareInternal:(CDVInvokedUrlCommand*)command withOptions:(NSDictionary*)options isBooleanResponse:(BOOL)boolResponse {+ [self.commandDelegate runInBackground:^{ //avoid main thread block especially if sharing big files from url+ if (!NSClassFromString(@"UIActivityViewController")) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ return;+ }++ NSString *message = options[kShareOptionMessage];+ NSString *subject = options[kShareOptionSubject];+ NSArray *filenames = options[kShareOptionFiles];+ NSString *urlString = options[kShareOptionUrl];+ NSString *iPadCoordString = options[kShareOptionIPadCoordinates];+ NSArray *iPadCoordinates;++ if (iPadCoordString != nil && iPadCoordString != [NSNull null]) {+ iPadCoordinates = [iPadCoordString componentsSeparatedByString:@","];+ } else {+ iPadCoordinates = @[];+ }+++ NSMutableArray *activityItems = [[NSMutableArray alloc] init];++ if (message != (id)[NSNull null] && message != nil) {+ [activityItems addObject:message];+ }++ if (filenames != (id)[NSNull null] && filenames != nil && filenames.count > 0) {+ NSMutableArray *files = [[NSMutableArray alloc] init];+ for (NSString* filename in filenames) {+ NSObject *file = [self getImage:filename];+ if (file == nil) {+ file = [self getFile:filename];+ }+ if (file != nil) {+ [files addObject:file];+ }+ }+ [activityItems addObjectsFromArray:files];+ }++ if (urlString != (id)[NSNull null] && urlString != nil) {+ [activityItems addObject:[NSURL URLWithString:[urlString SSURLEncodedString]]];+ }++ UIActivity *activity = [[UIActivity alloc] init];+ NSArray *applicationActivities = [[NSArray alloc] initWithObjects:activity, nil];+ UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:applicationActivities];+ if (subject != (id)[NSNull null] && subject != nil) {+ [activityVC setValue:subject forKey:@"subject"];+ }++ if ([activityVC respondsToSelector:(@selector(setCompletionWithItemsHandler:))]) {+ [activityVC setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray * returnedItems, NSError * activityError) {+ [self cleanupStoredFiles];+ if (boolResponse) {+ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:completed]+ callbackId:command.callbackId];+ } else {+ NSDictionary * result = @{@"completed":@(completed), @"app":activityType == nil ? @"" : activityType};+ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]+ callbackId:command.callbackId];+ }+ }];+ } else {+ // let's suppress this warning otherwise folks will start opening issues while it's not relevant+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"+ [activityVC setCompletionHandler:^(NSString *activityType, BOOL completed) {+ [self cleanupStoredFiles];+ NSDictionary * result = @{@"completed":@(completed), @"app":activityType == nil ? @"" : activityType};+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ }];+#pragma GCC diagnostic warning "-Wdeprecated-declarations"+ }++ NSArray * socialSharingExcludeActivities = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"SocialSharingExcludeActivities"];+ if (socialSharingExcludeActivities!=nil && [socialSharingExcludeActivities count] > 0) {+ activityVC.excludedActivityTypes = socialSharingExcludeActivities;+ }++ dispatch_async(dispatch_get_main_queue(), ^(void){+ // iPad on iOS >= 8 needs a different approach+ if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {+ NSString* iPadCoords = [self getIPadPopupCoordinates];+ if (iPadCoords != nil && ![iPadCoords isEqual:@"-1,-1,-1,-1"]) {+ CGRect rect;+ if ([iPadCoordinates count] == 4) {++ rect = CGRectMake((int) [[iPadCoordinates objectAtIndex:0] integerValue], (int) [[iPadCoordinates objectAtIndex:1] integerValue], (int) [[iPadCoordinates objectAtIndex:2] integerValue], (int) [[iPadCoordinates objectAtIndex:3] integerValue]);+ } else {+ NSArray *comps = [iPadCoords componentsSeparatedByString:@","];+ rect = [self getPopupRectFromIPadPopupCoordinates:comps];+ }+ if ([activityVC respondsToSelector:@selector(popoverPresentationController)]) {+#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // iOS 8.0 supported+ activityVC.popoverPresentationController.sourceView = self.webView;+ activityVC.popoverPresentationController.sourceRect = rect;+#endif+ } else {+ _popover = [[UIPopoverController alloc] initWithContentViewController:activityVC];+ _popover.delegate = self;+ [_popover presentPopoverFromRect:rect inView:self.webView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];+ }+ } else if ([activityVC respondsToSelector:@selector(popoverPresentationController)]) {+#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // iOS 8.0 supported+ activityVC.popoverPresentationController.sourceView = self.webView;+ // position the popup at the bottom, just like iOS < 8 did (and iPhone still does on iOS 8)+ CGRect rect;+ if ([iPadCoordinates count] == 4) {+ NSLog([[NSString alloc] initWithFormat:@"test %d", [[iPadCoordinates objectAtIndex:0] integerValue]]);+ rect = CGRectMake((int) [[iPadCoordinates objectAtIndex:0] integerValue], (int) [[iPadCoordinates objectAtIndex:1] integerValue], (int) [[iPadCoordinates objectAtIndex:2] integerValue], (int) [[iPadCoordinates objectAtIndex:3] integerValue]);+ } else {+ NSArray *comps = [NSArray arrayWithObjects:+ [NSNumber numberWithInt:(self.viewController.view.frame.size.width/2)-200],+ [NSNumber numberWithInt:self.viewController.view.frame.size.height],+ [NSNumber numberWithInt:400],+ [NSNumber numberWithInt:400],+ nil];+ rect = [self getPopupRectFromIPadPopupCoordinates:comps];+ }+ activityVC.popoverPresentationController.sourceRect = rect;+#endif+ }+ }+ [[self getTopMostViewController] presentViewController:activityVC animated:YES completion:nil];+ });+ }];+}++- (void)shareViaTwitter:(CDVInvokedUrlCommand*)command {+ [self shareViaInternal:command type:SLServiceTypeTwitter];+}++- (void)shareViaFacebook:(CDVInvokedUrlCommand*)command {+ [self shareViaInternal:command type:SLServiceTypeFacebook];+}++- (void)shareViaFacebookWithPasteMessageHint:(CDVInvokedUrlCommand*)command {+ // If Fb app is installed a message is not prefilled.+ // When shared through the default iOS widget (iOS Settings > Facebook) the message is prefilled already.+ NSString *message = [command.arguments objectAtIndex:0];+ if (message != (id)[NSNull null]) {+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1000 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{+ BOOL fbAppInstalled = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]; // requires whitelisting on iOS9+ if (fbAppInstalled) {+ UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];+ [pasteboard setValue:message forPasteboardType:@"public.utf8-plain-text"];+ NSString *hint = [command.arguments objectAtIndex:4];+ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:hint delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];+ [alert show];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2800 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{+ [alert dismissWithClickedButtonIndex:-1 animated:YES];+ });+ }+ });+ }+ [self shareViaInternal:command type:SLServiceTypeFacebook];+}++- (void)shareVia:(CDVInvokedUrlCommand*)command {+ [self shareViaInternal:command type:[command.arguments objectAtIndex:4]];+}++- (void)canShareVia:(CDVInvokedUrlCommand*)command {+ NSString *via = [command.arguments objectAtIndex:4];+ CDVPluginResult * pluginResult;+ if ([@"sms" caseInsensitiveCompare:via] == NSOrderedSame && [self canShareViaSMS]) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else if ([@"email" caseInsensitiveCompare:via] == NSOrderedSame && [self isEmailAvailable]) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else if ([@"whatsapp" caseInsensitiveCompare:via] == NSOrderedSame && [self canShareViaWhatsApp]) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else if ([@"instagram" caseInsensitiveCompare:via] == NSOrderedSame && [self canShareViaInstagram]) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else if ([@"com.apple.social.facebook" caseInsensitiveCompare:via] == NSOrderedSame && [self canShareViaFacebook]) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else if ([@"com.apple.social.twitter" caseInsensitiveCompare:via] == NSOrderedSame && [self canShareViaTwitter]) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else if ([self isAvailableForSharing:command type:via]) {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ } else {+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ }+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+}++- (void)canShareViaEmail:(CDVInvokedUrlCommand*)command {+ if ([self isEmailAvailable]) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ } else {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ }+}++- (bool)isEmailAvailable {+ Class messageClass = (NSClassFromString(@"MFMailComposeViewController"));+ return messageClass != nil && [messageClass canSendMail];+}++- (bool)isAvailableForSharing:(CDVInvokedUrlCommand*)command+ type:(NSString *) type {++ // isAvailableForServiceType returns true if you pass it a type that is not+ // in the defined constants, this is probably a bug on apples part+ if(!([type isEqualToString:SLServiceTypeFacebook]+ || [type isEqualToString:SLServiceTypeTwitter]+ || [type isEqualToString:SLServiceTypeTencentWeibo]+ || [type isEqualToString:SLServiceTypeSinaWeibo])) {+ return false;+ }+ // wrapped in try-catch, because isAvailableForServiceType may crash if an invalid type is passed+ @try {+ return [SLComposeViewController isAvailableForServiceType:type];+ }+ @catch (NSException* exception) {+ return false;+ }+}++- (void)shareViaInternal:(CDVInvokedUrlCommand*)command+ type:(NSString *) type {++ NSString *message = [command.arguments objectAtIndex:0];+ // subject is not supported by the SLComposeViewController+ NSArray *filenames = [command.arguments objectAtIndex:2];+ NSString *urlString = [command.arguments objectAtIndex:3];++ // boldly invoke the target app, because the phone will display a nice message asking to configure the app+ SLComposeViewController *composeViewController = [SLComposeViewController composeViewControllerForServiceType:type];+ if (message != (id)[NSNull null]) {+ [composeViewController setInitialText:message];+ }++ for (NSString* filename in filenames) {+ UIImage* image = [self getImage:filename];+ if (image != nil) {+ [composeViewController addImage:image];+ }+ }++ if (urlString != (id)[NSNull null]) {+ [composeViewController addURL:[NSURL URLWithString:[urlString SSURLEncodedString]]];+ }++ [composeViewController setCompletionHandler:^(SLComposeViewControllerResult result) {+ if (SLComposeViewControllerResultCancelled == result) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"cancelled"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ } else if (SLComposeViewControllerResultDone == result || [self isAvailableForSharing:command type:type]) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:true];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ } else {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ }+ // required for iOS6 (issues #162 and #167)+ [self.viewController dismissViewControllerAnimated:YES completion:nil];+ }];+ [[self getTopMostViewController] presentViewController:composeViewController animated:YES completion:nil];+}++- (void)shareViaEmail:(CDVInvokedUrlCommand*)command {+ if ([self isEmailAvailable]) {++ if (TARGET_IPHONE_SIMULATOR && IsAtLeastiOSVersion(@"8.0")) {+ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"SocialSharing plugin"+ message:@"Sharing via email is not supported on the iOS 8 simulator."+ delegate:nil+ cancelButtonTitle:@"OK"+ otherButtonTitles:nil];+ [alert show];+ return;+ }++ [self cycleTheGlobalMailComposer];++ self.globalMailComposer.mailComposeDelegate = self;++ if ([command.arguments objectAtIndex:0] != (id)[NSNull null]) {+ NSString *message = [command.arguments objectAtIndex:0];+ BOOL isHTML = [message rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch].location != NSNotFound;+ [self.globalMailComposer setMessageBody:message isHTML:isHTML];+ }++ if ([command.arguments objectAtIndex:1] != (id)[NSNull null]) {+ [self.globalMailComposer setSubject: [command.arguments objectAtIndex:1]];+ }++ if ([command.arguments objectAtIndex:2] != (id)[NSNull null]) {+ [self.globalMailComposer setToRecipients:[command.arguments objectAtIndex:2]];+ }++ if ([command.arguments objectAtIndex:3] != (id)[NSNull null]) {+ [self.globalMailComposer setCcRecipients:[command.arguments objectAtIndex:3]];+ }++ if ([command.arguments objectAtIndex:4] != (id)[NSNull null]) {+ [self.globalMailComposer setBccRecipients:[command.arguments objectAtIndex:4]];+ }++ if ([command.arguments objectAtIndex:5] != (id)[NSNull null]) {+ NSArray* attachments = [command.arguments objectAtIndex:5];+ NSFileManager* fileManager = [NSFileManager defaultManager];+ for (NSString* path in attachments) {+ NSURL *file = [self getFile:path];+ NSData* data = [fileManager contentsAtPath:file.path];++ if (!data) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"invalid attachment"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ return;+ }++ NSString* fileName;+ NSString* mimeType;+ NSString* basename = [self getBasenameFromAttachmentPath:path];++ //Find data anywhere in string+ NSRange rangeData = [basename rangeOfString:@"data:"];+ if (rangeData.location == NSNotFound)+ {+ fileName = [basename pathComponents].lastObject;+ mimeType = [self getMimeTypeFromFileExtension:[basename pathExtension]];+ }+ else+ {+ mimeType = (NSString*)[[[basename substringFromIndex:rangeData.location+rangeData.length] componentsSeparatedByString: @";"] objectAtIndex:0];++ //Find df anywhere in string+ NSRange rangeDF = [basename rangeOfString:@"df:"];+ //If not found fallback to default name+ if (rangeDF.location == NSNotFound) {+ fileName = @"attachment.";+ fileName = [fileName stringByAppendingString:(NSString*)[[mimeType componentsSeparatedByString: @"/"] lastObject]];+ } else {+ //Found, apply name+ fileName = (NSString*)[[[basename substringFromIndex:rangeDF.location+rangeDF.length] componentsSeparatedByString: @";"] objectAtIndex:0];+ }+++ NSString *base64content = (NSString*)[[basename componentsSeparatedByString: @","] lastObject];+ data = [SocialSharing dataFromBase64String:base64content];+ }+ [self.globalMailComposer addAttachmentData:data mimeType:mimeType fileName:fileName];+ }+ }++ // remember the command, because we need it in the didFinishWithResult method+ _command = command;++ dispatch_async(dispatch_get_main_queue(), ^{+ [[self getTopMostViewController] presentViewController:self.globalMailComposer animated:YES completion:nil];+ });+ } else {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ }+}++- (UIViewController*) getTopMostViewController {+ UIViewController *presentingViewController = [[UIApplication sharedApplication] keyWindow].rootViewController;+ while (presentingViewController.presentedViewController != nil) {+ presentingViewController = presentingViewController.presentedViewController;+ }+ return presentingViewController;+}++- (NSString*) getBasenameFromAttachmentPath:(NSString*)path {+ if ([path hasPrefix:@"base64:"]) {+ NSString* pathWithoutPrefix = [path stringByReplacingOccurrencesOfString:@"base64:" withString:@""];+ return [pathWithoutPrefix substringToIndex:[pathWithoutPrefix rangeOfString:@"//"].location];+ }+ return [path componentsSeparatedByString: @"?"][0];+}++- (NSString*) getMimeTypeFromFileExtension:(NSString*)extension {+ if (!extension) {+ return nil;+ }+ // Get the UTI from the file's extension+ CFStringRef ext = (CFStringRef)CFBridgingRetain(extension);+ CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, NULL);+ // Converting UTI to a mime type+ NSString *result = (NSString*)CFBridgingRelease(UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType));+ CFRelease(ext);+ CFRelease(type);+ if (result == nil) {+ result = @"application/octet-stream";+ }++ return result;+}++/**+ * Delegate will be called after the mail composer did finish an action+ * to dismiss the view.+ */+- (void) mailComposeController:(MFMailComposeViewController*)controller+ didFinishWithResult:(MFMailComposeResult)result+ error:(NSError*)error {+ bool ok = result == MFMailComposeResultSent;+ [self.globalMailComposer dismissViewControllerAnimated:YES completion:nil];+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:ok];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:_command.callbackId];+}++-(void)cycleTheGlobalMailComposer {+ // we are cycling the damned GlobalMailComposer: http://stackoverflow.com/questions/25604552/i-have-real-misunderstanding-with-mfmailcomposeviewcontroller-in-swift-ios8-in/25604976#25604976+ self.globalMailComposer = nil;+ self.globalMailComposer = [[MFMailComposeViewController alloc] init];+}++- (bool)canShareViaSMS {+ Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));+ return messageClass != nil && [messageClass canSendText];+}++- (void)shareViaSMS:(CDVInvokedUrlCommand*)command {+ if ([self canShareViaSMS]) {+ NSDictionary* options = [command.arguments objectAtIndex:0];+ NSString *phonenumbers = [command.arguments objectAtIndex:1];+ NSString *message = [options objectForKey:@"message"];+ NSString *subject = [options objectForKey:@"subject"];+ NSString *image = [options objectForKey:@"image"];++ MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];+ picker.messageComposeDelegate = (id) self;+ if (message != (id)[NSNull null]) {+ picker.body = message;+ }+ if (subject != (id)[NSNull null]) {+ [picker setSubject:subject];+ }+ if (image != nil && image != (id)[NSNull null]) {+ BOOL canSendAttachments = [[MFMessageComposeViewController class] respondsToSelector:@selector(canSendAttachments)];+ if (canSendAttachments) {+ NSURL *file = [self getFile:image];+ if (file != nil) {+ [picker addAttachmentURL:file withAlternateFilename:nil];+ }+ }+ }++ if (phonenumbers != (id)[NSNull null]) {+ [picker setRecipients:[phonenumbers componentsSeparatedByString:@","]];+ }+ // remember the command, because we need it in the didFinishWithResult method+ _command = command;+ dispatch_async(dispatch_get_main_queue(), ^{+ picker.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;+ [[self getTopMostViewController] presentViewController:picker animated:NO completion:nil];+ });+ } else {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ }+}++// Dismisses the SMS composition interface when users taps Cancel or Send+- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {+ bool ok = result == MessageComposeResultSent;+ [[self getTopMostViewController] dismissViewControllerAnimated:YES completion:nil];+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:ok];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:_command.callbackId];+}++- (bool)canShareViaInstagram {+ return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"instagram://app"]]; // requires whitelisting on iOS9+}++- (bool)canShareViaWhatsApp {+ return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"whatsapp://app"]]; // requires whitelisting on iOS9+}++- (bool)canShareViaFacebook {+ return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"fb://"]]; // requires whitelisting on iOS9+}++- (bool)canShareViaTwitter {+ return [[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"twitter://"]]; // requires whitelisting on iOS9+}++// this is only an internal test method for now, can be used to open a share sheet with 'Open in xx' links for tumblr, drive, dropbox, ..+- (void)openImage:(NSString *)imageName {+ UIImage* image =[self getImage:imageName];+ if (image != nil) {+ NSString * savePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/myTempImage.jpg"];+ [UIImageJPEGRepresentation(image, 1.0) writeToFile:savePath atomically:YES];+ _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];+ _documentInteractionController.UTI = @""; // TODO find the scheme for google drive and create a shareViaGoogleDrive function+ [_documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.viewController.view animated: YES];+ }+}++- (void)shareViaInstagram:(CDVInvokedUrlCommand*)command {++ // on iOS9 canShareVia('instagram'..) will only work if instagram:// is whitelisted.+ // If it's not, this method will ask permission to the user on iOS9 for opening the app,+ // which is of course better than Instagram sharing not working at all because you forgot to whitelist it.+ // Tradeoff: on iOS9 this method will always return true, so make sure to whitelist it and call canShareVia('instagram'..)+ if (!IsAtLeastiOSVersion(@"9.0")) {+ if (![self canShareViaInstagram]) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ return;+ }+ }++ NSString *message = [command.arguments objectAtIndex:0];+ // subject is not supported by the SLComposeViewController+ NSArray *filenames = [command.arguments objectAtIndex:2];++ // only use the first image (for now.. maybe we can share in a loop?)+ UIImage* image = nil;+ for (NSString* filename in filenames) {+ image = [self getImage:filename];+ break;+ }++// NSData *imageObj = [NSData dataFromBase64String:objectAtIndex0];+ NSString *tmpDir = NSTemporaryDirectory();+ NSString *path = [tmpDir stringByAppendingPathComponent:@"instagram.igo"];+ [UIImageJPEGRepresentation(image, 1.0) writeToFile:path atomically:YES];++ _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]];+ _documentInteractionController.delegate = self;+ _documentInteractionController.UTI = @"com.instagram.exclusivegram";++ if (message != (id)[NSNull null]) {+ // no longer working, so ..+ _documentInteractionController.annotation = @{@"InstagramCaption" : message};++ // .. we put the message on the clipboard (you app can prompt the user to paste it)+ UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];+ [pasteboard setValue:message forPasteboardType:@"public.utf8-plain-text"];+ }++ // remember the command for the delegate method+ _command = command;++ // test for #513+ dispatch_async(dispatch_get_main_queue(), ^(void){+ [_documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.webView animated:YES];+ });+}++- (void)shareViaWhatsApp:(CDVInvokedUrlCommand*)command {++ // on iOS9 canShareVia('whatsapp'..) will only work if whatsapp:// is whitelisted.+ // If it's not, this method will ask permission to the user on iOS9 for opening the app,+ // which is of course better than WhatsApp sharing not working at all because you forgot to whitelist it.+ // Tradeoff: on iOS9 this method will always return true, so make sure to whitelist it and call canShareVia('whatsapp'..)+ if (!IsAtLeastiOSVersion(@"9.0")) {+ if (![self canShareViaWhatsApp]) {+ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"not available"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ return;+ }+ }++ NSString *message = [command.arguments objectAtIndex:0];+ // subject is not supported by the SLComposeViewController+ NSArray *filenames = [command.arguments objectAtIndex:2];+ NSString *urlString = [command.arguments objectAtIndex:3];+ NSString *abid = [command.arguments objectAtIndex:4];+ NSString *phone = [command.arguments objectAtIndex:5];++ // only use the first image (for now.. maybe we can share in a loop?)+ UIImage *image = nil;+ for (NSString *filename in filenames) {+ image = [self getImage:filename];+ break;+ }++ // with WhatsApp, we can share an image OR text+url.. image wins if set+ if (image != nil) {+ NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/whatsAppTmp.jpg"];+ [UIImageJPEGRepresentation(image, 1.0) writeToFile:savePath atomically:YES];+ _documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];+ _documentInteractionController.UTI = @"net.whatsapp.image";+ _documentInteractionController.delegate = self;+ _command = command;+ [_documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.viewController.view animated: YES];+ } else {+ // append an url to a message, if both are passed+ NSString *shareString = @"";+ if (message != (id)[NSNull null]) {+ shareString = message;+ }+ if (urlString != (id)[NSNull null]) {+ if ([shareString isEqual: @""]) {+ shareString = urlString;+ } else {+ shareString = [NSString stringWithFormat:@"%@ %@", shareString, [urlString SSURLEncodedString]];+ }+ }+ NSString *encodedShareString = [shareString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];+ // also encode the '=' character+ encodedShareString = [encodedShareString stringByReplacingOccurrencesOfString:@"=" withString:@"%3D"];+ encodedShareString = [encodedShareString stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];+ NSString *abidString = @"";+ if (abid != (id)[NSNull null]) {+ abidString = [NSString stringWithFormat:@"abid=%@&", abid];+ }+ NSString *phoneString = @"";+ if (phone != (id)[NSNull null]) {+ phoneString = [NSString stringWithFormat:@"phone=%@&", phone];+ }+ NSString *encodedShareStringForWhatsApp = [NSString stringWithFormat:@"whatsapp://send?%@%@text=%@", abidString, phoneString, encodedShareString];++ NSURL *whatsappURL = [NSURL URLWithString:encodedShareStringForWhatsApp];+ [[UIApplication sharedApplication] openURL: whatsappURL];+ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];+ }+}++- (void)saveToPhotoAlbum:(CDVInvokedUrlCommand*)command {+ self.command = command;+ NSArray *filenames = [command.arguments objectAtIndex:0];+ [self.commandDelegate runInBackground:^{+ bool shared = false;+ for (NSString* filename in filenames) {+ UIImage* image = [self getImage:filename];+ if (image != nil) {+ shared = true;+ UIImageWriteToSavedPhotosAlbum(image, self, @selector(thisImage:wasSavedToPhotoAlbumWithError:contextInfo:), nil);+ }+ }+ if (!shared) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"no valid image was passed"];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:self.command.callbackId];+ }+ }];+}++// called from saveToPhotoAlbum, note that we only send feedback for the first image that's being saved (not keeping the callback)+// but since the UIImageWriteToSavedPhotosAlbum function is only called with valid images that should not be a problem+- (void)thisImage:(UIImage *)image wasSavedToPhotoAlbumWithError:(NSError *)error contextInfo:(void*)ctxInfo {+ if (error) {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.localizedDescription];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:self.command.callbackId];+ } else {+ CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ [self.commandDelegate sendPluginResult:pluginResult callbackId:self.command.callbackId];+ }+}++-(UIImage*)getImage: (NSString *)imageName {+ UIImage *image = nil;+ if (imageName != (id)[NSNull null]) {+ if ([imageName hasPrefix:@"http"]) {+ image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageName]]];+ } else if ([imageName hasPrefix:@"www/"]) {+ image = [UIImage imageNamed:imageName];+ } else if ([imageName hasPrefix:@"file://"]) {+ image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[[NSURL URLWithString:imageName] path]]];+ } else if ([imageName hasPrefix:@"data:"]) {+ // using a base64 encoded string+ NSURL *imageURL = [NSURL URLWithString:imageName];+ NSData *imageData = [NSData dataWithContentsOfURL:imageURL];+ image = [UIImage imageWithData:imageData];+ } else if ([imageName hasPrefix:@"assets-library://"]) {+ // use assets-library+ NSURL *imageURL = [NSURL URLWithString:imageName];+ NSData *imageData = [NSData dataWithContentsOfURL:imageURL];+ image = [UIImage imageWithData:imageData];+ } else {+ // assume anywhere else, on the local filesystem+ image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageName]];+ }+ }+ return image;+}++-(NSURL*)getFile: (NSString *)fileName {+ NSURL *file = nil;+ if (fileName != (id)[NSNull null]) {+ NSRange rangeData = [fileName rangeOfString:@"data:"];+ if ([fileName hasPrefix:@"http"]) {+ NSURL *url = [NSURL URLWithString:fileName];+ NSData *fileData = [NSData dataWithContentsOfURL:url];+ NSURLRequest *request = [NSURLRequest requestWithURL: url];+ NSHTTPURLResponse *response;+ [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];+ if ([response respondsToSelector:@selector(allHeaderFields)]) {+ NSDictionary *dictionary = [response allHeaderFields];+ NSLog([dictionary description]);+ NSString *name = dictionary[@"Content-Disposition"];+ if (name == nil){+ NSString *name = (NSString*)[[fileName componentsSeparatedByString: @"/"] lastObject];+ file = [NSURL fileURLWithPath:[self storeInFile:[name componentsSeparatedByString: @"?"][0] fileData:fileData]];+ } else {+ file = [NSURL fileURLWithPath:[self storeInFile:[[name componentsSeparatedByString:@"="] lastObject] fileData:fileData]];+ }+ } else {+ NSString *name = (NSString*)[[fileName componentsSeparatedByString: @"/"] lastObject];+ file = [NSURL fileURLWithPath:[self storeInFile:[name componentsSeparatedByString: @"?"][0] fileData:fileData]];+ }+ } else if ([fileName hasPrefix:@"www/"]) {+ NSString *bundlePath = [[NSBundle mainBundle] bundlePath];+ NSString *fullPath = [NSString stringWithFormat:@"%@/%@", bundlePath, fileName];+ file = [NSURL fileURLWithPath:fullPath];+ } else if ([fileName hasPrefix:@"file://"]) {+ // stripping the first 6 chars, because the path should start with / instead of file://+ file = [NSURL fileURLWithPath:[fileName substringFromIndex:6]];+ } else if (rangeData.location != NSNotFound ){+ //If found "data:"+ NSString *fileType = (NSString*)[[[fileName substringFromIndex:rangeData.location+rangeData.length] componentsSeparatedByString: @";"] objectAtIndex:0];++ NSString* attachmentName;+ //Find df anywhere in string+ NSRange rangeDF = [fileName rangeOfString:@"df:"];+ //If not found fallback to default name+ if (rangeDF.location == NSNotFound) {+ attachmentName = @"attachment.";+ attachmentName = [attachmentName stringByAppendingString:(NSString*)[[fileType componentsSeparatedByString: @"/"] lastObject]];+ } else {+ //Found, apply name+ attachmentName = (NSString*)[[[fileName substringFromIndex:rangeDF.location+rangeDF.length] componentsSeparatedByString: @";"] objectAtIndex:0];+ }+++ NSString *base64content = (NSString*)[[fileName componentsSeparatedByString: @","] lastObject];+ NSData* data = [SocialSharing dataFromBase64String:base64content];+ file = [NSURL fileURLWithPath:[self storeInFile:attachmentName fileData:data]];++ } else {+ // assume anywhere else, on the local filesystem+ file = [NSURL fileURLWithPath:fileName];+ }+ }+ return file;+}++-(NSString*) storeInFile: (NSString*) fileName+ fileData: (NSData*) fileData {+ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);+ NSString *documentsDirectory = [paths objectAtIndex:0];+ NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];+ [fileData writeToFile:filePath atomically:YES];+ _tempStoredFile = filePath;+ return filePath;+}++- (void) cleanupStoredFiles {+ if (_tempStoredFile != nil) {+ NSError *error;+ [[NSFileManager defaultManager]removeItemAtPath:_tempStoredFile error:&error];+ }+}+++ (NSData*) dataFromBase64String:(NSString*)aString {+ return [[NSData alloc] initWithBase64EncodedString:aString options:0];+}++#pragma mark - UIPopoverControllerDelegate methods++- (void)popoverController:(UIPopoverController *)popoverController willRepositionPopoverToRect:(inout CGRect *)rect inView:(inout UIView **)view {+ NSArray *comps = [[self getIPadPopupCoordinates] componentsSeparatedByString:@","];+ CGRect newRect = [self getPopupRectFromIPadPopupCoordinates:comps];+ rect->origin = newRect.origin;+}++- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {+ _popover = nil;+}++#pragma mark - UIDocumentInteractionControllerDelegate methods++- (void) documentInteractionController: (UIDocumentInteractionController *) controller willBeginSendingToApplication: (NSString *) application {+ // note that the application actually contains the app bundle id which was picked (for whatsapp and instagram only)+ NSLog(@"SocialSharing app selected: %@", application);+}++- (void) documentInteractionControllerDidDismissOpenInMenu: (UIDocumentInteractionController *) controller {+ if (self.command != nil) {+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];+ [self.commandDelegate sendPluginResult:result callbackId: self.command.callbackId];+ }+}++@enddiff --git a/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Info.plist b/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Info.plistindex efb88a050..ffb58f4e3 100644--- a/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Info.plist+++ b/cordova/platforms/ios/TagSpaces Beta/TagSpaces Beta-Info.plist@@ -24,23 +24,12 @@<string>1.0.0</string><key>LSRequiresIPhoneOS</key><true/>- <key>NSAppTransportSecurity</key>- <dict>- <key>NSAllowsArbitraryLoads</key>- <true/>- </dict><key>NSMainNibFile</key><string/><key>NSMainNibFile~ipad</key><string/>- <key>NSPhotoLibraryUsageDescription</key>- <string>This app requires access to the photo library.</string>- <key>NSCameraUsageDescription</key>- <string>This app requires access to the camera.</string>- <key>UIBackgroundModes</key>- <array>- <string>audio</string>- </array>+ <key>UILaunchStoryboardName</key>+ <string>CDVLaunchScreen</string><key>UIRequiresFullScreen</key><true/><key>UISupportedInterfaceOrientations</key>@@ -56,5 +45,18 @@<string>UIInterfaceOrientationPortraitUpsideDown</string><string>UIInterfaceOrientationLandscapeRight</string></array>+ <key>NSAppTransportSecurity</key>+ <dict>+ <key>NSAllowsArbitraryLoads</key>+ <true/>+ </dict>+ <key>UIBackgroundModes</key>+ <array>+ <string>audio</string>+ </array>+ <key>NSPhotoLibraryAddUsageDescription</key>+ <string>This app requires photo library access to function properly.</string>+ <key>NSPhotoLibraryUsageDescription</key>+ <string>This app requires photo library access to function properly.</string></dict></plist>\ No newline at end of filediff --git a/cordova/platforms/ios/TagSpaces Beta/config.xml b/cordova/platforms/ios/TagSpaces Beta/config.xmlindex b6f6dbe99..f318ad2c7 100755--- a/cordova/platforms/ios/TagSpaces Beta/config.xml+++ b/cordova/platforms/ios/TagSpaces Beta/config.xml@@ -1,5 +1,11 @@<?xml version='1.0' encoding='utf-8'?><widget id="org.tagspaces.mobile" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">+ <feature name="CDVWebViewEngine">+ <param name="ios-package" value="CDVWebViewEngine" />+ </feature>+ <feature name="LaunchScreen">+ <param name="ios-package" value="CDVLaunchScreen" />+ </feature><feature name="LocalStorage"><param name="ios-package" value="CDVLocalStorage" /></feature>@@ -36,8 +42,16 @@<feature name="FileOpener2"><param name="ios-package" value="FileOpener2" /></feature>- <feature name="CDVWKWebViewEngine">- <param name="ios-package" value="CDVWKWebViewEngine" />+ <feature name="Downloader">+ <param name="ios-package" value="Downloader" />+ </feature>+ <feature name="SocialSharing">+ <param name="ios-package" value="SocialSharing" />+ <param name="onload" value="true" />+ </feature>+ <feature name="CDVWKWebViewFileXhr">+ <param name="ios-package" value="CDVWKWebViewFileXhr" />+ <param name="onload" value="true" /></feature><name>TagSpaces Beta</name><description>@@ -61,7 +75,7 @@<preference name="DisallowOverscroll" value="false" /><preference name="EnableViewportScale" value="false" /><preference name="KeyboardDisplayRequiresUserAction" value="true" />- <preference name="MediaPlaybackRequiresUserAction" value="false" />+ <preference name="MediaTypesRequiringUserActionForPlayback" value="none" /><preference name="SuppressesIncrementalRendering" value="false" /><preference name="SuppressesLongPressGesture" value="false" /><preference name="Suppresses3DTouchGesture" value="false" />@@ -73,6 +87,6 @@<preference name="AndroidPersistentFileLocation" value="Compatibility" /><preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" /><preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />- <preference name="WKWebViewOnly" value="true" />- <preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />+ <preference name="InterceptRemoteRequests" value="all" />+ <preference name="allowFileAccessFromFileURLs" value="true" /></widget>diff --git a/cordova/platforms/ios/cordova/Api.js b/cordova/platforms/ios/cordova/Api.jsindex e45b7822c..e87a135de 100755--- a/cordova/platforms/ios/cordova/Api.js+++ b/cordova/platforms/ios/cordova/Api.js@@ -19,19 +19,27 @@/* jslint node: true */-var fs = require('fs');-var path = require('path');-var unorm = require('unorm');-var projectFile = require('./lib/projectFile');-var check_reqs = require('./lib/check_reqs');-var CordovaError = require('cordova-common').CordovaError;-var CordovaLogger = require('cordova-common').CordovaLogger;-var events = require('cordova-common').events;-var PluginManager = require('cordova-common').PluginManager;-var Q = require('q');-var util = require('util');-var xcode = require('xcode');-var ConfigParser = require('cordova-common').ConfigParser;+/**+ * @todo update coho to update this line.+ * @todo use `package.json` instead but first+ * figure out how this fit in with the platform-centered workflow structure.+ * This workflow would not have the `package.json` file.+ */+// Coho updates this line+const VERSION = '6.1.0';++const fs = require('fs-extra');+const path = require('path');+const unorm = require('unorm');+const projectFile = require('./lib/projectFile');+const check_reqs = require('./lib/check_reqs');+const CordovaError = require('cordova-common').CordovaError;+const CordovaLogger = require('cordova-common').CordovaLogger;+const events = require('cordova-common').events;+const PluginManager = require('cordova-common').PluginManager;+const util = require('util');+const xcode = require('xcode');+const ConfigParser = require('cordova-common').ConfigParser;function setupEvents (externalEventEmitter) {if (externalEventEmitter) {@@ -44,6 +52,10 @@ function setupEvents (externalEventEmitter) {}}+function getVariableSpec (spec, options) {+ return spec.includes('$') ? options.cli_variables[spec.replace('$', '')] : spec;+}+/*** Creates a new PlatformApi instance.*@@ -62,14 +74,13 @@ function Api (platform, platformRootDir, events) {setupEvents(events);- var xcodeProjDir;- var xcodeCordovaProj;+ let xcodeProjDir;+ let xcodeCordovaProj;try {-- var xcodeProjDir_array = fs.readdirSync(this.root).filter(function (e) { return e.match(/\.xcodeproj$/i); });+ const xcodeProjDir_array = fs.readdirSync(this.root).filter(e => e.match(/\.xcodeproj$/i));if (xcodeProjDir_array.length > 1) {- for (var x = 0; x < xcodeProjDir_array.length; x++) {+ for (let x = 0; x < xcodeProjDir_array.length; x++) {if (xcodeProjDir_array[x].substring(0, 2) === '._') {xcodeProjDir_array.splice(x, 1);}@@ -78,13 +89,13 @@ function Api (platform, platformRootDir, events) {xcodeProjDir = xcodeProjDir_array[0];if (!xcodeProjDir) {- throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');+ throw new CordovaError(`The provided path "${this.root}" is not a Cordova iOS project.`);}- var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep) + 1, xcodeProjDir.indexOf('.xcodeproj'));+ const cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep) + 1, xcodeProjDir.indexOf('.xcodeproj'));xcodeCordovaProj = path.join(this.root, cordovaProjName);} catch (e) {- throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');+ throw new CordovaError(`The provided path "${this.root}" is not a Cordova iOS project.`);}this.locations = {@@ -95,7 +106,7 @@ function Api (platform, platformRootDir, events) {defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'),pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'),xcodeProjDir: path.join(this.root, xcodeProjDir),- xcodeCordovaProj: xcodeCordovaProj+ xcodeCordovaProj};}@@ -117,21 +128,21 @@ function Api (platform, platformRootDir, events) {* @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi* instance or rejected with CordovaError.*/-Api.createPlatform = function (destination, config, options, events) {+Api.createPlatform = (destination, config, options, events) => {setupEvents(events);// CB-6992 it is necessary to normalize characters// because node and shell scripts handles unicode symbols differently// We need to normalize the name to NFD form since iOS uses NFD unicode form- var name = unorm.nfd(config.name());- var result;+ const name = unorm.nfd(config.name());+ let result;try {result = require('../../../lib/create').createProject(destination, config.getAttribute('ios-CFBundleIdentifier') || config.packageName(), name, options, config)- .then(function () {+ .then(() => {// after platform is created we return Api instance based on new Api.js location// This is required to correctly resolve paths in the future api calls- var PlatformApi = require(path.resolve(destination, 'cordova/Api'));+ const PlatformApi = require(path.resolve(destination, 'cordova/Api'));return new PlatformApi('ios', destination, events);});} catch (e) {@@ -157,15 +168,15 @@ Api.createPlatform = function (destination, config, options, events) {* @return {Promise<PlatformApi>} Promise either fulfilled with PlatformApi* instance or rejected with CordovaError.*/-Api.updatePlatform = function (destination, options, events) {+Api.updatePlatform = (destination, options, events) => {setupEvents(events);- var result;+ let result;try {result = require('../../../lib/create').updateProject(destination, options)- .then(function () {- var PlatformApi = require(path.resolve(destination, 'cordova/Api'));+ .then(() => {+ const PlatformApi = require(path.resolve(destination, 'cordova/Api'));return new PlatformApi('ios', destination, events);});} catch (e) {@@ -182,11 +193,11 @@ Api.updatePlatform = function (destination, options, events) {* platform's file structure and other properties of platform.*/Api.prototype.getPlatformInfo = function () {- var result = {};+ const result = {};result.locations = this.locations;result.root = this.root;result.name = this.platform;- result.version = require('./version');+ result.version = Api.version();result.projectConfig = new ConfigParser(this.locations.configXml);return result;@@ -230,9 +241,7 @@ Api.prototype.prepare = function (cordovaProject) {* CordovaError instance.*/Api.prototype.addPlugin = function (plugin, installOptions) {-- var xcodeproj = projectFile.parse(this.locations);- var self = this;+ const xcodeproj = projectFile.parse(this.locations);installOptions = installOptions || {};installOptions.variables = installOptions.variables || {};@@ -241,41 +250,36 @@ Api.prototype.addPlugin = function (plugin, installOptions) {installOptions.variables.PACKAGE_NAME = xcodeproj.getPackageName();}- return PluginManager.get(self.platform, self.locations, xcodeproj)+ return PluginManager.get(this.platform, this.locations, xcodeproj).addPlugin(plugin, installOptions)- .then(function () {+ .then(() => {if (plugin != null) {- var headerTags = plugin.getHeaderFiles(self.platform);- var bridgingHeaders = headerTags.filter(function (obj) {- return (obj.type === 'BridgingHeader');- });+ const headerTags = plugin.getHeaderFiles(this.platform);+ const bridgingHeaders = headerTags.filter(obj => obj.type === 'BridgingHeader');if (bridgingHeaders.length > 0) {- var project_dir = self.locations.root;- var project_name = self.locations.xcodeCordovaProj.split('/').pop();- var BridgingHeader = require('./lib/BridgingHeader').BridgingHeader;- var bridgingHeaderFile = new BridgingHeader(path.join(project_dir, project_name, 'Bridging-Header.h'));+ const project_dir = this.locations.root;+ const project_name = this.locations.xcodeCordovaProj.split('/').pop();+ const BridgingHeader = require('./lib/BridgingHeader').BridgingHeader;+ const bridgingHeaderFile = new BridgingHeader(path.join(project_dir, project_name, 'Bridging-Header.h'));events.emit('verbose', 'Adding Bridging-Headers since the plugin contained <header-file> with type="BridgingHeader"');- bridgingHeaders.forEach(function (obj) {- var bridgingHeaderPath = path.basename(obj.src);+ bridgingHeaders.forEach(obj => {+ const bridgingHeaderPath = path.basename(obj.src);bridgingHeaderFile.addHeader(plugin.id, bridgingHeaderPath);});bridgingHeaderFile.write();}}})- .then(function () {+ .then(() => {if (plugin != null) {- var podSpecs = plugin.getPodSpecs ? plugin.getPodSpecs(self.platform) : [];- var frameworkTags = plugin.getFrameworks(self.platform);- var frameworkPods = frameworkTags.filter(function (obj) {- return (obj.type === 'podspec');- });- return self.addPodSpecs(plugin, podSpecs, frameworkPods);+ const podSpecs = plugin.getPodSpecs ? plugin.getPodSpecs(this.platform) : [];+ const frameworkTags = plugin.getFrameworks(this.platform);+ const frameworkPods = frameworkTags.filter(obj => obj.type === 'podspec');+ return this.addPodSpecs(plugin, podSpecs, frameworkPods, installOptions);}})- // CB-11022 return non-falsy value to indicate- // that there is no need to run prepare after- .thenResolve(true);+ // CB-11022 Return truthy value to prevent running prepare after+ .then(() => true);};/**@@ -292,44 +296,38 @@ Api.prototype.addPlugin = function (plugin, installOptions) {* CordovaError instance.*/Api.prototype.removePlugin = function (plugin, uninstallOptions) {- var xcodeproj = projectFile.parse(this.locations);- var self = this;+ const xcodeproj = projectFile.parse(this.locations);- return PluginManager.get(self.platform, self.locations, xcodeproj)+ return PluginManager.get(this.platform, this.locations, xcodeproj).removePlugin(plugin, uninstallOptions)- .then(function () {+ .then(() => {if (plugin != null) {- var headerTags = plugin.getHeaderFiles(self.platform);- var bridgingHeaders = headerTags.filter(function (obj) {- return (obj.type === 'BridgingHeader');- });+ const headerTags = plugin.getHeaderFiles(this.platform);+ const bridgingHeaders = headerTags.filter(obj => obj.type === 'BridgingHeader');if (bridgingHeaders.length > 0) {- var project_dir = self.locations.root;- var project_name = self.locations.xcodeCordovaProj.split('/').pop();- var BridgingHeader = require('./lib/BridgingHeader').BridgingHeader;- var bridgingHeaderFile = new BridgingHeader(path.join(project_dir, project_name, 'Bridging-Header.h'));+ const project_dir = this.locations.root;+ const project_name = this.locations.xcodeCordovaProj.split('/').pop();+ const BridgingHeader = require('./lib/BridgingHeader').BridgingHeader;+ const bridgingHeaderFile = new BridgingHeader(path.join(project_dir, project_name, 'Bridging-Header.h'));events.emit('verbose', 'Removing Bridging-Headers since the plugin contained <header-file> with type="BridgingHeader"');- bridgingHeaders.forEach(function (obj) {- var bridgingHeaderPath = path.basename(obj.src);+ bridgingHeaders.forEach(obj => {+ const bridgingHeaderPath = path.basename(obj.src);bridgingHeaderFile.removeHeader(plugin.id, bridgingHeaderPath);});bridgingHeaderFile.write();}}})- .then(function () {+ .then(() => {if (plugin != null) {- var podSpecs = plugin.getPodSpecs ? plugin.getPodSpecs(self.platform) : [];- var frameworkTags = plugin.getFrameworks(self.platform);- var frameworkPods = frameworkTags.filter(function (obj) {- return (obj.type === 'podspec');- });- return self.removePodSpecs(plugin, podSpecs, frameworkPods);+ const podSpecs = plugin.getPodSpecs ? plugin.getPodSpecs(this.platform) : [];+ const frameworkTags = plugin.getFrameworks(this.platform);+ const frameworkPods = frameworkTags.filter(obj => obj.type === 'podspec');+ return this.removePodSpecs(plugin, podSpecs, frameworkPods, uninstallOptions);}})- // CB-11022 return non-falsy value to indicate- // that there is no need to run prepare after- .thenResolve(true);+ // CB-11022 Return truthy value to prevent running prepare after+ .then(() => true);};/**@@ -337,34 +335,32 @@ Api.prototype.removePlugin = function (plugin, uninstallOptions) {** @param {PluginInfo} plugin A PluginInfo instance that represents plugin* that will be installed.- * @param {Object} podSpecs: the return value of plugin.getPodSpecs(self.platform)+ * @param {Object} podSpecs: the return value of plugin.getPodSpecs(this.platform)* @param {Object} frameworkPods: framework tags object with type === 'podspec'* @return {Promise} Return a promise*/-Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods) {- var self = this;-- var project_dir = self.locations.root;- var project_name = self.locations.xcodeCordovaProj.split('/').pop();- var minDeploymentTarget = self.getPlatformInfo().projectConfig.getPreference('deployment-target', 'ios');+Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods, installOptions) {+ const project_dir = this.locations.root;+ const project_name = this.locations.xcodeCordovaProj.split('/').pop();+ const minDeploymentTarget = this.getPlatformInfo().projectConfig.getPreference('deployment-target', 'ios');- var Podfile = require('./lib/Podfile').Podfile;- var PodsJson = require('./lib/PodsJson').PodsJson;- var podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));- var podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name, minDeploymentTarget);+ const Podfile = require('./lib/Podfile').Podfile;+ const PodsJson = require('./lib/PodsJson').PodsJson;+ const podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));+ const podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name, minDeploymentTarget);if (podSpecs.length) {events.emit('verbose', 'Adding pods since the plugin contained <podspecs>');- podSpecs.forEach(function (obj) {+ podSpecs.forEach(obj => {// declarations- Object.keys(obj.declarations).forEach(function (key) {+ Object.keys(obj.declarations).forEach(key => {if (obj.declarations[key] === 'true') {- var declaration = Podfile.proofDeclaration(key);- var podJson = {- declaration: declaration+ const declaration = Podfile.proofDeclaration(key);+ const podJson = {+ declaration};- var val = podsjsonFile.getDeclaration(declaration);+ const val = podsjsonFile.getDeclaration(declaration);if (val) {podsjsonFile.incrementDeclaration(declaration);} else {@@ -375,11 +371,11 @@ Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods) {}});// sources- Object.keys(obj.sources).forEach(function (key) {- var podJson = {+ Object.keys(obj.sources).forEach(key => {+ const podJson = {source: obj.sources[key].source};- var val = podsjsonFile.getSource(key);+ const val = podsjsonFile.getSource(key);if (val) {podsjsonFile.incrementSource(key);} else {@@ -389,11 +385,14 @@ Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods) {}});// libraries- Object.keys(obj.libraries).forEach(function (key) {- var podJson = Object.assign({}, obj.libraries[key]);- var val = podsjsonFile.getLibrary(key);+ Object.keys(obj.libraries).forEach(key => {+ const podJson = Object.assign({}, obj.libraries[key]);+ if (podJson.spec) {+ podJson.spec = getVariableSpec(podJson.spec, installOptions);+ }+ const val = podsjsonFile.getLibrary(key);if (val) {- events.emit('warn', plugin.id + ' depends on ' + podJson.name + ', which may conflict with another plugin. ' + podJson.name + '@' + val.spec + ' is already installed and was not overwritten.');+ events.emit('warn', `${plugin.id} depends on ${podJson.name}, which may conflict with another plugin. ${podJson.name}@${val.spec} is already installed and was not overwritten.`);podsjsonFile.incrementLibrary(key);} else {podJson.count = 1;@@ -401,24 +400,24 @@ Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods) {podfileFile.addSpec(podJson.name, podJson);}});-});}if (frameworkPods.length) {events.emit('warn', '"framework" tag with type "podspec" is deprecated and will be removed. Please use the "podspec" tag.');events.emit('verbose', 'Adding pods since the plugin contained <framework>(s) with type="podspec"');- frameworkPods.forEach(function (obj) {- var podJson = {+ frameworkPods.forEach(obj => {+ const spec = getVariableSpec(obj.spec, installOptions);+ const podJson = {name: obj.src,type: obj.type,- spec: obj.spec+ spec};- var val = podsjsonFile.getLibrary(podJson.name);+ const val = podsjsonFile.getLibrary(podJson.name);if (val) { // foundif (podJson.spec !== val.spec) { // exists, different spec, print warning- events.emit('warn', plugin.id + ' depends on ' + podJson.name + '@' + podJson.spec + ', which conflicts with another plugin. ' + podJson.name + '@' + val.spec + ' is already installed and was not overwritten.');+ events.emit('warn', `${plugin.id} depends on ${podJson.name}@${podJson.spec}, which conflicts with another plugin. ${podJson.name}@${val.spec} is already installed and was not overwritten.`);}// increment count, but don't add in Podfile because it already existspodsjsonFile.incrementLibrary(podJson.name);@@ -439,17 +438,15 @@ Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods) {if (podfileFile.isDirty()) {podfileFile.write();events.emit('verbose', 'Running `pod install` (to install plugins)');- projectFile.purgeProjectFileCache(self.locations.root);+ projectFile.purgeProjectFileCache(this.locations.root);return podfileFile.install(check_reqs.check_cocoapods)- .then(function () {- return self.setSwiftVersionForCocoaPodsLibraries(podsjsonFile);- });+ .then(() => this.setSwiftVersionForCocoaPodsLibraries(podsjsonFile));} else {events.emit('verbose', 'Podfile unchanged, skipping `pod install`');}}- return Q.when();+ return Promise.resolve();};/**@@ -457,37 +454,35 @@ Api.prototype.addPodSpecs = function (plugin, podSpecs, frameworkPods) {** @param {PluginInfo} plugin A PluginInfo instance that represents plugin* that will be installed.- * @param {Object} podSpecs: the return value of plugin.getPodSpecs(self.platform)+ * @param {Object} podSpecs: the return value of plugin.getPodSpecs(this.platform)* @param {Object} frameworkPods: framework tags object with type === 'podspec'* @return {Promise} Return a promise*/-Api.prototype.removePodSpecs = function (plugin, podSpecs, frameworkPods) {- var self = this;-- var project_dir = self.locations.root;- var project_name = self.locations.xcodeCordovaProj.split('/').pop();+Api.prototype.removePodSpecs = function (plugin, podSpecs, frameworkPods, uninstallOptions) {+ const project_dir = this.locations.root;+ const project_name = this.locations.xcodeCordovaProj.split('/').pop();- var Podfile = require('./lib/Podfile').Podfile;- var PodsJson = require('./lib/PodsJson').PodsJson;- var podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));- var podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name);+ const Podfile = require('./lib/Podfile').Podfile;+ const PodsJson = require('./lib/PodsJson').PodsJson;+ const podsjsonFile = new PodsJson(path.join(project_dir, PodsJson.FILENAME));+ const podfileFile = new Podfile(path.join(project_dir, Podfile.FILENAME), project_name);if (podSpecs.length) {events.emit('verbose', 'Adding pods since the plugin contained <podspecs>');- podSpecs.forEach(function (obj) {+ podSpecs.forEach(obj => {// declarations- Object.keys(obj.declarations).forEach(function (key) {+ Object.keys(obj.declarations).forEach(key => {if (obj.declarations[key] === 'true') {- var declaration = Podfile.proofDeclaration(key);- var podJson = {- declaration: declaration+ const declaration = Podfile.proofDeclaration(key);+ const podJson = {+ declaration};- var val = podsjsonFile.getDeclaration(declaration);+ const val = podsjsonFile.getDeclaration(declaration);if (val) {podsjsonFile.decrementDeclaration(declaration);} else {- var message = util.format('plugin \"%s\" declaration \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.declaration); /* eslint no-useless-escape : 0 */+ const message = util.format('plugin \"%s\" declaration \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.declaration); /* eslint no-useless-escape : 0 */events.emit('verbose', message);}if (!val || val.count === 0) {@@ -496,15 +491,15 @@ Api.prototype.removePodSpecs = function (plugin, podSpecs, frameworkPods) {}});// sources- Object.keys(obj.sources).forEach(function (key) {- var podJson = {+ Object.keys(obj.sources).forEach(key => {+ const podJson = {source: obj.sources[key].source};- var val = podsjsonFile.getSource(key);+ const val = podsjsonFile.getSource(key);if (val) {podsjsonFile.decrementSource(key);} else {- var message = util.format('plugin \"%s\" source \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.source); /* eslint no-useless-escape : 0 */+ const message = util.format('plugin \"%s\" source \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.source); /* eslint no-useless-escape : 0 */events.emit('verbose', message);}if (!val || val.count === 0) {@@ -512,38 +507,41 @@ Api.prototype.removePodSpecs = function (plugin, podSpecs, frameworkPods) {}});// libraries- Object.keys(obj.libraries).forEach(function (key) {- var podJson = Object.assign({}, obj.libraries[key]);- var val = podsjsonFile.getLibrary(key);+ Object.keys(obj.libraries).forEach(key => {+ const podJson = Object.assign({}, obj.libraries[key]);+ if (podJson.spec) {+ podJson.spec = getVariableSpec(podJson.spec, uninstallOptions);+ }+ const val = podsjsonFile.getLibrary(key);if (val) {podsjsonFile.decrementLibrary(key);} else {- var message = util.format('plugin \"%s\" podspec \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.name); /* eslint no-useless-escape : 0 */+ const message = util.format('plugin \"%s\" podspec \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.name); /* eslint no-useless-escape : 0 */events.emit('verbose', message);}if (!val || val.count === 0) {podfileFile.removeSpec(podJson.name);}});-});}if (frameworkPods.length) {events.emit('warn', '"framework" tag with type "podspec" is deprecated and will be removed. Please use the "podspec" tag.');events.emit('verbose', 'Adding pods since the plugin contained <framework>(s) with type=\"podspec\"'); /* eslint no-useless-escape : 0 */- frameworkPods.forEach(function (obj) {- var podJson = {+ frameworkPods.forEach(obj => {+ const spec = getVariableSpec(obj.spec, uninstallOptions);+ const podJson = {name: obj.src,type: obj.type,- spec: obj.spec+ spec};- var val = podsjsonFile.getLibrary(podJson.name);+ const val = podsjsonFile.getLibrary(podJson.name);if (val) { // found, decrement countpodsjsonFile.decrementLibrary(podJson.name);} else { // not found (perhaps a sync error)- var message = util.format('plugin \"%s\" podspec \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.name); /* eslint no-useless-escape : 0 */+ const message = util.format('plugin \"%s\" podspec \"%s\" does not seem to be in pods.json, nothing to remove. Will attempt to remove from Podfile.', plugin.id, podJson.name); /* eslint no-useless-escape : 0 */events.emit('verbose', message);}@@ -561,14 +559,12 @@ Api.prototype.removePodSpecs = function (plugin, podSpecs, frameworkPods) {events.emit('verbose', 'Running `pod install` (to uninstall pods)');return podfileFile.install(check_reqs.check_cocoapods)- .then(function () {- return self.setSwiftVersionForCocoaPodsLibraries(podsjsonFile);- });+ .then(() => this.setSwiftVersionForCocoaPodsLibraries(podsjsonFile));} else {events.emit('verbose', 'Podfile unchanged, skipping `pod install`');}}- return Q.when();+ return Promise.resolve();};/**@@ -578,42 +574,36 @@ Api.prototype.removePodSpecs = function (plugin, podSpecs, frameworkPods) {*/Api.prototype.setSwiftVersionForCocoaPodsLibraries = function (podsjsonFile) {- var self = this;- var __dirty = false;- return check_reqs.check_cocoapods().then(function (toolOptions) {+ let __dirty = false;+ return check_reqs.check_cocoapods().then(toolOptions => {if (toolOptions.ignore) {events.emit('verbose', '=== skip Swift Version Settings For Cocoapods Libraries');} else {- var podPbxPath = path.join(self.root, 'Pods', 'Pods.xcodeproj', 'project.pbxproj');- var podXcodeproj = xcode.project(podPbxPath);+ const podPbxPath = path.join(this.root, 'Pods', 'Pods.xcodeproj', 'project.pbxproj');+ const podXcodeproj = xcode.project(podPbxPath);podXcodeproj.parseSync();- var podTargets = podXcodeproj.pbxNativeTargetSection();- var podConfigurationList = podXcodeproj.pbxXCConfigurationList();- var podConfigs = podXcodeproj.pbxXCBuildConfigurationSection();-- var libraries = podsjsonFile.getLibraries();- Object.keys(libraries).forEach(function (key) {- var podJson = libraries[key];- var name = podJson.name;- var swiftVersion = podJson['swift-version'];+ const podTargets = podXcodeproj.pbxNativeTargetSection();+ const podConfigurationList = podXcodeproj.pbxXCConfigurationList();+ const podConfigs = podXcodeproj.pbxXCBuildConfigurationSection();++ const libraries = podsjsonFile.getLibraries();+ Object.keys(libraries).forEach(key => {+ const podJson = libraries[key];+ const name = podJson.name;+ const swiftVersion = podJson['swift-version'];if (swiftVersion) {__dirty = true;- Object.keys(podTargets).filter(function (targetKey) {- return podTargets[targetKey].productName === name;- }).map(function (targetKey) {- return podTargets[targetKey].buildConfigurationList;- }).map(function (buildConfigurationListId) {- return podConfigurationList[buildConfigurationListId];- }).map(function (buildConfigurationList) {- return buildConfigurationList.buildConfigurations;- }).reduce(function (acc, buildConfigurations) {- return acc.concat(buildConfigurations);- }, []).map(function (buildConfiguration) {- return buildConfiguration.value;- }).forEach(function (buildId) {- __dirty = true;- podConfigs[buildId].buildSettings['SWIFT_VERSION'] = swiftVersion;- });+ Object.keys(podTargets)+ .filter(targetKey => podTargets[targetKey].productName === name)+ .map(targetKey => podTargets[targetKey].buildConfigurationList)+ .map(buildConfigurationListId => podConfigurationList[buildConfigurationListId])+ .map(buildConfigurationList => buildConfigurationList.buildConfigurations)+ .reduce((acc, buildConfigurations) => acc.concat(buildConfigurations), [])+ .map(buildConfiguration => buildConfiguration.value)+ .forEach(buildId => {+ __dirty = true;+ podConfigs[buildId].buildSettings.SWIFT_VERSION = swiftVersion;+ });}});if (__dirty) {@@ -656,11 +646,8 @@ Api.prototype.setSwiftVersionForCocoaPodsLibraries = function (podsjsonFile) {* CordovaError instance.*/Api.prototype.build = function (buildOptions) {- var self = this;return check_reqs.run()- .then(function () {- return require('./lib/build').run.call(self, buildOptions);- });+ .then(() => require('./lib/build').run.call(this, buildOptions));};/**@@ -676,11 +663,8 @@ Api.prototype.build = function (buildOptions) {* successfully, or rejected with CordovaError.*/Api.prototype.run = function (runOptions) {- var self = this;return check_reqs.run()- .then(function () {- return require('./lib/run').run.call(self, runOptions);- });+ .then(() => require('./lib/run').run.call(this, runOptions));};/**@@ -690,14 +674,9 @@ Api.prototype.run = function (runOptions) {* CordovaError.*/Api.prototype.clean = function (cleanOptions) {- var self = this;return check_reqs.run()- .then(function () {- return require('./lib/clean').run.call(self, cleanOptions);- })- .then(function () {- return require('./lib/prepare').clean.call(self, cleanOptions);- });+ .then(() => require('./lib/clean').run.call(this, cleanOptions))+ .then(() => require('./lib/prepare').clean.call(this, cleanOptions));};/**@@ -712,4 +691,8 @@ Api.prototype.requirements = function () {return check_reqs.check_all();};+Api.version = function () {+ return VERSION;+};+module.exports = Api;diff --git a/cordova/platforms/ios/cordova/apple_ios_version b/cordova/platforms/ios/cordova/apple_ios_versionindex 754dd3910..5fee9e852 100755--- a/cordova/platforms/ios/cordova/apple_ios_version+++ b/cordova/platforms/ios/cordova/apple_ios_version@@ -21,7 +21,7 @@var versions = require('./lib/versions.js');-versions.get_apple_ios_version().done(null, function (err) {+versions.get_apple_ios_version().catch(err => {console.log(err);process.exit(2);});diff --git a/cordova/platforms/ios/cordova/apple_osx_version b/cordova/platforms/ios/cordova/apple_osx_versionindex 5b4a8b853..062d8b7fb 100755--- a/cordova/platforms/ios/cordova/apple_osx_version+++ b/cordova/platforms/ios/cordova/apple_osx_version@@ -21,7 +21,7 @@var versions = require('./lib/versions.js');-versions.get_apple_osx_version().done(null, function (err) {+versions.get_apple_osx_version().catch(err => {console.log(err);process.exit(2);});diff --git a/cordova/platforms/ios/cordova/apple_xcode_version b/cordova/platforms/ios/cordova/apple_xcode_versionindex 296332910..4656e3851 100755--- a/cordova/platforms/ios/cordova/apple_xcode_version+++ b/cordova/platforms/ios/cordova/apple_xcode_version@@ -21,9 +21,12 @@var versions = require('./lib/versions.js');-versions.get_apple_xcode_version().done(function (version) {- console.log(version);-}, function (err) {- console.error(err);- process.exit(2);-});+versions.get_apple_xcode_version().then(+ version => {+ console.log(version);+ },+ err => {+ console.error(err);+ process.exit(2);+ }+);diff --git a/cordova/platforms/ios/cordova/build b/cordova/platforms/ios/cordova/buildindex e795d13dd..f4b0d9a04 100755--- a/cordova/platforms/ios/cordova/build+++ b/cordova/platforms/ios/cordova/build@@ -31,33 +31,36 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=// Parse argumentsvar buildOpts = nopt({- 'verbose': Boolean,- 'silent': Boolean,- 'archs': String,- 'debug': Boolean,- 'release': Boolean,- 'device': Boolean,- 'emulator': Boolean,- 'codeSignIdentity': String,- 'codeSignResourceRules': String,- 'provisioningProfile': String,- 'automaticProvisioning': Boolean,- 'developmentTeam': String,- 'packageType': String,- 'buildConfig': String,- 'buildFlag': [String, Array],- 'noSign': Boolean-}, { '-r': '--release', 'd': '--verbose' }, args);+ verbose: Boolean,+ silent: Boolean,+ archs: String,+ debug: Boolean,+ release: Boolean,+ device: Boolean,+ emulator: Boolean,+ codeSignIdentity: String,+ codeSignResourceRules: String,+ provisioningProfile: String,+ automaticProvisioning: Boolean,+ developmentTeam: String,+ packageType: String,+ buildConfig: String,+ buildFlag: [String, Array],+ noSign: Boolean+}, { '-r': '--release', d: '--verbose' }, args);// Make buildOptions compatible with PlatformApi build method specbuildOpts.argv = buildOpts.argv.remain;require('./loggingHelper').adjustLoggerLevel(buildOpts);-new Api().build(buildOpts).done(function () {- console.log('** BUILD SUCCEEDED **');-}, function (err) {- var errorMessage = (err && err.stack) ? err.stack : err;- console.error(errorMessage);- process.exit(2);-});+new Api().build(buildOpts).then(+ () => {+ console.log('** BUILD SUCCEEDED **');+ },+ err => {+ var errorMessage = (err && err.stack) ? err.stack : err;+ console.error(errorMessage);+ process.exit(2);+ }+);diff --git a/cordova/platforms/ios/cordova/check_reqs b/cordova/platforms/ios/cordova/check_reqsindex 8f1d5ca5c..e46db6c82 100755--- a/cordova/platforms/ios/cordova/check_reqs+++ b/cordova/platforms/ios/cordova/check_reqs@@ -25,7 +25,7 @@ var check_reqs = require('./lib/check_reqs');if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) > -1) {console.log('Usage: check_reqs or node check_reqs');} else {- check_reqs.run().done(null, function (err) {+ check_reqs.run().catch(err => {console.error('Failed to check requirements due to ' + err);process.exit(2);});diff --git a/cordova/platforms/ios/cordova/clean b/cordova/platforms/ios/cordova/cleanindex ccd4a56d5..f36a648e5 100755--- a/cordova/platforms/ios/cordova/clean+++ b/cordova/platforms/ios/cordova/clean@@ -29,9 +29,9 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=// Do some basic argument parsingvar opts = nopt({- 'verbose': Boolean,- 'silent': Boolean-}, { 'd': '--verbose' });+ verbose: Boolean,+ silent: Boolean+}, { d: '--verbose' });// Make buildOptions compatible with PlatformApi clean method specopts.argv = opts.argv.original;@@ -41,9 +41,12 @@ opts.noPrepare = true;require('./loggingHelper').adjustLoggerLevel(opts);-new Api().clean(opts).done(function () {- console.log('** CLEAN SUCCEEDED **');-}, function (err) {- console.error(err);- process.exit(2);-});+new Api().clean(opts).then(+ () => {+ console.log('** CLEAN SUCCEEDED **');+ },+ err => {+ console.error(err);+ process.exit(2);+ }+);diff --git a/cordova/platforms/ios/cordova/defaults.xml b/cordova/platforms/ios/cordova/defaults.xmlindex 77a0a0b30..8733ce39f 100755--- a/cordova/platforms/ios/cordova/defaults.xml+++ b/cordova/platforms/ios/cordova/defaults.xml@@ -27,7 +27,7 @@<preference name="DisallowOverscroll" value="false" /><preference name="EnableViewportScale" value="false" /><preference name="KeyboardDisplayRequiresUserAction" value="true" />- <preference name="MediaPlaybackRequiresUserAction" value="false" />+ <preference name="MediaTypesRequiringUserActionForPlayback" value="none" /><preference name="SuppressesIncrementalRendering" value="false" /><preference name="SuppressesLongPressGesture" value="false" /><preference name="Suppresses3DTouchGesture" value="false" />@@ -36,6 +36,12 @@<preference name="PaginationBreakingMode" value="page" /> <!-- page, column --><preference name="PaginationMode" value="unpaginated" /> <!-- unpaginated, leftToRight, topToBottom, bottomToTop, rightToLeft -->+ <feature name="CDVWebViewEngine">+ <param name="ios-package" value="CDVWebViewEngine" />+ </feature>+ <feature name="LaunchScreen">+ <param name="ios-package" value="CDVLaunchScreen"/>+ </feature><feature name="LocalStorage"><param name="ios-package" value="CDVLocalStorage"/></feature>diff --git a/cordova/platforms/ios/cordova/lib/BridgingHeader.js b/cordova/platforms/ios/cordova/lib/BridgingHeader.jsindex 319d3feb8..9e200b508 100755--- a/cordova/platforms/ios/cordova/lib/BridgingHeader.js+++ b/cordova/platforms/ios/cordova/lib/BridgingHeader.js@@ -18,8 +18,8 @@*/'use strict';-var fs = require('fs');-var CordovaError = require('cordova-common').CordovaError;+const fs = require('fs-extra');+const CordovaError = require('cordova-common').CordovaError;function BridgingHeader (bridgingHeaderPath) {this.path = bridgingHeaderPath;@@ -31,7 +31,7 @@ function BridgingHeader (bridgingHeaderPath) {}BridgingHeader.prototype.addHeader = function (plugin_id, header_path) {- this.bridgingHeaders.push({ type: 'code', code: '#import "' + header_path + '"\n' });+ this.bridgingHeaders.push({ type: 'code', code: `#import "${header_path}"\n` });};BridgingHeader.prototype.removeHeader = function (plugin_id, header_path) {@@ -40,7 +40,7 @@ BridgingHeader.prototype.removeHeader = function (plugin_id, header_path) {return true;}if (line.type === 'code') {- var re = new RegExp('#import\\s+"' + preg_quote(header_path) + '"(\\s*|\\s.+)(\\n|$)');+ const re = new RegExp(`#import\\s+"${preg_quote(header_path)}"(\\s*|\\s.+)(\\n|$)`);if (re.test(line.code)) {this.found = true;return false;@@ -51,27 +51,25 @@ BridgingHeader.prototype.removeHeader = function (plugin_id, header_path) {};BridgingHeader.prototype.write = function () {- var text = this.__stringifyForBridgingHeader(this.bridgingHeaders);+ const text = this.__stringifyForBridgingHeader(this.bridgingHeaders);fs.writeFileSync(this.path, text, 'utf8');};BridgingHeader.prototype.__stringifyForBridgingHeader = function (bridgingHeaders) {- return bridgingHeaders.map(function (obj) {- return obj.code;- }).join('');+ return bridgingHeaders.map(obj => obj.code).join('');};BridgingHeader.prototype.__parseForBridgingHeader = function (text) {- var i = 0;- var list = [];- var type = 'code';- var start = 0;+ let i = 0;+ const list = [];+ let type = 'code';+ let start = 0;while (i < text.length) {switch (type) {case 'comment':if (i + 1 < text.length && text[i] === '*' && text[i + 1] === '/') {i += 2;- list.push({ type: type, code: text.slice(start, i) });+ list.push({ type, code: text.slice(start, i) });type = 'code';start = i;} else {@@ -81,7 +79,7 @@ BridgingHeader.prototype.__parseForBridgingHeader = function (text) {case 'line-comment':if (i < text.length && text[i] === '\n') {i += 1;- list.push({ type: type, code: text.slice(start, i) });+ list.push({ type, code: text.slice(start, i) });type = 'code';start = i;} else {@@ -92,19 +90,19 @@ BridgingHeader.prototype.__parseForBridgingHeader = function (text) {default:if (i + 1 < text.length && text[i] === '/' && text[i + 1] === '*') { // commentif (start < i) {- list.push({ type: type, code: text.slice(start, i) });+ list.push({ type, code: text.slice(start, i) });}type = 'comment';start = i;} else if (i + 1 < text.length && text[i] === '/' && text[i + 1] === '/') { // line commentif (start < i) {- list.push({ type: type, code: text.slice(start, i) });+ list.push({ type, code: text.slice(start, i) });}type = 'line-comment';start = i;} else if (i < text.length && text[i] === '\n') {i += 1;- list.push({ type: type, code: text.slice(start, i) });+ list.push({ type, code: text.slice(start, i) });start = i;} else {i += 1;@@ -113,13 +111,13 @@ BridgingHeader.prototype.__parseForBridgingHeader = function (text) {}}if (start < i) {- list.push({ type: type, code: text.slice(start, i) });+ list.push({ type, code: text.slice(start, i) });}return list;};function preg_quote (str, delimiter) {- return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');+ return (`${str}`).replace(new RegExp(`[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\${delimiter || ''}-]`, 'g'), '\\$&');}module.exports.BridgingHeader = BridgingHeader;diff --git a/cordova/platforms/ios/cordova/lib/Podfile.js b/cordova/platforms/ios/cordova/lib/Podfile.jsindex 7106ff663..f16729744 100755--- a/cordova/platforms/ios/cordova/lib/Podfile.js+++ b/cordova/platforms/ios/cordova/lib/Podfile.js@@ -18,13 +18,14 @@*/'use strict';-var fs = require('fs');-var path = require('path');-var util = require('util');-var events = require('cordova-common').events;-var Q = require('q');-var superspawn = require('cordova-common').superspawn;-var CordovaError = require('cordova-common').CordovaError;+const fs = require('fs-extra');+const path = require('path');+const util = require('util');+const {+ CordovaError,+ events,+ superspawn: { spawn }+} = require('cordova-common');Podfile.FILENAME = 'Podfile';Podfile.declarationRegexpMap = {@@ -39,7 +40,7 @@ function Podfile (podFilePath, projectName, minDeploymentTarget) {this.path = podFilePath;this.projectName = projectName;- this.minDeploymentTarget = minDeploymentTarget || '10.0';+ this.minDeploymentTarget = minDeploymentTarget || '11.0';this.contents = null;this.sources = null;this.declarations = null;@@ -47,7 +48,7 @@ function Podfile (podFilePath, projectName, minDeploymentTarget) {this.__dirty = false;// check whether it is named Podfile- var filename = this.path.split(path.sep).pop();+ const filename = this.path.split(path.sep).pop();if (filename !== Podfile.FILENAME) {throw new CordovaError(util.format('Podfile: The file at %s is not `%s`.', this.path, Podfile.FILENAME));}@@ -64,7 +65,7 @@ function Podfile (podFilePath, projectName, minDeploymentTarget) {} else {events.emit('verbose', 'Podfile found in platforms/ios');// parse for pods- var fileText = fs.readFileSync(this.path, 'utf8');+ const fileText = fs.readFileSync(this.path, 'utf8');this.declarations = this.__parseForDeclarations(fileText);this.sources = this.__parseForSources(fileText);this.pods = this.__parseForPods(fileText);@@ -73,14 +74,14 @@ function Podfile (podFilePath, projectName, minDeploymentTarget) {Podfile.prototype.__parseForDeclarations = function (text) {// split by \n- var arr = text.split('\n');+ const arr = text.split('\n');- // getting lines between "platform :ios, '10.0'"" and "target 'HelloCordova'" do- var declarationsPreRE = new RegExp('platform :ios,\\s+\'[^\']+\'');- var declarationsPostRE = new RegExp('target\\s+\'[^\']+\'\\s+do');- var declarationRE = new RegExp('^\\s*[^#]');+ // getting lines between "platform :ios, '11.0'"" and "target 'HelloCordova'" do+ const declarationsPreRE = new RegExp('platform :ios,\\s+\'[^\']+\'');+ const declarationsPostRE = new RegExp('target\\s+\'[^\']+\'\\s+do');+ const declarationRE = new RegExp('^\\s*[^#]');- return arr.reduce(function (acc, line) {+ return arr.reduce((acc, line) => {switch (acc.state) {case 0:if (declarationsPreRE.exec(line)) {@@ -101,10 +102,8 @@ Podfile.prototype.__parseForDeclarations = function (text) {return acc;}, { state: 0, lines: [] }).lines- .filter(function (line) {- return declarationRE.exec(line);- })- .reduce(function (obj, line) {+ .filter(line => declarationRE.exec(line))+ .reduce((obj, line) => {obj[line] = line;return obj;}, {});@@ -112,18 +111,18 @@ Podfile.prototype.__parseForDeclarations = function (text) {Podfile.prototype.__parseForSources = function (text) {// split by \n- var arr = text.split('\n');+ const arr = text.split('\n');- var sourceRE = new RegExp('source \'(.*)\'');- return arr.filter(function (line) {- var m = sourceRE.exec(line);+ const sourceRE = new RegExp('source \'(.*)\'');+ return arr.filter(line => {+ const m = sourceRE.exec(line);return (m !== null);})- .reduce(function (obj, line) {- var m = sourceRE.exec(line);+ .reduce((obj, line) => {+ const m = sourceRE.exec(line);if (m !== null) {- var source = m[1];+ const source = m[1];obj[source] = source;}return obj;@@ -132,26 +131,26 @@ Podfile.prototype.__parseForSources = function (text) {Podfile.prototype.__parseForPods = function (text) {// split by \n- var arr = text.split('\n');+ const arr = text.split('\n');// aim is to match (space insignificant around the comma, comma optional):// pod 'Foobar', '1.2'// pod 'Foobar', 'abc 123 1.2'// pod 'PonyDebugger', :configurations => ['Debug', 'Beta']// var podRE = new RegExp('pod \'([^\']*)\'\\s*,?\\s*(.*)');- var podRE = new RegExp('pod \'([^\']*)\'\\s*(?:,\\s*\'([^\']*)\'\\s*)?,?\\s*(.*)');+ const podRE = new RegExp('pod \'([^\']*)\'\\s*(?:,\\s*\'([^\']*)\'\\s*)?,?\\s*(.*)');// only grab lines that don't have the pod spec'- return arr.filter(function (line) {- var m = podRE.exec(line);+ return arr.filter(line => {+ const m = podRE.exec(line);return (m !== null);})- .reduce(function (obj, line) {- var m = podRE.exec(line);+ .reduce((obj, line) => {+ const m = podRE.exec(line);if (m !== null) {- var podspec = {+ const podspec = {name: m[1]};if (m[2]) {@@ -168,12 +167,12 @@ Podfile.prototype.__parseForPods = function (text) {};Podfile.prototype.escapeSingleQuotes = function (string) {- return string.replace('\'', '\\\'');+ return string.replace(/'/g, '\\\'');};Podfile.prototype.getTemplate = function () {// Escaping possible ' in the project name- var projectName = this.escapeSingleQuotes(this.projectName);+ const projectName = this.escapeSingleQuotes(this.projectName);return util.format('# DO NOT MODIFY -- auto-generated by Apache Cordova\n' +'%s\n' +@@ -197,9 +196,9 @@ Podfile.prototype.addSpec = function (name, spec) {if (typeof spec === 'string') {if (spec.startsWith(':')) {- spec = { name: name, options: spec };+ spec = { name, options: spec };} else {- spec = { name: name, spec: spec };+ spec = { name, spec };}}@@ -262,9 +261,9 @@ Podfile.prototype.removeDeclaration = function (declaration) {events.emit('verbose', util.format('Removed source line for `%s`', declaration));};-Podfile.proofDeclaration = function (declaration) {- var list = Object.keys(Podfile.declarationRegexpMap).filter(function (key) {- var regexp = new RegExp(Podfile.declarationRegexpMap[key]);+Podfile.proofDeclaration = declaration => {+ const list = Object.keys(Podfile.declarationRegexpMap).filter(key => {+ const regexp = new RegExp(Podfile.declarationRegexpMap[key]);return regexp.test(declaration);});if (list.length > 0) {@@ -290,16 +289,15 @@ Podfile.prototype.destroy = function () {};Podfile.prototype.write = function () {- var text = this.getTemplate();- var self = this;+ let text = this.getTemplate();- var podsString =- Object.keys(this.pods).map(function (key) {- var name = key;- var json = self.pods[key];+ const podsString =+ Object.keys(this.pods).map(key => {+ const name = key;+ const json = this.pods[key];if (typeof json === 'string') { // compatibility for using framework tag.- var spec = json;+ const spec = json;if (spec.length) {if (spec.indexOf(':') === 0) {// don't quote it, it's a specification (starts with ':')@@ -312,18 +310,17 @@ Podfile.prototype.write = function () {return util.format('\tpod \'%s\'', name);}} else {- var list = ['\'' + name + '\''];+ const list = [`'${name}'`];if ('spec' in json && json.spec.length) {- list.push('\'' + json.spec + '\'');+ list.push(`'${json.spec}'`);}- var options = ['tag', 'branch', 'commit', 'git', 'podspec'].filter(function (tag) {- return tag in json;- }).map(function (tag) {- return ':' + tag + ' => \'' + json[tag] + '\'';- });+ let options = ['tag', 'branch', 'commit', 'git', 'podspec']+ .filter(tag => tag in json)+ .map(tag => `:${tag} => '${json[tag]}'`);+if ('configurations' in json) {- options.push(':configurations => [' + json['configurations'].split(',').map(function (conf) { return '\'' + conf.trim() + '\''; }).join(',') + ']');+ options.push(`:configurations => [${json.configurations.split(',').map(conf => `'${conf.trim()}'`).join(',')}]`);}if ('options' in json) {options = [json.options];@@ -335,15 +332,15 @@ Podfile.prototype.write = function () {}}).join('\n');- var sourcesString =- Object.keys(this.sources).map(function (key) {- var source = self.sources[key];+ const sourcesString =+ Object.keys(this.sources).map(key => {+ const source = this.sources[key];return util.format('source \'%s\'', source);}).join('\n');- var declarationString =- Object.keys(this.declarations).map(function (key) {- var declaration = self.declarations[key];+ const declarationString =+ Object.keys(this.declarations).map(key => {+ const declaration = this.declarations[key];return declaration;}).join('\n');@@ -365,46 +362,43 @@ Podfile.prototype.before_install = function (toolOptions) {toolOptions = toolOptions || {};// Template tokens in order: project name, project name, debug | release- var template =+ const template ='// DO NOT MODIFY -- auto-generated by Apache Cordova\n' +'#include "Pods/Target Support Files/Pods-%s/Pods-%s.%s.xcconfig"';- var debugContents = util.format(template, this.projectName, this.projectName, 'debug');- var releaseContents = util.format(template, this.projectName, this.projectName, 'release');+ const debugContents = util.format(template, this.projectName, this.projectName, 'debug');+ const releaseContents = util.format(template, this.projectName, this.projectName, 'release');- var debugConfigPath = path.join(this.path, '..', 'pods-debug.xcconfig');- var releaseConfigPath = path.join(this.path, '..', 'pods-release.xcconfig');+ const debugConfigPath = path.join(this.path, '..', 'pods-debug.xcconfig');+ const releaseConfigPath = path.join(this.path, '..', 'pods-release.xcconfig');fs.writeFileSync(debugConfigPath, debugContents, 'utf8');fs.writeFileSync(releaseConfigPath, releaseContents, 'utf8');- return Q.resolve(toolOptions);+ return Promise.resolve(toolOptions);};Podfile.prototype.install = function (requirementsCheckerFunction) {- var opts = {};+ const opts = {};opts.cwd = path.join(this.path, '..'); // parent path of this Podfileopts.stdio = 'pipe';opts.printCommand = true;- var first = true;- var self = this;+ let first = true;if (!requirementsCheckerFunction) {- requirementsCheckerFunction = Q();+ requirementsCheckerFunction = Promise.resolve();}return requirementsCheckerFunction()- .then(function (toolOptions) {- return self.before_install(toolOptions);- })- .then(function (toolOptions) {+ .then(toolOptions => this.before_install(toolOptions))+ .then(toolOptions => {if (toolOptions.ignore) {events.emit('verbose', '==== pod install start ====\n');events.emit('verbose', toolOptions.ignoreMessage);- return Q.resolve();+ return Promise.resolve();} else {- return superspawn.spawn('pod', ['install', '--verbose'], opts)- .progress(function (stdio) {+ return spawn('pod', ['install', '--verbose'], opts)+ .progress(stdio => {if (stdio.stderr) { console.error(stdio.stderr); }if (stdio.stdout) {if (first) {@@ -416,7 +410,7 @@ Podfile.prototype.install = function (requirementsCheckerFunction) {});}})- .then(function () { // done+ .then(() => { // doneevents.emit('verbose', '==== pod install end ====\n');});};diff --git a/cordova/platforms/ios/cordova/lib/PodsJson.js b/cordova/platforms/ios/cordova/lib/PodsJson.jsindex 25afbac36..598d9607b 100755--- a/cordova/platforms/ios/cordova/lib/PodsJson.js+++ b/cordova/platforms/ios/cordova/lib/PodsJson.js@@ -17,11 +17,11 @@under the License.*/-var fs = require('fs');-var path = require('path');-var util = require('util');-var events = require('cordova-common').events;-var CordovaError = require('cordova-common').CordovaError;+const fs = require('fs-extra');+const path = require('path');+const util = require('util');+const events = require('cordova-common').events;+const CordovaError = require('cordova-common').CordovaError;PodsJson.FILENAME = 'pods.json';PodsJson.LIBRARY = 'libraries';@@ -33,7 +33,7 @@ function PodsJson (podsJsonPath) {this.contents = null;this.__dirty = false;- var filename = this.path.split(path.sep).pop();+ const filename = this.path.split(path.sep).pop();if (filename !== PodsJson.FILENAME) {throw new CordovaError(util.format('PodsJson: The file at %s is not `%s`.', this.path, PodsJson.FILENAME));}@@ -46,7 +46,7 @@ function PodsJson (podsJsonPath) {} else {events.emit('verbose', 'pods.json found in platforms/ios');// load contents- var contents = fs.readFileSync(this.path, 'utf8');+ const contents = fs.readFileSync(this.path, 'utf8');this.contents = JSON.parse(contents);}this.__updateFormatIfNecessary();@@ -138,7 +138,7 @@ PodsJson.prototype.write = function () {};PodsJson.prototype.__increment = function (kind, name) {- var val = this.__get(kind, name);+ const val = this.__get(kind, name);if (val) {val.count++;}@@ -157,7 +157,7 @@ PodsJson.prototype.incrementDeclaration = function (name) {};PodsJson.prototype.__decrement = function (kind, name) {- var val = this.__get(kind, name);+ const val = this.__get(kind, name);if (val) {val.count--;if (val.count <= 0) {diff --git a/cordova/platforms/ios/cordova/lib/build.js b/cordova/platforms/ios/cordova/lib/build.jsindex f8d301dfd..a72038756 100755--- a/cordova/platforms/ios/cordova/lib/build.js+++ b/cordova/platforms/ios/cordova/lib/build.js@@ -17,30 +17,31 @@* under the License.*/-var Q = require('q');-var path = require('path');-var shell = require('shelljs');-var superspawn = require('cordova-common').superspawn;-var fs = require('fs');-var plist = require('plist');-var util = require('util');--var check_reqs = require('./check_reqs');-var projectFile = require('./projectFile');--var events = require('cordova-common').events;+const path = require('path');+const which = require('which');+const {+ CordovaError,+ events,+ superspawn: { spawn }+} = require('cordova-common');+const fs = require('fs-extra');+const plist = require('plist');+const util = require('util');++const check_reqs = require('./check_reqs');+const projectFile = require('./projectFile');// These are regular expressions to detect if the user is changing any of the built-in xcodebuildArgs/* eslint-disable no-useless-escape */-var buildFlagMatchers = {- 'workspace': /^\-workspace\s*(.*)/,- 'scheme': /^\-scheme\s*(.*)/,- 'configuration': /^\-configuration\s*(.*)/,- 'sdk': /^\-sdk\s*(.*)/,- 'destination': /^\-destination\s*(.*)/,- 'archivePath': /^\-archivePath\s*(.*)/,- 'configuration_build_dir': /^(CONFIGURATION_BUILD_DIR=.*)/,- 'shared_precomps_dir': /^(SHARED_PRECOMPS_DIR=.*)/+const buildFlagMatchers = {+ workspace: /^\-workspace\s*(.*)/,+ scheme: /^\-scheme\s*(.*)/,+ configuration: /^\-configuration\s*(.*)/,+ sdk: /^\-sdk\s*(.*)/,+ destination: /^\-destination\s*(.*)/,+ archivePath: /^\-archivePath\s*(.*)/,+ configuration_build_dir: /^(CONFIGURATION_BUILD_DIR=.*)/,+ shared_precomps_dir: /^(SHARED_PRECOMPS_DIR=.*)/};/* eslint-enable no-useless-escape */@@ -52,32 +53,14 @@ var buildFlagMatchers = {* @param {*} projectName*/function createProjectObject (projectPath, projectName) {- var locations = {+ const locations = {root: projectPath,- pbxproj: path.join(projectPath, projectName + '.xcodeproj', 'project.pbxproj')+ pbxproj: path.join(projectPath, `${projectName}.xcodeproj`, 'project.pbxproj')};return projectFile.parse(locations);}-/**- * Gets the resolved bundle identifier from a project.- * Resolves the variable set in INFO.plist, if any (simple case)- *- * @param {*} projectObject- */-function getBundleIdentifier (projectObject) {- var packageName = projectObject.getPackageName();- var bundleIdentifier = packageName;-- var variables = packageName.match(/\$\((\w+)\)/); // match $(VARIABLE), if any- if (variables && variables.length >= 2) {- bundleIdentifier = projectObject.xcode.getBuildProperty(variables[1]);- }-- return bundleIdentifier;-}-/*** Returns a promise that resolves to the default simulator target; the logic here* matches what `cordova emulate ios` does.@@ -88,13 +71,13 @@ function getBundleIdentifier (projectObject) {* @return {Promise}*/function getDefaultSimulatorTarget () {- return require('./list-emulator-build-targets').run()- .then(function (emulators) {- var targetEmulator;+ return require('./listEmulatorBuildTargets').run()+ .then(emulators => {+ let targetEmulator;if (emulators.length > 0) {targetEmulator = emulators[0];}- emulators.forEach(function (emulator) {+ emulators.forEach(emulator => {if (emulator.name.indexOf('iPhone') === 0) {targetEmulator = emulator;}@@ -103,62 +86,62 @@ function getDefaultSimulatorTarget () {});}-module.exports.run = function (buildOpts) {- var emulatorTarget = '';- var projectPath = path.join(__dirname, '..', '..');- var projectName = '';+module.exports.run = buildOpts => {+ let emulatorTarget = '';+ const projectPath = path.join(__dirname, '..', '..');+ let projectName = '';buildOpts = buildOpts || {};if (buildOpts.debug && buildOpts.release) {- return Q.reject('Cannot specify "debug" and "release" options together.');+ return Promise.reject(new CordovaError('Cannot specify "debug" and "release" options together.'));}if (buildOpts.device && buildOpts.emulator) {- return Q.reject('Cannot specify "device" and "emulator" options together.');+ return Promise.reject(new CordovaError('Cannot specify "device" and "emulator" options together.'));}if (buildOpts.buildConfig) {if (!fs.existsSync(buildOpts.buildConfig)) {- return Q.reject('Build config file does not exist: ' + buildOpts.buildConfig);+ return Promise.reject(new CordovaError(`Build config file does not exist: ${buildOpts.buildConfig}`));}- events.emit('log', 'Reading build config file: ' + path.resolve(buildOpts.buildConfig));- var contents = fs.readFileSync(buildOpts.buildConfig, 'utf-8');- var buildConfig = JSON.parse(contents.replace(/^\ufeff/, '')); // Remove BOM+ events.emit('log', `Reading build config file: ${path.resolve(buildOpts.buildConfig)}`);+ const contents = fs.readFileSync(buildOpts.buildConfig, 'utf-8');+ const buildConfig = JSON.parse(contents.replace(/^\ufeff/, '')); // Remove BOMif (buildConfig.ios) {- var buildType = buildOpts.release ? 'release' : 'debug';- var config = buildConfig.ios[buildType];+ const buildType = buildOpts.release ? 'release' : 'debug';+ const config = buildConfig.ios[buildType];if (config) {['codeSignIdentity', 'codeSignResourceRules', 'provisioningProfile', 'developmentTeam', 'packageType', 'buildFlag', 'iCloudContainerEnvironment', 'automaticProvisioning'].forEach(- function (key) {+ key => {buildOpts[key] = buildOpts[key] || config[key];});}}}- return require('./list-devices').run()- .then(function (devices) {+ return require('./listDevices').run()+ .then(devices => {if (devices.length > 0 && !(buildOpts.emulator)) {// we also explicitly set device flag in options as we pass// those parameters to other api (build as an example)buildOpts.device = true;return check_reqs.check_ios_deploy();}- }).then(function () {+ }).then(() => {// CB-12287: Determine the device we should target when building for a simulatorif (!buildOpts.device) {- var newTarget = buildOpts.target || '';+ let newTarget = buildOpts.target || '';if (newTarget) {// only grab the device name, not the runtime specifiernewTarget = newTarget.split(',')[0];}// a target was given to us, find the matching Xcode destination name- var promise = require('./list-emulator-build-targets').targetForSimIdentifier(newTarget);- return promise.then(function (theTarget) {+ const promise = require('./listEmulatorBuildTargets').targetForSimIdentifier(newTarget);+ return promise.then(theTarget => {if (!theTarget) {- return getDefaultSimulatorTarget().then(function (defaultTarget) {+ return getDefaultSimulatorTarget().then(defaultTarget => {emulatorTarget = defaultTarget.name;events.emit('warn', `No simulator found for "${newTarget}. Falling back to the default target.`);events.emit('log', `Building for "${emulatorTarget}" Simulator (${defaultTarget.identifier}, ${defaultTarget.simIdentifier}).`);@@ -171,29 +154,28 @@ module.exports.run = function (buildOpts) {}});}- }).then(function () {- return check_reqs.run();- }).then(function () {- return findXCodeProjectIn(projectPath);- }).then(function (name) {+ })+ .then(() => check_reqs.run())+ .then(() => findXCodeProjectIn(projectPath))+ .then(name => {projectName = name;- var extraConfig = '';+ let extraConfig = '';if (buildOpts.codeSignIdentity) {- extraConfig += 'CODE_SIGN_IDENTITY = ' + buildOpts.codeSignIdentity + '\n';- extraConfig += 'CODE_SIGN_IDENTITY[sdk=iphoneos*] = ' + buildOpts.codeSignIdentity + '\n';+ extraConfig += `CODE_SIGN_IDENTITY = ${buildOpts.codeSignIdentity}\n`;+ extraConfig += `CODE_SIGN_IDENTITY[sdk=iphoneos*] = ${buildOpts.codeSignIdentity}\n`;}if (buildOpts.codeSignResourceRules) {- extraConfig += 'CODE_SIGN_RESOURCE_RULES_PATH = ' + buildOpts.codeSignResourceRules + '\n';+ extraConfig += `CODE_SIGN_RESOURCE_RULES_PATH = ${buildOpts.codeSignResourceRules}\n`;}if (buildOpts.provisioningProfile) {- extraConfig += 'PROVISIONING_PROFILE = ' + buildOpts.provisioningProfile + '\n';+ extraConfig += `PROVISIONING_PROFILE = ${buildOpts.provisioningProfile}\n`;}if (buildOpts.developmentTeam) {- extraConfig += 'DEVELOPMENT_TEAM = ' + buildOpts.developmentTeam + '\n';+ extraConfig += `DEVELOPMENT_TEAM = ${buildOpts.developmentTeam}\n`;}function writeCodeSignStyle (value) {- var project = createProjectObject(projectPath, projectName);+ const project = createProjectObject(projectPath, projectName);events.emit('verbose', `Set CODE_SIGN_STYLE Build Property to ${value}.`);project.xcode.updateBuildProperty('CODE_SIGN_STYLE', value);@@ -211,31 +193,30 @@ module.exports.run = function (buildOpts) {writeCodeSignStyle('Automatic');}- return Q.nfcall(fs.writeFile, path.join(__dirname, '..', 'build-extras.xcconfig'), extraConfig, 'utf-8');- }).then(function () {- var configuration = buildOpts.release ? 'Release' : 'Debug';+ return fs.writeFile(path.join(__dirname, '..', 'build-extras.xcconfig'), extraConfig, 'utf-8');+ }).then(() => {+ const configuration = buildOpts.release ? 'Release' : 'Debug';- events.emit('log', 'Building project: ' + path.join(projectPath, projectName + '.xcworkspace'));- events.emit('log', '\tConfiguration: ' + configuration);- events.emit('log', '\tPlatform: ' + (buildOpts.device ? 'device' : 'emulator'));- events.emit('log', '\tTarget: ' + emulatorTarget);+ events.emit('log', `Building project: ${path.join(projectPath, `${projectName}.xcworkspace`)}`);+ events.emit('log', `\tConfiguration: ${configuration}`);+ events.emit('log', `\tPlatform: ${buildOpts.device ? 'device' : 'emulator'}`);+ events.emit('log', `\tTarget: ${emulatorTarget}`);- var buildOutputDir = path.join(projectPath, 'build', (buildOpts.device ? 'device' : 'emulator'));+ const buildOutputDir = path.join(projectPath, 'build', (buildOpts.device ? 'device' : 'emulator'));// remove the build/device folder before building- shell.rm('-rf', buildOutputDir);-- var xcodebuildArgs = getXcodeBuildArgs(projectName, projectPath, configuration, buildOpts.device, buildOpts.buildFlag, emulatorTarget, buildOpts.automaticProvisioning);- return superspawn.spawn('xcodebuild', xcodebuildArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });+ fs.removeSync(buildOutputDir);- }).then(function () {+ const xcodebuildArgs = getXcodeBuildArgs(projectName, projectPath, configuration, buildOpts.device, buildOpts.buildFlag, emulatorTarget, buildOpts.automaticProvisioning);+ return spawn('xcodebuild', xcodebuildArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });+ }).then(() => {if (!buildOpts.device || buildOpts.noSign) {return;}- var project = createProjectObject(projectPath, projectName);- var bundleIdentifier = getBundleIdentifier(project);- var exportOptions = { 'compileBitcode': false, 'method': 'development' };+ const project = createProjectObject(projectPath, projectName);+ const bundleIdentifier = project.getPackageName();+ const exportOptions = { compileBitcode: false, method: 'development' };if (buildOpts.packageType) {exportOptions.method = buildOpts.packageType;@@ -250,7 +231,7 @@ module.exports.run = function (buildOpts) {}if (buildOpts.provisioningProfile && bundleIdentifier) {- exportOptions.provisioningProfiles = { [ bundleIdentifier ]: String(buildOpts.provisioningProfile) };+ exportOptions.provisioningProfiles = { [bundleIdentifier]: String(buildOpts.provisioningProfile) };exportOptions.signingStyle = 'manual';}@@ -258,13 +239,13 @@ module.exports.run = function (buildOpts) {exportOptions.signingCertificate = buildOpts.codeSignIdentity;}- var exportOptionsPlist = plist.build(exportOptions);- var exportOptionsPath = path.join(projectPath, 'exportOptions.plist');+ const exportOptionsPlist = plist.build(exportOptions);+ const exportOptionsPath = path.join(projectPath, 'exportOptions.plist');- var buildOutputDir = path.join(projectPath, 'build', 'device');+ const buildOutputDir = path.join(projectPath, 'build', 'device');function checkSystemRuby () {- var ruby_cmd = shell.which('ruby');+ const ruby_cmd = which.sync('ruby', { nothrow: true });if (ruby_cmd !== '/usr/bin/ruby') {events.emit('warn', 'Non-system Ruby in use. This may cause packaging to fail.\n' +@@ -274,11 +255,11 @@ module.exports.run = function (buildOpts) {}function packageArchive () {- var xcodearchiveArgs = getXcodeArchiveArgs(projectName, projectPath, buildOutputDir, exportOptionsPath, buildOpts.automaticProvisioning);- return superspawn.spawn('xcodebuild', xcodearchiveArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });+ const xcodearchiveArgs = getXcodeArchiveArgs(projectName, projectPath, buildOutputDir, exportOptionsPath, buildOpts.automaticProvisioning);+ return spawn('xcodebuild', xcodearchiveArgs, { cwd: projectPath, printCommand: true, stdio: 'inherit' });}- return Q.nfcall(fs.writeFile, exportOptionsPath, exportOptionsPlist, 'utf-8')+ return fs.writeFile(exportOptionsPath, exportOptionsPlist, 'utf-8').then(checkSystemRuby).then(packageArchive);});@@ -291,20 +272,17 @@ module.exports.run = function (buildOpts) {*/function findXCodeProjectIn (projectPath) {// 'Searching for Xcode project in ' + projectPath);- var xcodeProjFiles = shell.ls(projectPath).filter(function (name) {- return path.extname(name) === '.xcodeproj';- });+ const xcodeProjFiles = fs.readdirSync(projectPath).filter(name => path.extname(name) === '.xcodeproj');if (xcodeProjFiles.length === 0) {- return Q.reject('No Xcode project found in ' + projectPath);+ return Promise.reject(new CordovaError(`No Xcode project found in ${projectPath}`));}if (xcodeProjFiles.length > 1) {- events.emit('warn', 'Found multiple .xcodeproj directories in \n' +- projectPath + '\nUsing first one');+ events.emit('warn', `Found multiple .xcodeproj directories in \n${projectPath}\nUsing first one`);}- var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');- return Q.resolve(projectName);+ const projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');+ return Promise.resolve(projectName);}module.exports.findXCodeProjectIn = findXCodeProjectIn;@@ -321,18 +299,17 @@ module.exports.findXCodeProjectIn = findXCodeProjectIn;* @return {Array} Array of arguments that could be passed directly to spawn method*/function getXcodeBuildArgs (projectName, projectPath, configuration, isDevice, buildFlags, emulatorTarget, autoProvisioning) {- var xcodebuildArgs;- var options;- var buildActions;- var settings;- var customArgs = {};+ let options;+ let buildActions;+ let settings;+ const customArgs = {};customArgs.otherFlags = [];if (buildFlags) {if (typeof buildFlags === 'string' || buildFlags instanceof String) {parseBuildFlag(buildFlags, customArgs);} else { // buildFlags is an Array of strings- buildFlags.forEach(function (flag) {+ buildFlags.forEach(flag => {parseBuildFlag(flag, customArgs);});}@@ -340,16 +317,16 @@ function getXcodeBuildArgs (projectName, projectPath, configuration, isDevice, bif (isDevice) {options = [- '-workspace', customArgs.workspace || projectName + '.xcworkspace',+ '-workspace', customArgs.workspace || `${projectName}.xcworkspace`,'-scheme', customArgs.scheme || projectName,'-configuration', customArgs.configuration || configuration,'-destination', customArgs.destination || 'generic/platform=iOS',- '-archivePath', customArgs.archivePath || projectName + '.xcarchive'+ '-archivePath', customArgs.archivePath || `${projectName}.xcarchive`];- buildActions = [ 'archive' ];+ buildActions = ['archive'];settings = [- customArgs.configuration_build_dir || 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'),- customArgs.shared_precomps_dir || 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')+ customArgs.configuration_build_dir || `CONFIGURATION_BUILD_DIR=${path.join(projectPath, 'build', 'device')}`,+ customArgs.shared_precomps_dir || `SHARED_PRECOMPS_DIR=${path.join(projectPath, 'build', 'sharedpch')}`];// Add other matched flags to otherFlags to let xcodebuild present an appropriate error.// This is preferable to just ignoring the flags that the user has passed in.@@ -362,16 +339,16 @@ function getXcodeBuildArgs (projectName, projectPath, configuration, isDevice, b}} else { // emulatoroptions = [- '-workspace', customArgs.project || projectName + '.xcworkspace',+ '-workspace', customArgs.project || `${projectName}.xcworkspace`,'-scheme', customArgs.scheme || projectName,'-configuration', customArgs.configuration || configuration,'-sdk', customArgs.sdk || 'iphonesimulator',- '-destination', customArgs.destination || 'platform=iOS Simulator,name=' + emulatorTarget+ '-destination', customArgs.destination || `platform=iOS Simulator,name=${emulatorTarget}`];- buildActions = [ 'build' ];+ buildActions = ['build'];settings = [- customArgs.configuration_build_dir || 'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'),- customArgs.shared_precomps_dir || 'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')+ customArgs.configuration_build_dir || `CONFIGURATION_BUILD_DIR=${path.join(projectPath, 'build', 'emulator')}`,+ customArgs.shared_precomps_dir || `SHARED_PRECOMPS_DIR=${path.join(projectPath, 'build', 'sharedpch')}`];// Add other matched flags to otherFlags to let xcodebuild present an appropriate error.// This is preferable to just ignoring the flags that the user has passed in.@@ -379,8 +356,8 @@ function getXcodeBuildArgs (projectName, projectPath, configuration, isDevice, bcustomArgs.otherFlags = customArgs.otherFlags.concat(['-archivePath', customArgs.archivePath]);}}- xcodebuildArgs = options.concat(buildActions).concat(settings).concat(customArgs.otherFlags);- return xcodebuildArgs;++ return options.concat(buildActions).concat(settings).concat(customArgs.otherFlags);}/**@@ -395,16 +372,16 @@ function getXcodeBuildArgs (projectName, projectPath, configuration, isDevice, bfunction getXcodeArchiveArgs (projectName, projectPath, outputPath, exportOptionsPath, autoProvisioning) {return ['-exportArchive',- '-archivePath', projectName + '.xcarchive',+ '-archivePath', `${projectName}.xcarchive`,'-exportOptionsPlist', exportOptionsPath,'-exportPath', outputPath].concat(autoProvisioning ? ['-allowProvisioningUpdates'] : []);}function parseBuildFlag (buildFlag, args) {- var matched;- for (var key in buildFlagMatchers) {- var found = buildFlag.match(buildFlagMatchers[key]);+ let matched;+ for (const key in buildFlagMatchers) {+ const found = buildFlag.match(buildFlagMatchers[key]);if (found) {matched = true;// found[0] is the whole match, found[1] is the first match in parentheses.diff --git a/cordova/platforms/ios/cordova/lib/check_reqs.js b/cordova/platforms/ios/cordova/lib/check_reqs.jsindex f786fc46a..33dc684fc 100755--- a/cordova/platforms/ios/cordova/lib/check_reqs.js+++ b/cordova/platforms/ios/cordova/lib/check_reqs.js@@ -19,37 +19,28 @@'use strict';-const Q = require('q');-const shell = require('shelljs');-const util = require('util');+const which = require('which');const versions = require('./versions');+const { CordovaError } = require('cordova-common');-const SUPPORTED_OS_PLATFORMS = [ 'darwin' ];+const SUPPORTED_OS_PLATFORMS = ['darwin'];const XCODEBUILD_MIN_VERSION = '9.0.0';const XCODEBUILD_NOT_FOUND_MESSAGE =- 'Please install version ' + XCODEBUILD_MIN_VERSION + ' or greater from App Store';+ `Please install version ${XCODEBUILD_MIN_VERSION} or greater from App Store`;const IOS_DEPLOY_MIN_VERSION = '1.9.2';const IOS_DEPLOY_NOT_FOUND_MESSAGE =- 'Please download, build and install version ' + IOS_DEPLOY_MIN_VERSION + ' or greater' +- ' from https://github.com/ios-control/ios-deploy into your path, or do \'npm install -g ios-deploy\'';--const COCOAPODS_MIN_VERSION = '1.0.1';-const COCOAPODS_NOT_FOUND_MESSAGE =- 'Please install version ' + COCOAPODS_MIN_VERSION + ' or greater from https://cocoapods.org/';-const COCOAPODS_NOT_SYNCED_MESSAGE =- 'The CocoaPods repo has not been synced yet, this will take a long time (approximately 500MB as of Sept 2016). Please run `pod setup` first to sync the repo.';-const COCOAPODS_SYNCED_MIN_SIZE = 475; // in megabytes-const COCOAPODS_SYNC_ERROR_MESSAGE =- 'The CocoaPods repo has been created, but there appears to be a sync error. The repo size should be at least ' + COCOAPODS_SYNCED_MIN_SIZE + '. Please run `pod setup --verbose` to sync the repo.';-const COCOAPODS_REPO_NOT_FOUND_MESSAGE = 'The CocoaPods repo at ~/.cocoapods was not found.';+ `Please download, build and install version ${IOS_DEPLOY_MIN_VERSION} or greater from https://github.com/ios-control/ios-deploy into your path, or do 'npm install -g ios-deploy'`;++const COCOAPODS_MIN_VERSION = '1.8.0';+const COCOAPODS_NOT_FOUND_MESSAGE = `Please install version ${COCOAPODS_MIN_VERSION} or greater from https://cocoapods.org/`;/*** Checks if xcode util is available* @return {Promise} Returns a promise either resolved with xcode version or rejected*/-module.exports.run = module.exports.check_xcodebuild = function () {+module.exports.run = module.exports.check_xcodebuild = () => {return checkTool('xcodebuild', XCODEBUILD_MIN_VERSION, XCODEBUILD_NOT_FOUND_MESSAGE);};@@ -57,88 +48,27 @@ module.exports.run = module.exports.check_xcodebuild = function () {* Checks if ios-deploy util is available* @return {Promise} Returns a promise either resolved with ios-deploy version or rejected*/-module.exports.check_ios_deploy = function () {+module.exports.check_ios_deploy = () => {return checkTool('ios-deploy', IOS_DEPLOY_MIN_VERSION, IOS_DEPLOY_NOT_FOUND_MESSAGE);};-module.exports.check_os = function () {+module.exports.check_os = () => {// Build iOS apps available for OSX platform only, so we reject on others platforms- return os_platform_is_supported() ?- Q.resolve(process.platform) :- Q.reject('Cordova tooling for iOS requires Apple macOS');+ return os_platform_is_supported()+ ? Promise.resolve(process.platform)+ : Promise.reject(new CordovaError('Cordova tooling for iOS requires Apple macOS'));};function os_platform_is_supported () {return (SUPPORTED_OS_PLATFORMS.indexOf(process.platform) !== -1);}-function check_cocoapod_tool (toolChecker) {- toolChecker = toolChecker || checkTool;- if (os_platform_is_supported()) { // CB-12856- return toolChecker('pod', COCOAPODS_MIN_VERSION, COCOAPODS_NOT_FOUND_MESSAGE, 'CocoaPods');- } else {- return Q.resolve({- 'ignore': true,- 'ignoreMessage': `CocoaPods check and installation ignored on ${process.platform}`- });- }-}--/**- * Checks if cocoapods repo size is what is expected- * @return {Promise} Returns a promise either resolved or rejected- */-module.exports.check_cocoapods_repo_size = function () {- return check_cocoapod_tool()- .then(function (toolOptions) {- // check size of ~/.cocoapods repo- let commandString = util.format('du -sh %s/.cocoapods', process.env.HOME);- let command = shell.exec(commandString, { silent: true });- // command.output is e.g "750M path/to/.cocoapods", we just scan the number- let size = toolOptions.ignore ? 0 : parseFloat(command.output);-- if (toolOptions.ignore || command.code === 0) { // success, parse output- return Q.resolve(size, toolOptions);- } else { // error, perhaps not found- return Q.reject(util.format('%s (%s)', COCOAPODS_REPO_NOT_FOUND_MESSAGE, command.output));- }- })- .then(function (repoSize, toolOptions) {- if (toolOptions.ignore || COCOAPODS_SYNCED_MIN_SIZE <= repoSize) { // success, expected size- return Q.resolve(toolOptions);- } else {- return Q.reject(COCOAPODS_SYNC_ERROR_MESSAGE);- }- });-};-/**- * Checks if cocoapods is available, and whether the repo is synced (because it takes a long time to download)+ * Checks if cocoapods is available.* @return {Promise} Returns a promise either resolved or rejected*/-module.exports.check_cocoapods = function (toolChecker) {- return check_cocoapod_tool(toolChecker)- // check whether the cocoapods repo has been synced through `pod repo` command- // a value of '0 repos' means it hasn't been synced- .then(function (toolOptions) {- if (toolOptions.ignore) return toolOptions;-- // starting with 1.8.0 cocoapods now use cdn and we dont need to sync first- if (versions.compareVersions(toolOptions.version, '1.8.0') >= 0) {- return toolOptions;- }-- let code = shell.exec('pod repo | grep -e "^0 repos"', { silent: true }).code;- let repoIsSynced = (code !== 0);-- if (repoIsSynced) {- // return check_cocoapods_repo_size();- // we could check the repo size above, but it takes too long.- return toolOptions;- } else {- return Promise.reject(COCOAPODS_NOT_SYNCED_MESSAGE);- }- });+module.exports.check_cocoapods = toolChecker => {+ return checkTool('pod', COCOAPODS_MIN_VERSION, COCOAPODS_NOT_FOUND_MESSAGE, 'CocoaPods');};/**@@ -153,18 +83,17 @@ function checkTool (tool, minVersion, message, toolFriendlyName) {toolFriendlyName = toolFriendlyName || tool;// Check whether tool command is available at all- let tool_command = shell.which(tool);+ const tool_command = which.sync(tool, { nothrow: true });if (!tool_command) {- return Q.reject(toolFriendlyName + ' was not found. ' + (message || ''));+ return Promise.reject(new CordovaError(`${toolFriendlyName} was not found. ${message || ''}`));}// check if tool version is greater than specified one- return versions.get_tool_version(tool).then(function (version) {+ return versions.get_tool_version(tool).then(version => {version = version.trim();- return versions.compareVersions(version, minVersion) >= 0 ?- Q.resolve({ 'version': version }) :- Q.reject('Cordova needs ' + toolFriendlyName + ' version ' + minVersion +- ' or greater, you have version ' + version + '. ' + (message || ''));+ return versions.compareVersions(version, minVersion) >= 0+ ? Promise.resolve({ version })+ : Promise.reject(new CordovaError(`Cordova needs ${toolFriendlyName} version ${minVersion} or greater, you have version ${version}. ${message || ''}`));});}@@ -175,7 +104,7 @@ function checkTool (tool, minVersion, message, toolFriendlyName) {* @param {Boolean} isFatal Marks the requirement as fatal. If such requirement will fail* next requirements' checks will be skipped.*/-let Requirement = function (id, name, isFatal) {+const Requirement = function (id, name, isFatal) {this.id = id;this.name = name;this.installed = false;@@ -189,8 +118,7 @@ let Requirement = function (id, name, isFatal) {** @return Promise<Requirement[]> Array of requirements. Due to implementation, promise is always fulfilled.*/-module.exports.check_all = function () {-+module.exports.check_all = () => {const requirements = [new Requirement('os', 'Apple macOS', true),new Requirement('xcode', 'Xcode'),@@ -198,10 +126,10 @@ module.exports.check_all = function () {new Requirement('CocoaPods', 'CocoaPods')];- let result = [];+ const result = [];let fatalIsHit = false;- let checkFns = [+ const checkFns = [module.exports.check_os,module.exports.check_xcodebuild,module.exports.check_ios_deploy,@@ -209,27 +137,25 @@ module.exports.check_all = function () {];// Then execute requirement checks one-by-one- return checkFns.reduce(function (promise, checkFn, idx) {- return promise.then(function () {+ return checkFns.reduce((promise, checkFn, idx) => {+ return promise.then(() => {// If fatal requirement is failed,// we don't need to check others- if (fatalIsHit) return Q();+ if (fatalIsHit) return Promise.resolve();- let requirement = requirements[idx];+ const requirement = requirements[idx];return checkFn()- .then(function (version) {+ .then(version => {requirement.installed = true;requirement.metadata.version = version;result.push(requirement);- }, function (err) {+ }, err => {if (requirement.isFatal) fatalIsHit = true;requirement.metadata.reason = err;result.push(requirement);});});- }, Q())- .then(function () {- // When chain is completed, return requirements array to upstream API- return result;- });+ }, Promise.resolve())+ // When chain is completed, return requirements array to upstream API+ .then(() => result);};diff --git a/cordova/platforms/ios/cordova/lib/clean.js b/cordova/platforms/ios/cordova/lib/clean.jsindex e5c24a509..72aac0baf 100755--- a/cordova/platforms/ios/cordova/lib/clean.js+++ b/cordova/platforms/ios/cordova/lib/clean.js@@ -17,26 +17,31 @@* under the License.*/-var Q = require('q');-var path = require('path');-var shell = require('shelljs');-var superspawn = require('cordova-common').superspawn;+const path = require('path');+const fs = require('fs-extra');+const {+ CordovaError,+ superspawn: { spawn }+} = require('cordova-common');-var projectPath = path.join(__dirname, '..', '..');+const projectPath = path.join(__dirname, '..', '..');-module.exports.run = function () {- var projectName = shell.ls(projectPath).filter(function (name) {- return path.extname(name) === '.xcodeproj';- })[0];+module.exports.run = () => {+ const projectName = fs.readdirSync(projectPath).filter(name => path.extname(name) === '.xcodeproj');if (!projectName) {- return Q.reject('No Xcode project found in ' + projectPath);+ return Promise.reject(new CordovaError(`No Xcode project found in ${projectPath}`));}- return superspawn.spawn('xcodebuild', ['-project', projectName, '-configuration', 'Debug', '-alltargets', 'clean'], { cwd: projectPath, printCommand: true, stdio: 'inherit' })- .then(function () {- return superspawn.spawn('xcodebuild', ['-project', projectName, '-configuration', 'Release', '-alltargets', 'clean'], { cwd: projectPath, printCommand: true, stdio: 'inherit' });- }).then(function () {- return shell.rm('-rf', path.join(projectPath, 'build'));- });+ const xcodebuildClean = configName => {+ return spawn(+ 'xcodebuild',+ ['-project', projectName, '-configuration', configName, '-alltargets', 'clean'],+ { cwd: projectPath, printCommand: true, stdio: 'inherit' }+ );+ };++ return xcodebuildClean('Debug')+ .then(() => xcodebuildClean('Release'))+ .then(() => fs.removeSync(path.join(projectPath, 'build')));};diff --git a/cordova/platforms/ios/cordova/lib/list-devices b/cordova/platforms/ios/cordova/lib/list-devicesindex 473ff5ccd..5f89e21b2 100755--- a/cordova/platforms/ios/cordova/lib/list-devices+++ b/cordova/platforms/ios/cordova/lib/list-devices@@ -19,48 +19,10 @@under the License.*/-var Q = require('q');-var exec = require('child_process').exec;+const { run } = require('./listDevices');-/**- * Gets list of connected iOS devices- * @return {Promise} Promise fulfilled with list of available iOS devices- */-function listDevices () {- var commands = [- Q.nfcall(exec, "ioreg -p IOUSB -l | sed -n -e '/iPad/,/USB Serial Number/p' | grep 'Serial Number' | awk -F\\\" '{print $4 \" iPad\"}'"),- Q.nfcall(exec, "ioreg -p IOUSB -l | sed -n -e '/iPhone/,/USB Serial Number/p' | grep 'Serial Number' | awk -F\\\" '{print $4 \" iPhone\"}'"),- Q.nfcall(exec, "ioreg -p IOUSB -l | sed -n -e '/iPod/,/USB Serial Number/p' | grep 'Serial Number' | awk -F\\\" '{print $4 \" iPod\"}'")- ];-- // wrap al lexec calls into promises and wait until they're fullfilled- return Q.all(commands).then(function (results) {- var accumulator = [];- results.forEach(function (result) {- var devicefound;- // Each command promise resolves with array [stout, stderr], and we need stdout only- // Append stdout lines to accumulator- devicefound = result[0].trim().split('\n');- if (devicefound && devicefound.length) {- devicefound.forEach(function (device) {- if (device) {- accumulator.push(device);- }- });- }- });- return accumulator;- });-}--exports.run = listDevices;--// Check if module is started as separate script.-// If so, then invoke main method and print out results.-if (!module.parent) {- listDevices().then(function (devices) {- devices.forEach(function (device) {- console.log(device);- });+run().then(devices => {+ devices.forEach(device => {+ console.log(device);});-}+});diff --git a/cordova/platforms/ios/cordova/lib/list-emulator-build-targets b/cordova/platforms/ios/cordova/lib/list-emulator-build-targetsindex 25dfe720f..304c4c171 100755--- a/cordova/platforms/ios/cordova/lib/list-emulator-build-targets+++ b/cordova/platforms/ios/cordova/lib/list-emulator-build-targets@@ -19,90 +19,8 @@under the License.*/-var Q = require('q');-var exec = require('child_process').exec;+const { run } = require('./listEmulatorBuildTargets');-/**- * Returns a list of available simulator build targets of the form- *- * [- * { name: <xcode-destination-name>,- * identifier: <simctl-identifier>,- * simIdentifier: <cordova emulate target>- * }- * ]- *- */-function listEmulatorBuildTargets () {- return Q.nfcall(exec, 'xcrun simctl list --json')- .then(function (stdio) {- return JSON.parse(stdio[0]);- })- .then(function (simInfo) {- var devices = simInfo.devices;- var deviceTypes = simInfo.devicetypes;- return deviceTypes.reduce(function (typeAcc, deviceType) {- if (!deviceType.name.match(/^[iPad|iPhone]/)) {- // ignore targets we don't support (like Apple Watch or Apple TV)- return typeAcc;- }- var availableDevices = Object.keys(devices).reduce(function (availAcc, deviceCategory) {- var availableDevicesInCategory = devices[deviceCategory];- availableDevicesInCategory.forEach(function (device) {- if (device.name === deviceType.name || device.name === deviceType.name.replace(/-inch/g, ' inch')) {- // Check new flag isAvailable (XCode 10.1+) or legacy string availability (XCode 10 and lower)- if (device.isAvailable || (device.availability && device.availability.toLowerCase().indexOf('unavailable') < 0)) {- availAcc.push(device);- }- }- });- return availAcc;- }, []);- // we only want device types that have at least one available device- // (regardless of OS); this filters things out like iPhone 4s, which- // is present in deviceTypes, but probably not available on the user's- // system.- if (availableDevices.length > 0) {- typeAcc.push(deviceType);- }- return typeAcc;- }, []);- })- .then(function (filteredTargets) {- // the simIdentifier, or cordova emulate target name, is the very last part- // of identifier.- return filteredTargets.map(function (target) {- var identifierPieces = target.identifier.split('.');- target.simIdentifier = identifierPieces[identifierPieces.length - 1];- return target;- });- });-}--exports.run = listEmulatorBuildTargets;--/**- * Given a simIdentifier, return the matching target.- *- * @param {string} simIdentifier a target, like "iPhone-SE"- * @return {Object} the matching target, or undefined if no match- */-exports.targetForSimIdentifier = function (simIdentifier) {- return listEmulatorBuildTargets()- .then(function (targets) {- return targets.reduce(function (acc, target) {- if (!acc && target.simIdentifier.toLowerCase() === simIdentifier.toLowerCase()) {- acc = target;- }- return acc;- }, undefined);- });-};--// Check if module is started as separate script.-// If so, then invoke main method and print out results.-if (!module.parent) {- listEmulatorBuildTargets().then(function (targets) {- console.log(JSON.stringify(targets, null, 2));- });-}+run().then(targets => {+ console.log(JSON.stringify(targets, null, 2));+});diff --git a/cordova/platforms/ios/cordova/lib/list-emulator-images b/cordova/platforms/ios/cordova/lib/list-emulator-imagesindex 99557e236..db9b72af0 100755--- a/cordova/platforms/ios/cordova/lib/list-emulator-images+++ b/cordova/platforms/ios/cordova/lib/list-emulator-images@@ -19,25 +19,10 @@under the License.*/-var Q = require('q');-var iossim = require('ios-sim');+const { run } = require('./listEmulatorImages');-/**- * Gets list of iOS devices available for simulation- * @return {Promise} Promise fulfilled with list of devices available for simulation- */-function listEmulatorImages () {- return Q.resolve(iossim.getdevicetypes());-}--exports.run = listEmulatorImages;--// Check if module is started as separate script.-// If so, then invoke main method and print out results.-if (!module.parent) {- listEmulatorImages().then(function (names) {- names.forEach(function (name) {- console.log(name);- });+run().then(names => {+ names.forEach(name => {+ console.log(name);});-}+});diff --git a/cordova/platforms/ios/cordova/lib/list-started-emulators b/cordova/platforms/ios/cordova/lib/list-started-emulatorsindex 3626df810..7f06cf2e8 100755--- a/cordova/platforms/ios/cordova/lib/list-started-emulators+++ b/cordova/platforms/ios/cordova/lib/list-started-emulators@@ -19,31 +19,10 @@under the License.*/-var Q = require('q');-var exec = require('child_process').exec;+const { run } = require('./listStartedEmulators');-/**- * Gets list of running iOS simulators- * @return {Promise} Promise fulfilled with list of running iOS simulators- */-function listStartedEmulators () {- // wrap exec call into promise- return Q.nfcall(exec, 'ps aux | grep -i "[i]OS Simulator"')- .then(function () {- return Q.nfcall(exec, 'defaults read com.apple.iphonesimulator "SimulateDevice"');- }).then(function (stdio) {- return stdio[0].trim().split('\n');- });-}--exports.run = listStartedEmulators;--// Check if module is started as separate script.-// If so, then invoke main method and print out results.-if (!module.parent) {- listStartedEmulators().then(function (emulators) {- emulators.forEach(function (emulator) {- console.log(emulator);- });+run().then(emulators => {+ emulators.forEach(emulator => {+ console.log(emulator);});-}+});diff --git a/cordova/platforms/ios/cordova/lib/listDevices.js b/cordova/platforms/ios/cordova/lib/listDevices.jsnew file mode 100644index 000000000..86a67ffbb--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/listDevices.js@@ -0,0 +1,42 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++const { superspawn: { spawn } } = require('cordova-common');++const DEVICE_REGEX = /-o (iPhone|iPad|iPod)@.*?"USB Serial Number" = "([^"]*)"/gs;++/**+ * Gets list of connected iOS devices+ * @return {Promise} Promise fulfilled with list of available iOS devices+ */+function listDevices () {+ return spawn('ioreg', ['-p', 'IOUSB', '-l'])+ .then(output => {+ return [...matchAll(output, DEVICE_REGEX)]+ .map(m => m.slice(1).reverse().join(' '));+ });+}++// TODO: Should be replaced with String#matchAll once available+function * matchAll (s, r) {+ let match;+ while ((match = r.exec(s))) yield match;+}++exports.run = listDevices;diff --git a/cordova/platforms/ios/cordova/lib/listEmulatorBuildTargets.js b/cordova/platforms/ios/cordova/lib/listEmulatorBuildTargets.jsnew file mode 100644index 000000000..73e35c05a--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/listEmulatorBuildTargets.js@@ -0,0 +1,95 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++const { superspawn: { spawn } } = require('cordova-common');++/**+ * Returns a list of available simulator build targets of the form+ *+ * [+ * { name: <xcode-destination-name>,+ * identifier: <simctl-identifier>,+ * simIdentifier: <cordova emulate target>+ * }+ * ]+ *+ */+function listEmulatorBuildTargets () {+ return spawn('xcrun', ['simctl', 'list', '--json'])+ .then(output => JSON.parse(output))+ .then(function (simInfo) {+ var devices = simInfo.devices;+ var deviceTypes = simInfo.devicetypes;+ return deviceTypes.reduce(function (typeAcc, deviceType) {+ if (!deviceType.name.match(/^[iPad|iPhone]/)) {+ // ignore targets we don't support (like Apple Watch or Apple TV)+ return typeAcc;+ }+ var availableDevices = Object.keys(devices).reduce(function (availAcc, deviceCategory) {+ var availableDevicesInCategory = devices[deviceCategory];+ availableDevicesInCategory.forEach(function (device) {+ if (device.name === deviceType.name || device.name === deviceType.name.replace(/-inch/g, ' inch')) {+ // Check new flag isAvailable (XCode 10.1+) or legacy string availability (XCode 10 and lower)+ if (device.isAvailable || (device.availability && device.availability.toLowerCase().indexOf('unavailable') < 0)) {+ availAcc.push(device);+ }+ }+ });+ return availAcc;+ }, []);+ // we only want device types that have at least one available device+ // (regardless of OS); this filters things out like iPhone 4s, which+ // is present in deviceTypes, but probably not available on the user's+ // system.+ if (availableDevices.length > 0) {+ typeAcc.push(deviceType);+ }+ return typeAcc;+ }, []);+ })+ .then(function (filteredTargets) {+ // the simIdentifier, or cordova emulate target name, is the very last part+ // of identifier.+ return filteredTargets.map(function (target) {+ var identifierPieces = target.identifier.split('.');+ target.simIdentifier = identifierPieces[identifierPieces.length - 1];+ return target;+ });+ });+}++exports.run = listEmulatorBuildTargets;++/**+ * Given a simIdentifier, return the matching target.+ *+ * @param {string} simIdentifier a target, like "iPhone-SE"+ * @return {Object} the matching target, or undefined if no match+ */+exports.targetForSimIdentifier = function (simIdentifier) {+ return listEmulatorBuildTargets()+ .then(function (targets) {+ return targets.reduce(function (acc, target) {+ if (!acc && target.simIdentifier.toLowerCase() === simIdentifier.toLowerCase()) {+ acc = target;+ }+ return acc;+ }, undefined);+ });+};diff --git a/cordova/platforms/ios/cordova/lib/listEmulatorImages.js b/cordova/platforms/ios/cordova/lib/listEmulatorImages.jsnew file mode 100644index 000000000..09e143402--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/listEmulatorImages.js@@ -0,0 +1,30 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++var iossim = require('ios-sim');++/**+ * Gets list of iOS devices available for simulation+ * @return {Promise} Promise fulfilled with list of devices available for simulation+ */+function listEmulatorImages () {+ return Promise.resolve(iossim.getdevicetypes());+}++exports.run = listEmulatorImages;diff --git a/cordova/platforms/ios/cordova/lib/listStartedEmulators.js b/cordova/platforms/ios/cordova/lib/listStartedEmulators.jsnew file mode 100644index 000000000..ec1cb7f2f--- /dev/null+++ b/cordova/platforms/ios/cordova/lib/listStartedEmulators.js@@ -0,0 +1,50 @@+/*+ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you under the Apache License, Version 2.0 (the+ "License"); you may not use this file except in compliance+ with the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing,+ software distributed under the License is distributed on an+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the+ specific language governing permissions and limitations+ under the License.+*/++const { superspawn: { spawn } } = require('cordova-common');++/**+ * Gets list of running iOS simulators+ * @return {Promise} Promise fulfilled with list of running iOS simulators+ *+ * @todo In the next PR, I will refactor this entire method.+ *+ * The process no longer contains the pattern "[i]OS Simulator".+ * The process is now called "Simulator.app"+ *+ * Additionaly, `defaults read com.apple.iphonesimulator "SimulateDevice"` is also not valid aymore.+ *+ * I will replace this entire method to locate the active simulators though `simctl`+ *+ * Alternativly, remove this file. It is not documented in Cordova and not used anywhere in our code base.+ */+function listStartedEmulators () {+ // wrap exec call into promise+ return spawn('ps', ['aux'])+ .then(output => {+ if (output.match(/[i]OS Simulator/)) {+ return spawn('defaults', ['read', 'com.apple.iphonesimulator', '"SimulateDevice"']);+ }++ return '';+ })+ .then(output => output.split('\n'));+}++exports.run = listStartedEmulators;diff --git a/cordova/platforms/ios/cordova/lib/plugman/pluginHandlers.js b/cordova/platforms/ios/cordova/lib/plugman/pluginHandlers.jsindex bd9d853e3..09d5ae51e 100755--- a/cordova/platforms/ios/cordova/lib/plugman/pluginHandlers.js+++ b/cordova/platforms/ios/cordova/lib/plugman/pluginHandlers.js@@ -15,21 +15,20 @@under the License.*/'use strict';-var fs = require('fs');-var path = require('path');-var shell = require('shelljs');-var util = require('util');-var events = require('cordova-common').events;-var CordovaError = require('cordova-common').CordovaError;+const fs = require('fs-extra');+const path = require('path');+const util = require('util');+const events = require('cordova-common').events;+const CordovaError = require('cordova-common').CordovaError;// These frameworks are required by cordova-ios by default. We should never add/remove them.-var keep_these_frameworks = [+const keep_these_frameworks = ['MobileCoreServices.framework','CoreGraphics.framework','AssetsLibrary.framework'];-var handlers = {+const handlers = {'source-file': {install: function (obj, plugin, project, options) {installHelper('source-file', obj, plugin.dir, project.projectDir, plugin.id, options, project);@@ -48,47 +47,47 @@ var handlers = {},'resource-file': {install: function (obj, plugin, project, options) {- var src = obj.src;- var target = obj.target;- var srcFile = path.resolve(plugin.dir, src);+ const src = obj.src;+ let target = obj.target;+ const srcFile = path.resolve(plugin.dir, src);if (!target) {target = path.basename(src);}- var destFile = path.resolve(project.resources_dir, target);+ const destFile = path.resolve(project.resources_dir, target);if (!fs.existsSync(srcFile)) {- throw new CordovaError('Cannot find resource file "' + srcFile + '" for plugin ' + plugin.id + ' in iOS platform');+ throw new CordovaError(`Cannot find resource file "${srcFile}" for plugin ${plugin.id} in iOS platform`);}if (fs.existsSync(destFile)) {- throw new CordovaError('File already exists at destination "' + destFile + '" for resource file specified by plugin ' + plugin.id + ' in iOS platform');+ throw new CordovaError(`File already exists at destination "${destFile}" for resource file specified by plugin ${plugin.id} in iOS platform`);}project.xcode.addResourceFile(path.join('Resources', target));- var link = !!(options && options.link);+ const link = !!(options && options.link);copyFile(plugin.dir, src, project.projectDir, destFile, link);},uninstall: function (obj, plugin, project, options) {- var src = obj.src;- var target = obj.target;+ const src = obj.src;+ let target = obj.target;if (!target) {target = path.basename(src);}- var destFile = path.resolve(project.resources_dir, target);+ const destFile = path.resolve(project.resources_dir, target);project.xcode.removeResourceFile(path.join('Resources', target));- shell.rm('-rf', destFile);+ fs.removeSync(destFile);}},- 'framework': { // CB-5238 custom frameworks only+ framework: { // CB-5238 custom frameworks onlyinstall: function (obj, plugin, project, options) {- var src = obj.src;- var custom = !!(obj.custom); // convert to boolean (if truthy/falsy)- var embed = !!(obj.embed); // convert to boolean (if truthy/falsy)- var link = !embed; // either link or embed can be true, but not both. the other has to be false+ const src = obj.src;+ const custom = !!(obj.custom); // convert to boolean (if truthy/falsy)+ const embed = !!(obj.embed); // convert to boolean (if truthy/falsy)+ const link = !embed; // either link or embed can be true, but not both. the other has to be falseif (!custom) {- var keepFrameworks = keep_these_frameworks;+ const keepFrameworks = keep_these_frameworks;if (keepFrameworks.indexOf(src) < 0) {if (obj.type === 'podspec') {@@ -96,7 +95,7 @@ var handlers = {} else {project.frameworks[src] = project.frameworks[src] || 0;project.frameworks[src]++;- let opt = { customFramework: false, embed: false, link: true, weak: obj.weak };+ const opt = { customFramework: false, embed: false, link: true, weak: obj.weak };events.emit('verbose', util.format('Adding non-custom framework to project... %s -> %s', src, JSON.stringify(opt)));project.xcode.addFramework(src, opt);events.emit('verbose', util.format('Non-custom framework added to project. %s -> %s', src, JSON.stringify(opt)));@@ -104,30 +103,30 @@ var handlers = {}return;}- var srcFile = path.resolve(plugin.dir, src);- var targetDir = path.resolve(project.plugins_dir, plugin.id, path.basename(src));- if (!fs.existsSync(srcFile)) throw new CordovaError('Cannot find framework "' + srcFile + '" for plugin ' + plugin.id + ' in iOS platform');- if (fs.existsSync(targetDir)) throw new CordovaError('Framework "' + targetDir + '" for plugin ' + plugin.id + ' already exists in iOS platform');- var symlink = !!(options && options.link);+ const srcFile = path.resolve(plugin.dir, src);+ const targetDir = path.resolve(project.plugins_dir, plugin.id, path.basename(src));+ if (!fs.existsSync(srcFile)) throw new CordovaError(`Cannot find framework "${srcFile}" for plugin ${plugin.id} in iOS platform`);+ if (fs.existsSync(targetDir)) throw new CordovaError(`Framework "${targetDir}" for plugin ${plugin.id} already exists in iOS platform`);+ const symlink = !!(options && options.link);copyFile(plugin.dir, src, project.projectDir, targetDir, symlink); // frameworks are directories// CB-10773 translate back slashes to forward on win32- var project_relative = fixPathSep(path.relative(project.projectDir, targetDir));+ const project_relative = fixPathSep(path.relative(project.projectDir, targetDir));// CB-11233 create Embed Frameworks Build Phase if does not exist- var existsEmbedFrameworks = project.xcode.buildPhaseObject('PBXCopyFilesBuildPhase', 'Embed Frameworks');+ const existsEmbedFrameworks = project.xcode.buildPhaseObject('PBXCopyFilesBuildPhase', 'Embed Frameworks');if (!existsEmbedFrameworks && embed) {events.emit('verbose', '"Embed Frameworks" Build Phase (Embedded Binaries) does not exist, creating it.');project.xcode.addBuildPhase([], 'PBXCopyFilesBuildPhase', 'Embed Frameworks', null, 'frameworks');}- let opt = { customFramework: true, embed: embed, link: link, sign: true };+ const opt = { customFramework: true, embed, link, sign: true };events.emit('verbose', util.format('Adding custom framework to project... %s -> %s', src, JSON.stringify(opt)));project.xcode.addFramework(project_relative, opt);events.emit('verbose', util.format('Custom framework added to project. %s -> %s', src, JSON.stringify(opt)));},uninstall: function (obj, plugin, project, options) {- var src = obj.src;+ const src = obj.src;if (!obj.custom) { // CB-9825 cocoapod integration for plugins- var keepFrameworks = keep_these_frameworks;+ const keepFrameworks = keep_these_frameworks;if (keepFrameworks.indexOf(src) < 0) {if (obj.type !== 'podspec') {// this should be refactored@@ -144,12 +143,12 @@ var handlers = {return;}- var targetDir = fixPathSep(path.resolve(project.plugins_dir, plugin.id, path.basename(src)));- var pbxFile = project.xcode.removeFramework(targetDir, { customFramework: true });+ const targetDir = fixPathSep(path.resolve(project.plugins_dir, plugin.id, path.basename(src)));+ const pbxFile = project.xcode.removeFramework(targetDir, { customFramework: true });if (pbxFile) {project.xcode.removeFromPbxEmbedFrameworksBuildPhase(pbxFile);}- shell.rm('-rf', targetDir);+ fs.removeSync(targetDir);}},'lib-file': {@@ -160,7 +159,7 @@ var handlers = {events.emit('verbose', '<lib-file> uninstall is not supported for iOS plugins');}},- 'asset': {+ asset: {install: function (obj, plugin, project, options) {if (!obj.src) {throw new CordovaError(generateAttributeError('src', 'asset', plugin.id));@@ -173,7 +172,7 @@ var handlers = {if (options && options.usePlatformWww) copyFile(plugin.dir, obj.src, project.platformWww, obj.target);},uninstall: function (obj, plugin, project, options) {- var target = obj.target;+ const target = obj.target;if (!target) {throw new CordovaError(generateAttributeError('target', 'asset', plugin.id));@@ -190,58 +189,58 @@ var handlers = {'js-module': {install: function (obj, plugin, project, options) {// Copy the plugin's files into the www directory.- var moduleSource = path.resolve(plugin.dir, obj.src);- var moduleName = plugin.id + '.' + (obj.name || path.basename(obj.src, path.extname(obj.src)));+ const moduleSource = path.resolve(plugin.dir, obj.src);+ const moduleName = `${plugin.id}.${obj.name || path.basename(obj.src, path.extname(obj.src))}`;// Read in the file, prepend the cordova.define, and write it back out.- var scriptContent = fs.readFileSync(moduleSource, 'utf-8').replace(/^\ufeff/, ''); // Window BOM+ let scriptContent = fs.readFileSync(moduleSource, 'utf-8').replace(/^\ufeff/, ''); // Window BOMif (moduleSource.match(/.*\.json$/)) {- scriptContent = 'module.exports = ' + scriptContent;+ scriptContent = `module.exports = ${scriptContent}`;}- scriptContent = 'cordova.define("' + moduleName + '", function(require, exports, module) {\n' + scriptContent + '\n});\n';+ scriptContent = `cordova.define("${moduleName}", function(require, exports, module) {\n${scriptContent}\n});\n`;- var moduleDestination = path.resolve(project.www, 'plugins', plugin.id, obj.src);- shell.mkdir('-p', path.dirname(moduleDestination));+ const moduleDestination = path.resolve(project.www, 'plugins', plugin.id, obj.src);+ fs.ensureDirSync(path.dirname(moduleDestination));fs.writeFileSync(moduleDestination, scriptContent, 'utf-8');if (options && options.usePlatformWww) {- var platformWwwDestination = path.resolve(project.platformWww, 'plugins', plugin.id, obj.src);- shell.mkdir('-p', path.dirname(platformWwwDestination));+ const platformWwwDestination = path.resolve(project.platformWww, 'plugins', plugin.id, obj.src);+ fs.ensureDirSync(path.dirname(platformWwwDestination));fs.writeFileSync(platformWwwDestination, scriptContent, 'utf-8');}},uninstall: function (obj, plugin, project, options) {- var pluginRelativePath = path.join('plugins', plugin.id, obj.src);+ const pluginRelativePath = path.join('plugins', plugin.id, obj.src);removeFileAndParents(project.www, pluginRelativePath);if (options && options.usePlatformWww) removeFileAndParents(project.platformWww, pluginRelativePath);}}};-module.exports.getInstaller = function (type) {+module.exports.getInstaller = type => {if (handlers[type] && handlers[type].install) {return handlers[type].install;}- events.emit('warn', '<' + type + '> is not supported for iOS plugins');+ events.emit('warn', `<${type}> is not supported for iOS plugins`);};-module.exports.getUninstaller = function (type) {+module.exports.getUninstaller = type => {if (handlers[type] && handlers[type].uninstall) {return handlers[type].uninstall;}- events.emit('warn', '<' + type + '> is not supported for iOS plugins');+ events.emit('warn', `<${type}> is not supported for iOS plugins`);};function installHelper (type, obj, plugin_dir, project_dir, plugin_id, options, project) {- var srcFile = path.resolve(plugin_dir, obj.src);- var targetDir = path.resolve(project.plugins_dir, plugin_id, obj.targetDir || '');- var destFile = path.join(targetDir, path.basename(obj.src));+ const srcFile = path.resolve(plugin_dir, obj.src);+ const targetDir = path.resolve(project.plugins_dir, plugin_id, obj.targetDir || '');+ const destFile = path.join(targetDir, path.basename(obj.src));- var project_ref;- var link = !!(options && options.link);+ let project_ref;+ const link = !!(options && options.link);if (link) {- var trueSrc = fs.realpathSync(srcFile);+ const trueSrc = fs.realpathSync(srcFile);// Create a symlink in the expected place, so that uninstall can use it.if (options && options.force) {copyFile(plugin_dir, trueSrc, project_dir, destFile, link);@@ -252,21 +251,21 @@ function installHelper (type, obj, plugin_dir, project_dir, plugin_id, options,// Make the Xcode reference the file directly.// Note: Can't use path.join() here since it collapses 'Plugins/..', and xcode// library special-cases Plugins/ prefix.- project_ref = 'Plugins/' + fixPathSep(path.relative(fs.realpathSync(project.plugins_dir), trueSrc));+ project_ref = `Plugins/${fixPathSep(path.relative(fs.realpathSync(project.plugins_dir), trueSrc))}`;} else {if (options && options.force) {copyFile(plugin_dir, srcFile, project_dir, destFile, link);} else {copyNewFile(plugin_dir, srcFile, project_dir, destFile, link);}- project_ref = 'Plugins/' + fixPathSep(path.relative(project.plugins_dir, destFile));+ project_ref = `Plugins/${fixPathSep(path.relative(project.plugins_dir, destFile))}`;}if (type === 'header-file') {project.xcode.addHeaderFile(project_ref);} else if (obj.framework) {- var opt = { weak: obj.weak };- var project_relative = path.join(path.basename(project.xcode_path), project_ref);+ const opt = { weak: obj.weak };+ const project_relative = path.join(path.basename(project.xcode_path), project_ref);project.xcode.addFramework(project_relative, opt);project.xcode.addToLibrarySearchPaths({ path: project_ref });} else {@@ -275,24 +274,24 @@ function installHelper (type, obj, plugin_dir, project_dir, plugin_id, options,}function uninstallHelper (type, obj, project_dir, plugin_id, options, project) {- var targetDir = path.resolve(project.plugins_dir, plugin_id, obj.targetDir || '');- var destFile = path.join(targetDir, path.basename(obj.src));+ const targetDir = path.resolve(project.plugins_dir, plugin_id, obj.targetDir || '');+ const destFile = path.join(targetDir, path.basename(obj.src));- var project_ref;- var link = !!(options && options.link);+ let project_ref;+ const link = !!(options && options.link);if (link) {- var trueSrc = fs.readlinkSync(destFile);- project_ref = 'Plugins/' + fixPathSep(path.relative(fs.realpathSync(project.plugins_dir), trueSrc));+ const trueSrc = fs.readlinkSync(destFile);+ project_ref = `Plugins/${fixPathSep(path.relative(fs.realpathSync(project.plugins_dir), trueSrc))}`;} else {- project_ref = 'Plugins/' + fixPathSep(path.relative(project.plugins_dir, destFile));+ project_ref = `Plugins/${fixPathSep(path.relative(project.plugins_dir, destFile))}`;}- shell.rm('-rf', targetDir);+ fs.removeSync(targetDir);if (type === 'header-file') {project.xcode.removeHeaderFile(project_ref);} else if (obj.framework) {- var project_relative = path.join(path.basename(project.xcode_path), project_ref);+ const project_relative = path.join(path.basename(project.xcode_path), project_ref);project.xcode.removeFramework(project_relative);project.xcode.removeFromLibrarySearchPaths({ path: project_ref });} else {@@ -300,53 +299,50 @@ function uninstallHelper (type, obj, project_dir, plugin_id, options, project) {}}-var pathSepFix = new RegExp(path.sep.replace(/\\/, '\\\\'), 'g');+const pathSepFix = new RegExp(path.sep.replace(/\\/, '\\\\'), 'g');function fixPathSep (file) {return file.replace(pathSepFix, '/');}function copyFile (plugin_dir, src, project_dir, dest, link) {src = path.resolve(plugin_dir, src);- if (!fs.existsSync(src)) throw new CordovaError('"' + src + '" not found!');+ if (!fs.existsSync(src)) throw new CordovaError(`"${src}" not found!`);// check that src path is inside plugin directory- var real_path = fs.realpathSync(src);- var real_plugin_path = fs.realpathSync(plugin_dir);- if (real_path.indexOf(real_plugin_path) !== 0) { throw new CordovaError('File "' + src + '" is located outside the plugin directory "' + plugin_dir + '"'); }+ const real_path = fs.realpathSync(src);+ const real_plugin_path = fs.realpathSync(plugin_dir);+ if (real_path.indexOf(real_plugin_path) !== 0) { throw new CordovaError(`File "${src}" is located outside the plugin directory "${plugin_dir}"`); }dest = path.resolve(project_dir, dest);// check that dest path is located in project directory- if (dest.indexOf(project_dir) !== 0) { throw new CordovaError('Destination "' + dest + '" for source file "' + src + '" is located outside the project'); }+ if (dest.indexOf(project_dir) !== 0) { throw new CordovaError(`Destination "${dest}" for source file "${src}" is located outside the project`); }- shell.mkdir('-p', path.dirname(dest));+ fs.ensureDirSync(path.dirname(dest));if (link) {linkFileOrDirTree(src, dest);- } else if (fs.statSync(src).isDirectory()) {- // XXX shelljs decides to create a directory when -R|-r is used which sucks. http://goo.gl/nbsjq- shell.cp('-Rf', path.join(src, '/*'), dest);} else {- shell.cp('-f', src, dest);+ fs.copySync(src, dest);}}// Same as copy file but throws error if target existsfunction copyNewFile (plugin_dir, src, project_dir, dest, link) {- var target_path = path.resolve(project_dir, dest);- if (fs.existsSync(target_path)) { throw new CordovaError('"' + target_path + '" already exists!'); }+ const target_path = path.resolve(project_dir, dest);+ if (fs.existsSync(target_path)) { throw new CordovaError(`"${target_path}" already exists!`); }copyFile(plugin_dir, src, project_dir, dest, !!link);}function linkFileOrDirTree (src, dest) {if (fs.existsSync(dest)) {- shell.rm('-Rf', dest);+ fs.removeSync(dest);}if (fs.statSync(src).isDirectory()) {- shell.mkdir('-p', dest);- fs.readdirSync(src).forEach(function (entry) {+ fs.ensureDirSync(dest);+ fs.readdirSync(src).forEach(entry => {linkFileOrDirTree(path.join(src, entry), path.join(dest, entry));});} else {@@ -356,24 +352,24 @@ function linkFileOrDirTree (src, dest) {// checks if file exists and then deletes. Error if doesn't existfunction removeFile (project_dir, src) {- var file = path.resolve(project_dir, src);- shell.rm('-Rf', file);+ const file = path.resolve(project_dir, src);+ fs.removeSync(file);}// deletes file/directory without checkingfunction removeFileF (file) {- shell.rm('-Rf', file);+ fs.removeSync(file);}function removeFileAndParents (baseDir, destFile, stopper) {stopper = stopper || '.';- var file = path.resolve(baseDir, destFile);+ const file = path.resolve(baseDir, destFile);if (!fs.existsSync(file)) return;removeFileF(file);// check if directory is empty- var curDir = path.dirname(file);+ let curDir = path.dirname(file);while (curDir !== path.resolve(baseDir, stopper)) {if (fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) {@@ -387,5 +383,5 @@ function removeFileAndParents (baseDir, destFile, stopper) {}function generateAttributeError (attribute, element, id) {- return 'Required attribute "' + attribute + '" not specified in <' + element + '> element from plugin: ' + id;+ return `Required attribute "${attribute}" not specified in <${element}> element from plugin: ${id}`;}diff --git a/cordova/platforms/ios/cordova/lib/prepare.js b/cordova/platforms/ios/cordova/lib/prepare.jsindex 16ffd4e71..c98cb8f48 100755--- a/cordova/platforms/ios/cordova/lib/prepare.js+++ b/cordova/platforms/ios/cordova/lib/prepare.js@@ -18,53 +18,46 @@*/'use strict';-var Q = require('q');-var fs = require('fs');-var path = require('path');-var shell = require('shelljs');-var unorm = require('unorm');-var plist = require('plist');-var URL = require('url');-var events = require('cordova-common').events;-var xmlHelpers = require('cordova-common').xmlHelpers;-var ConfigParser = require('cordova-common').ConfigParser;-var CordovaError = require('cordova-common').CordovaError;-var PlatformJson = require('cordova-common').PlatformJson;-var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;-var PluginInfoProvider = require('cordova-common').PluginInfoProvider;-var FileUpdater = require('cordova-common').FileUpdater;-var projectFile = require('./projectFile');-var xcode = require('xcode');++const fs = require('fs-extra');+const path = require('path');+const unorm = require('unorm');+const plist = require('plist');+const URL = require('url');+const events = require('cordova-common').events;+const xmlHelpers = require('cordova-common').xmlHelpers;+const ConfigParser = require('cordova-common').ConfigParser;+const CordovaError = require('cordova-common').CordovaError;+const PlatformJson = require('cordova-common').PlatformJson;+const PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;+const PluginInfoProvider = require('cordova-common').PluginInfoProvider;+const FileUpdater = require('cordova-common').FileUpdater;+const projectFile = require('./projectFile');// launch storyboard and related constants-var LAUNCHIMAGE_BUILD_SETTING = 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME';-var LAUNCHIMAGE_BUILD_SETTING_VALUE = 'LaunchImage';-var UI_LAUNCH_STORYBOARD_NAME = 'UILaunchStoryboardName';-var CDV_LAUNCH_STORYBOARD_NAME = 'CDVLaunchScreen';-var IMAGESET_COMPACT_SIZE_CLASS = 'compact';-var CDV_ANY_SIZE_CLASS = 'any';+const IMAGESET_COMPACT_SIZE_CLASS = 'compact';+const CDV_ANY_SIZE_CLASS = 'any';module.exports.prepare = function (cordovaProject, options) {- var self = this;-- var platformJson = PlatformJson.load(this.locations.root, 'ios');- var munger = new PlatformMunger('ios', this.locations.root, platformJson, new PluginInfoProvider());+ const platformJson = PlatformJson.load(this.locations.root, 'ios');+ const munger = new PlatformMunger('ios', this.locations.root, platformJson, new PluginInfoProvider());this._config = updateConfigFile(cordovaProject.projectConfig, munger, this.locations);// Update own www dir with project's www assets and plugins' assets and js-files- return Q.when(updateWww(cordovaProject, this.locations))- .then(function () {- // update project according to config.xml changes.- return updateProject(self._config, self.locations);+ return updateWww(cordovaProject, this.locations)+ // update project according to config.xml changes.+ .then(() => updateProject(this._config, this.locations))+ .then(() => {+ updateIcons(cordovaProject, this.locations);+ updateLaunchStoryboardImages(cordovaProject, this.locations);+ updateBackgroundColor(cordovaProject, this.locations);+ updateFileResources(cordovaProject, this.locations);})- .then(function () {- updateIcons(cordovaProject, self.locations);- updateSplashScreens(cordovaProject, self.locations);- updateLaunchStoryboardImages(cordovaProject, self.locations);- updateFileResources(cordovaProject, self.locations);+ .then(() => {+ alertDeprecatedPreference(this._config);})- .then(function () {+ .then(() => {events.emit('verbose', 'Prepared iOS project successfully');});};@@ -74,22 +67,21 @@ module.exports.clean = function (options) {// been called from the platform shell script rather than the CLI. Check for the// noPrepare option passed in by the non-CLI clean script. If that's present, or if// there's no config.xml found at the project root, then don't clean prepared files.- var projectRoot = path.resolve(this.root, '../..');- var projectConfigFile = path.join(projectRoot, 'config.xml');+ const projectRoot = path.resolve(this.root, '../..');+ const projectConfigFile = path.join(projectRoot, 'config.xml');if ((options && options.noPrepare) || !fs.existsSync(projectConfigFile) ||!fs.existsSync(this.locations.configXml)) {- return Q();+ return Promise.resolve();}- var projectConfig = new ConfigParser(this.locations.configXml);+ const projectConfig = new ConfigParser(this.locations.configXml);- var self = this;- return Q().then(function () {- cleanWww(projectRoot, self.locations);- cleanIcons(projectRoot, projectConfig, self.locations);- cleanSplashScreens(projectRoot, projectConfig, self.locations);- cleanLaunchStoryboardImages(projectRoot, projectConfig, self.locations);- cleanFileResources(projectRoot, projectConfig, self.locations);+ return Promise.resolve().then(() => {+ cleanWww(projectRoot, this.locations);+ cleanIcons(projectRoot, projectConfig, this.locations);+ cleanLaunchStoryboardImages(projectRoot, projectConfig, this.locations);+ cleanBackgroundColor(projectRoot, projectConfig, this.locations);+ cleanFileResources(projectRoot, projectConfig, this.locations);});};@@ -108,11 +100,11 @@ module.exports.clean = function (options) {* configuration is already dumped to appropriate config.xml file.*/function updateConfigFile (sourceConfig, configMunger, locations) {- events.emit('verbose', 'Generating platform-specific config.xml from defaults for iOS at ' + locations.configXml);+ events.emit('verbose', `Generating platform-specific config.xml from defaults for iOS at ${locations.configXml}`);// First cleanup current config and merge project's one into own// Overwrite platform config.xml with defaults.xml.- shell.cp('-f', locations.defaultConfigXml, locations.configXml);+ fs.copySync(locations.defaultConfigXml, locations.configXml);// Then apply config changes from global munge to all config files// in project (including project's config)@@ -120,7 +112,7 @@ function updateConfigFile (sourceConfig, configMunger, locations) {events.emit('verbose', 'Merging project\'s config.xml into platform-specific iOS config.xml');// Merge changes from app's config.xml into platform's one- var config = new ConfigParser(locations.configXml);+ const config = new ConfigParser(locations.configXml);xmlHelpers.mergeXml(sourceConfig.doc.getroot(),config.doc.getroot(), 'ios', /* clobber= */true);@@ -132,7 +124,7 @@ function updateConfigFile (sourceConfig, configMunger, locations) {* Logs all file operations via the verbose event stream, indented.*/function logFileOp (message) {- events.emit('verbose', ' ' + message);+ events.emit('verbose', ` ${message}`);}/**@@ -145,31 +137,33 @@ function logFileOp (message) {* paths for www files.*/function updateWww (cordovaProject, destinations) {- var sourceDirs = [+ const sourceDirs = [path.relative(cordovaProject.root, cordovaProject.locations.www),path.relative(cordovaProject.root, destinations.platformWww)];// If project contains 'merges' for our platform, use them as another overrides- var merges_path = path.join(cordovaProject.root, 'merges', 'ios');+ const merges_path = path.join(cordovaProject.root, 'merges', 'ios');if (fs.existsSync(merges_path)) {events.emit('verbose', 'Found "merges/ios" folder. Copying its contents into the iOS project.');sourceDirs.push(path.join('merges', 'ios'));}- var targetDir = path.relative(cordovaProject.root, destinations.www);+ const targetDir = path.relative(cordovaProject.root, destinations.www);events.emit(- 'verbose', 'Merging and updating files from [' + sourceDirs.join(', ') + '] to ' + targetDir);+ 'verbose', `Merging and updating files from [${sourceDirs.join(', ')}] to ${targetDir}`);FileUpdater.mergeAndUpdateDir(sourceDirs, targetDir, { rootDir: cordovaProject.root }, logFileOp);++ return Promise.resolve();}/*** Cleans all files from the platform 'www' directory.*/function cleanWww (projectRoot, locations) {- var targetDir = path.relative(projectRoot, locations.www);- events.emit('verbose', 'Cleaning ' + targetDir);+ const targetDir = path.relative(projectRoot, locations.www);+ events.emit('verbose', `Cleaning ${targetDir}`);// No source paths are specified, so mergeAndUpdateDir() will clear the target directory.FileUpdater.mergeAndUpdateDir(@@ -184,168 +178,144 @@ function cleanWww (projectRoot, locations) {* @param {Object} locations A map of locations for this platform (In/Out)*/function updateProject (platformConfig, locations) {-// CB-6992 it is necessary to normalize characters// because node and shell scripts handles unicode symbols differently// We need to normalize the name to NFD form since iOS uses NFD unicode form- var name = unorm.nfd(platformConfig.name());- var version = platformConfig.version();- var displayName = platformConfig.shortName && platformConfig.shortName();+ const name = unorm.nfd(platformConfig.name());+ const version = platformConfig.version();+ const displayName = platformConfig.shortName && platformConfig.shortName();- var originalName = path.basename(locations.xcodeCordovaProj);+ const originalName = path.basename(locations.xcodeCordovaProj);// Update package id (bundle id)- var plistFile = path.join(locations.xcodeCordovaProj, originalName + '-Info.plist');- var infoPlist = plist.parse(fs.readFileSync(plistFile, 'utf8'));+ const plistFile = path.join(locations.xcodeCordovaProj, `${originalName}-Info.plist`);+ const infoPlist = plist.parse(fs.readFileSync(plistFile, 'utf8'));// Update version (bundle version)- infoPlist['CFBundleShortVersionString'] = version;- var CFBundleVersion = platformConfig.getAttribute('ios-CFBundleVersion') || default_CFBundleVersion(version);- infoPlist['CFBundleVersion'] = CFBundleVersion;+ infoPlist.CFBundleShortVersionString = version;+ const CFBundleVersion = platformConfig.getAttribute('ios-CFBundleVersion') || default_CFBundleVersion(version);+ infoPlist.CFBundleVersion = CFBundleVersion;if (platformConfig.getAttribute('defaultlocale')) {- infoPlist['CFBundleDevelopmentRegion'] = platformConfig.getAttribute('defaultlocale');+ infoPlist.CFBundleDevelopmentRegion = platformConfig.getAttribute('defaultlocale');}if (displayName) {- infoPlist['CFBundleDisplayName'] = displayName;+ infoPlist.CFBundleDisplayName = displayName;}// replace Info.plist ATS entries according to <access> and <allow-navigation> config.xml entries- var ats = writeATSEntries(platformConfig);+ const ats = writeATSEntries(platformConfig);if (Object.keys(ats).length > 0) {- infoPlist['NSAppTransportSecurity'] = ats;+ infoPlist.NSAppTransportSecurity = ats;} else {- delete infoPlist['NSAppTransportSecurity'];+ delete infoPlist.NSAppTransportSecurity;}handleOrientationSettings(platformConfig, infoPlist);- updateProjectPlistForLaunchStoryboard(platformConfig, infoPlist);/* eslint-disable no-tabs */// Write out the plist file with the same formatting as Xcode does- var info_contents = plist.build(infoPlist, { indent: '\t', offset: -1 });+ let info_contents = plist.build(infoPlist, { indent: '\t', offset: -1 });/* eslint-enable no-tabs */info_contents = info_contents.replace(/<string>[\s\r\n]*<\/string>/g, '<string></string>');fs.writeFileSync(plistFile, info_contents, 'utf-8');- events.emit('verbose', 'Wrote out iOS Bundle Version "' + version + '" to ' + plistFile);+ events.emit('verbose', `Wrote out iOS Bundle Version "${version}" to ${plistFile}`);- return handleBuildSettings(platformConfig, locations, infoPlist).then(function () {+ return handleBuildSettings(platformConfig, locations, infoPlist).then(() => {if (name === originalName) {- events.emit('verbose', 'iOS Product Name has not changed (still "' + originalName + '")');- return Q();+ events.emit('verbose', `iOS Product Name has not changed (still "${originalName}")`);+ return Promise.resolve();} else { // CB-11712 <name> was changed, we don't support it'- var errorString =+ const errorString ='The product name change (<name> tag) in config.xml is not supported dynamically.\n' +'To change your product name, you have to remove, then add your ios platform again.\n' +'Make sure you save your plugins beforehand using `cordova plugin save`.\n' +'\tcordova plugin save\n' +'\tcordova platform rm ios\n' +- '\tcordova platform add ios\n'- ;+ '\tcordova platform add ios\n';- return Q.reject(new CordovaError(errorString));+ return Promise.reject(new CordovaError(errorString));}});}function handleOrientationSettings (platformConfig, infoPlist) {-switch (getOrientationValue(platformConfig)) {case 'portrait':- infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationPortrait' ];- infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown' ];- infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown' ];+ infoPlist.UIInterfaceOrientation = ['UIInterfaceOrientationPortrait'];+ infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown'];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown'];break;case 'landscape':- infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationLandscapeLeft' ];- infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];- infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ infoPlist.UIInterfaceOrientation = ['UIInterfaceOrientationLandscapeLeft'];+ infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];break;case 'all':- infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationPortrait' ];- infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];- infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];+ infoPlist.UIInterfaceOrientation = ['UIInterfaceOrientationPortrait'];+ infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];break;case 'default':- infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];- infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ];- delete infoPlist['UIInterfaceOrientation'];+ infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];+ infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];+ delete infoPlist.UIInterfaceOrientation;}}function handleBuildSettings (platformConfig, locations, infoPlist) {- var pkg = platformConfig.getAttribute('ios-CFBundleIdentifier') || platformConfig.packageName();- var targetDevice = parseTargetDevicePreference(platformConfig.getPreference('target-device', 'ios'));- var deploymentTarget = platformConfig.getPreference('deployment-target', 'ios');- var needUpdatedBuildSettingsForLaunchStoryboard = checkIfBuildSettingsNeedUpdatedForLaunchStoryboard(platformConfig, infoPlist);- var swiftVersion = platformConfig.getPreference('SwiftVersion', 'ios');- var wkWebViewOnly = platformConfig.getPreference('WKWebViewOnly');+ const pkg = platformConfig.getAttribute('ios-CFBundleIdentifier') || platformConfig.packageName();+ const targetDevice = parseTargetDevicePreference(platformConfig.getPreference('target-device', 'ios'));+ const deploymentTarget = platformConfig.getPreference('deployment-target', 'ios');+ const swiftVersion = platformConfig.getPreference('SwiftVersion', 'ios');- var project;+ let project;try {project = projectFile.parse(locations);} catch (err) {- return Q.reject(new CordovaError('Could not parse ' + locations.pbxproj + ': ' + err));+ return Promise.reject(new CordovaError(`Could not parse ${locations.pbxproj}: ${err}`));}- var origPkg = project.xcode.getBuildProperty('PRODUCT_BUNDLE_IDENTIFIER');+ const origPkg = project.xcode.getBuildProperty('PRODUCT_BUNDLE_IDENTIFIER', undefined, platformConfig.name());// no build settings provided and we don't need to update build settings for launch storyboards,// then we don't need to parse and update .pbxproj file- if (origPkg === pkg && !targetDevice && !deploymentTarget && !needUpdatedBuildSettingsForLaunchStoryboard && !swiftVersion && !wkWebViewOnly) {- return Q();+ if (origPkg === pkg && !targetDevice && !deploymentTarget && !swiftVersion) {+ return Promise.resolve();}if (origPkg !== pkg) {- events.emit('verbose', 'Set PRODUCT_BUNDLE_IDENTIFIER to ' + pkg + '.');- project.xcode.updateBuildProperty('PRODUCT_BUNDLE_IDENTIFIER', pkg);+ events.emit('verbose', `Set PRODUCT_BUNDLE_IDENTIFIER to ${pkg}.`);+ project.xcode.updateBuildProperty('PRODUCT_BUNDLE_IDENTIFIER', pkg, null, platformConfig.name());}if (targetDevice) {- events.emit('verbose', 'Set TARGETED_DEVICE_FAMILY to ' + targetDevice + '.');+ events.emit('verbose', `Set TARGETED_DEVICE_FAMILY to ${targetDevice}.`);project.xcode.updateBuildProperty('TARGETED_DEVICE_FAMILY', targetDevice);}if (deploymentTarget) {- events.emit('verbose', 'Set IPHONEOS_DEPLOYMENT_TARGET to "' + deploymentTarget + '".');+ events.emit('verbose', `Set IPHONEOS_DEPLOYMENT_TARGET to "${deploymentTarget}".`);project.xcode.updateBuildProperty('IPHONEOS_DEPLOYMENT_TARGET', deploymentTarget);}if (swiftVersion) {- events.emit('verbose', 'Set SwiftVersion to "' + swiftVersion + '".');+ events.emit('verbose', `Set SwiftVersion to "${swiftVersion}".`);project.xcode.updateBuildProperty('SWIFT_VERSION', swiftVersion);}- if (wkWebViewOnly) {- var wkwebviewValue = '1';- if (wkWebViewOnly === 'true') {- events.emit('verbose', 'Set WK_WEB_VIEW_ONLY.');- } else {- wkwebviewValue = '0';- events.emit('verbose', 'Unset WK_WEB_VIEW_ONLY.');- }- project.xcode.updateBuildProperty('WK_WEB_VIEW_ONLY', wkwebviewValue);- var cordovaLibXcodePath = path.join(locations.root, 'CordovaLib', 'CordovaLib.xcodeproj');- var pbxPath = path.join(cordovaLibXcodePath, 'project.pbxproj');- var xcodeproj = xcode.project(pbxPath);- xcodeproj.parseSync();- xcodeproj.updateBuildProperty('WK_WEB_VIEW_ONLY', wkwebviewValue);- fs.writeFileSync(pbxPath, xcodeproj.writeSync());- }-- updateBuildSettingsForLaunchStoryboard(project.xcode, platformConfig, infoPlist);project.write();- return Q();+ return Promise.resolve();}function mapIconResources (icons, iconsDir) {// See https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html// for launch images sizes reference.- var platformIcons = [+ const platformIcons = [{ dest: 'icon-20.png', width: 20, height: 20 },{ dest: '[email protected]', width: 40, height: 40 },{ dest: '[email protected]', width: 60, height: 60 },@@ -373,11 +343,11 @@ function mapIconResources (icons, iconsDir) {{ dest: '[email protected]', width: 196, height: 196 }];- var pathMap = {};- platformIcons.forEach(function (item) {- var icon = icons.getBySize(item.width, item.height) || icons.getDefault();+ const pathMap = {};+ platformIcons.forEach(item => {+ const icon = icons.getBySize(item.width, item.height) || icons.getDefault();if (icon) {- var target = path.join(iconsDir, item.dest);+ const target = path.join(iconsDir, item.dest);pathMap[target] = icon.src;}});@@ -385,8 +355,8 @@ function mapIconResources (icons, iconsDir) {}function getIconsDir (projectRoot, platformProjDir) {- var iconsDir;- var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));+ let iconsDir;+ const xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));if (xcassetsExists) {iconsDir = path.join(platformProjDir, 'Images.xcassets/AppIcon.appiconset/');@@ -398,31 +368,31 @@ function getIconsDir (projectRoot, platformProjDir) {}function updateIcons (cordovaProject, locations) {- var icons = cordovaProject.projectConfig.getIcons('ios');+ const icons = cordovaProject.projectConfig.getIcons('ios');if (icons.length === 0) {events.emit('verbose', 'This app does not have icons defined');return;}- var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);- var iconsDir = getIconsDir(cordovaProject.root, platformProjDir);- var resourceMap = mapIconResources(icons, iconsDir);- events.emit('verbose', 'Updating icons at ' + iconsDir);+ const platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);+ const iconsDir = getIconsDir(cordovaProject.root, platformProjDir);+ const resourceMap = mapIconResources(icons, iconsDir);+ events.emit('verbose', `Updating icons at ${iconsDir}`);FileUpdater.updatePaths(resourceMap, { rootDir: cordovaProject.root }, logFileOp);}function cleanIcons (projectRoot, projectConfig, locations) {- var icons = projectConfig.getIcons('ios');+ const icons = projectConfig.getIcons('ios');if (icons.length > 0) {- var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);- var iconsDir = getIconsDir(projectRoot, platformProjDir);- var resourceMap = mapIconResources(icons, iconsDir);- Object.keys(resourceMap).forEach(function (targetIconPath) {+ const platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);+ const iconsDir = getIconsDir(projectRoot, platformProjDir);+ const resourceMap = mapIconResources(icons, iconsDir);+ Object.keys(resourceMap).forEach(targetIconPath => {resourceMap[targetIconPath] = null;});- events.emit('verbose', 'Cleaning icons at ' + iconsDir);+ events.emit('verbose', `Cleaning icons at ${iconsDir}`);// Source paths are removed from the map, so updatePaths() will delete the target files.FileUpdater.updatePaths(@@ -430,76 +400,120 @@ function cleanIcons (projectRoot, projectConfig, locations) {}}-function mapSplashScreenResources (splashScreens, splashScreensDir) {- var platformSplashScreens = [- { dest: 'Default~iphone.png', width: 320, height: 480 },- { dest: 'Default@2x~iphone.png', width: 640, height: 960 },- { dest: 'Default-Portrait~ipad.png', width: 768, height: 1024 },- { dest: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2048 },- { dest: 'Default-Landscape~ipad.png', width: 1024, height: 768 },- { dest: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 },- { dest: 'Default-568h@2x~iphone.png', width: 640, height: 1136 },- { dest: 'Default-667h.png', width: 750, height: 1334 },- { dest: 'Default-736h.png', width: 1242, height: 2208 },- { dest: 'Default-Landscape-736h.png', width: 2208, height: 1242 },- { dest: 'Default-2436h.png', width: 1125, height: 2436 },- { dest: 'Default-Landscape-2436h.png', width: 2436, height: 1125 }- ];-- var pathMap = {};- platformSplashScreens.forEach(function (item) {- var splash = splashScreens.getBySize(item.width, item.height);- if (splash) {- var target = path.join(splashScreensDir, item.dest);- pathMap[target] = splash.src;- }- });- return pathMap;+/**+ * Returns the directory for the BackgroundColor.colorset asset, or null if no+ * xcassets exist.+ *+ * @param {string} projectRoot The project's root directory+ * @param {string} platformProjDir The platform's project directory+ */+function getBackgroundColorDir (projectRoot, platformProjDir) {+ if (folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'))) {+ return path.join(platformProjDir, 'Images.xcassets', 'BackgroundColor.colorset');+ } else {+ return null;+ }}-function getSplashScreensDir (projectRoot, platformProjDir) {- var splashScreensDir;- var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));+function colorPreferenceToComponents (pref) {+ if (!pref || !pref.match(/^(#[0-9A-F]{3}|(0x|#)([0-9A-F]{2})?[0-9A-F]{6})$/)) {+ return {+ platform: 'ios',+ reference: 'systemBackgroundColor'+ };+ }- if (xcassetsExists) {- splashScreensDir = path.join(platformProjDir, 'Images.xcassets/LaunchImage.launchimage/');- } else {- splashScreensDir = path.join(platformProjDir, 'Resources/splash/');+ let red = 'FF';+ let green = 'FF';+ let blue = 'FF';+ let alpha = 1.0;++ if (pref[0] === '#' && pref.length === 4) {+ red = pref[1] + pref[1];+ green = pref[2] + pref[2];+ blue = pref[3] + pref[3];}- return splashScreensDir;-}+ if (pref.length >= 7 && (pref[0] === '#' || pref.substring(0, 2) === '0x')) {+ let offset = pref[0] === '#' ? 1 : 2;-function updateSplashScreens (cordovaProject, locations) {- var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios');+ if (pref.substring(offset).length === 8) {+ alpha = parseInt(pref.substring(offset, offset + 2), 16) / 255.0;+ offset += 2;+ }- if (splashScreens.length === 0) {- events.emit('verbose', 'This app does not have splash screens defined');- return;+ red = pref.substring(offset, offset + 2);+ green = pref.substring(offset + 2, offset + 4);+ blue = pref.substring(offset + 4, offset + 6);}- var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);- var splashScreensDir = getSplashScreensDir(cordovaProject.root, platformProjDir);- var resourceMap = mapSplashScreenResources(splashScreens, splashScreensDir);- events.emit('verbose', 'Updating splash screens at ' + splashScreensDir);- FileUpdater.updatePaths(- resourceMap, { rootDir: cordovaProject.root }, logFileOp);+ return {+ 'color-space': 'srgb',+ components: {+ red: '0x' + red,+ green: '0x' + green,+ blue: '0x' + blue,+ alpha: alpha.toFixed(3)+ }+ };}-function cleanSplashScreens (projectRoot, projectConfig, locations) {- var splashScreens = projectConfig.getSplashScreens('ios');- if (splashScreens.length > 0) {- var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);- var splashScreensDir = getSplashScreensDir(projectRoot, platformProjDir);- var resourceMap = mapIconResources(splashScreens, splashScreensDir);- Object.keys(resourceMap).forEach(function (targetSplashPath) {- resourceMap[targetSplashPath] = null;- });- events.emit('verbose', 'Cleaning splash screens at ' + splashScreensDir);+/**+ * Update the background color Contents.json in xcassets.+ *+ * @param {Object} cordovaProject The cordova project+ * @param {Object} locations A dictionary containing useful location paths+ */+function updateBackgroundColor (cordovaProject, locations) {+ const pref = cordovaProject.projectConfig.getPreference('BackgroundColor', 'ios') || '';++ const platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);+ const backgroundColorDir = getBackgroundColorDir(cordovaProject.root, platformProjDir);++ if (backgroundColorDir) {+ const contentsJSON = {+ colors: [{+ idiom: 'universal',+ color: colorPreferenceToComponents(pref)+ }],+ info: {+ author: 'Xcode',+ version: 1+ }+ };- // Source paths are removed from the map, so updatePaths() will delete the target files.- FileUpdater.updatePaths(- resourceMap, { rootDir: projectRoot, all: true }, logFileOp);+ events.emit('verbose', 'Updating Background Color color set Contents.json');+ fs.writeFileSync(path.join(cordovaProject.root, backgroundColorDir, 'Contents.json'),+ JSON.stringify(contentsJSON, null, 2));+ }+}++/**+ * Resets the background color Contents.json in xcassets to default.+ *+ * @param {string} projectRoot Path to the project root+ * @param {Object} projectConfig The project's config.xml+ * @param {Object} locations A dictionary containing useful location paths+ */+function cleanBackgroundColor (projectRoot, projectConfig, locations) {+ const platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);+ const backgroundColorDir = getBackgroundColorDir(projectRoot, platformProjDir);++ if (backgroundColorDir) {+ const contentsJSON = {+ colors: [{+ idiom: 'universal',+ color: colorPreferenceToComponents(null)+ }],+ info: {+ author: 'Xcode',+ version: 1+ }+ };++ events.emit('verbose', 'Cleaning Background Color color set Contents.json');+ fs.writeFileSync(path.join(projectRoot, backgroundColorDir, 'Contents.json'),+ JSON.stringify(contentsJSON, null, 2));}}@@ -515,9 +529,9 @@ function updateFileResources (cordovaProject, locations) {return;}- let resourceMap = {};- files.forEach(function (res) {- let src = res.src;+ const resourceMap = {};+ files.forEach(res => {+ const src = res.src;let target = res.target;if (!target) {@@ -530,30 +544,72 @@ function updateFileResources (cordovaProject, locations) {if (!fs.existsSync(targetPath)) {project.xcode.addResourceFile(target);} else {- events.emit('warn', 'Overwriting existing resource file at ' + targetPath);+ events.emit('warn', `Overwriting existing resource file at ${targetPath}`);}resourceMap[targetPath] = src;});- events.emit('verbose', 'Updating resource files at ' + platformDir);+ events.emit('verbose', `Updating resource files at ${platformDir}`);FileUpdater.updatePaths(resourceMap, { rootDir: cordovaProject.root }, logFileOp);project.write();}+function alertDeprecatedPreference (configParser) {+ const deprecatedToNewPreferences = {+ MediaPlaybackRequiresUserAction: {+ newPreference: 'MediaTypesRequiringUserActionForPlayback',+ isDeprecated: true+ },+ MediaPlaybackAllowsAirPlay: {+ newPreference: 'AllowsAirPlayForMediaPlayback',+ isDeprecated: false+ }+ };++ Object.keys(deprecatedToNewPreferences).forEach(oldKey => {+ if (configParser.getPreference(oldKey)) {+ const isDeprecated = deprecatedToNewPreferences[oldKey].isDeprecated;+ const verb = isDeprecated ? 'has been' : 'is being';+ const newPreferenceKey = deprecatedToNewPreferences[oldKey].newPreference;++ // Create the Log Message+ const log = [`The preference name "${oldKey}" ${verb} deprecated.`];+ if (newPreferenceKey) {+ log.push(`It is recommended to replace this preference with "${newPreferenceKey}."`);+ } else {+ log.push('There is no replacement for this preference.');+ }++ /**+ * If the preference has been deprecated, the usage of the old preference is no longer used.+ * Therefore, the following line is not appended. It is added only if the old preference is still used.+ * We are only keeping the top lines for deprecated items only for an additional major release when+ * the pre-warning was not provided in a past major release due to a necessary quick deprecation.+ * Typically caused by implementation nature or third-party requirement changes.+ */+ if (!isDeprecated) {+ log.push('Please note that this preference will be removed in the near future.');+ }++ events.emit('warn', log.join(' '));+ }+ });+}+function cleanFileResources (projectRoot, projectConfig, locations) {const platformDir = path.relative(projectRoot, locations.root);const files = projectConfig.getFileResources('ios', true);if (files.length > 0) {- events.emit('verbose', 'Cleaning resource files at ' + platformDir);+ events.emit('verbose', `Cleaning resource files at ${platformDir}`);const project = projectFile.parse(locations);- var resourceMap = {};- files.forEach(function (res) {- let src = res.src;+ const resourceMap = {};+ files.forEach(res => {+ const src = res.src;let target = res.target;if (!target) {@@ -592,7 +648,8 @@ function cleanFileResources (projectRoot, projectConfig, locations) {* height: 'any|com',* filename: undefined|'Default@scale~idiom~widthheight.png',* src: undefined|'path/to/original/matched/image/from/splash/screens.png',- * target: undefined|'path/to/asset/library/Default@scale~idiom~widthheight.png'+ * target: undefined|'path/to/asset/library/Default@scale~idiom~widthheight.png',+ * appearence: undefined|'dark'|'light'* }, ...* ]*@@ -601,51 +658,54 @@ function cleanFileResources (projectRoot, projectConfig, locations) {* @return {Array<Object>}*/function mapLaunchStoryboardContents (splashScreens, launchStoryboardImagesDir) {- var platformLaunchStoryboardImages = [];- var idioms = ['universal', 'ipad', 'iphone'];- var scalesForIdiom = {+ const platformLaunchStoryboardImages = [];+ const idioms = ['universal', 'ipad', 'iphone'];+ const scalesForIdiom = {universal: ['1x', '2x', '3x'],ipad: ['1x', '2x'],iphone: ['1x', '2x', '3x']};- var sizes = ['com', 'any'];-- idioms.forEach(function (idiom) {- scalesForIdiom[idiom].forEach(function (scale) {- sizes.forEach(function (width) {- sizes.forEach(function (height) {- var item = {- idiom: idiom,- scale: scale,- width: width,- height: height- };-- /* examples of the search pattern:- * scale ~ idiom ~ width height- * @2x ~ universal ~ any any- * @3x ~ iphone ~ com any- * @2x ~ ipad ~ com any- */- var searchPattern = '@' + scale + '~' + idiom + '~' + width + height;-- /* because old node versions don't have Array.find, the below is- * functionally equivalent to this:- * var launchStoryboardImage = splashScreens.find(function(item) {- * return item.src.indexOf(searchPattern) >= 0;- * });- */- var launchStoryboardImage = splashScreens.reduce(function (p, c) {- return (c.src.indexOf(searchPattern) >= 0) ? c : p;- }, undefined);-- if (launchStoryboardImage) {- item.filename = 'Default' + searchPattern + '.png';- item.src = launchStoryboardImage.src;- item.target = path.join(launchStoryboardImagesDir, item.filename);- }-- platformLaunchStoryboardImages.push(item);+ const sizes = ['com', 'any'];+ const appearences = ['', 'dark', 'light'];++ idioms.forEach(idiom => {+ scalesForIdiom[idiom].forEach(scale => {+ sizes.forEach(width => {+ sizes.forEach(height => {+ appearences.forEach(appearence => {+ const item = { idiom, scale, width, height };++ if (appearence !== '') {+ item.appearence = appearence;+ }++ /* examples of the search pattern:+ * scale ~ idiom ~ width height ~ appearence+ * @2x ~ universal ~ any any+ * @3x ~ iphone ~ com any ~ dark+ * @2x ~ ipad ~ com any ~ light+ */+ const searchPattern = '@' + scale + '~' + idiom + '~' + width + height + (appearence ? '~' + appearence : '');++ /* because old node versions don't have Array.find, the below is+ * functionally equivalent to this:+ * var launchStoryboardImage = splashScreens.find(function(item) {+ * return (item.src.indexOf(searchPattern) >= 0) ? (appearence !== '' ? true : ((item.src.indexOf(searchPattern + '~light') >= 0 || (item.src.indexOf(searchPattern + '~dark') >= 0)) ? false : true)) : false;+ * });+ */+ const launchStoryboardImage = splashScreens.reduce(+ (p, c) => (c.src.indexOf(searchPattern) >= 0) ? (appearence !== '' ? c : ((c.src.indexOf(searchPattern + '~light') >= 0 || (c.src.indexOf(searchPattern + '~dark') >= 0)) ? p : c)) : p,+ undefined+ );++ if (launchStoryboardImage) {+ item.filename = `Default${searchPattern}.png`;+ item.src = launchStoryboardImage.src;+ item.target = path.join(launchStoryboardImagesDir, item.filename);+ }++ platformLaunchStoryboardImages.push(item);+ });});});});@@ -669,9 +729,9 @@ function mapLaunchStoryboardContents (splashScreens, launchStoryboardImagesDir)* @return {Object}*/function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir) {- var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);- var pathMap = {};- platformLaunchStoryboardImages.forEach(function (item) {+ const platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);+ const pathMap = {};+ platformLaunchStoryboardImages.forEach(item => {if (item.target) {pathMap[item.target] = item.src;}@@ -691,6 +751,7 @@ function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir)* scale: '1x|2x|3x',* width-class: undefined|'compact',* height-class: undefined|'compact'+ * ...* }, ...* ],* info: {@@ -707,17 +768,16 @@ function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir)* @return {Object}*/function getLaunchStoryboardContentsJSON (splashScreens, launchStoryboardImagesDir) {-- var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);- var contentsJSON = {+ const platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);+ const contentsJSON = {images: [],info: {author: 'Xcode',version: 1}};- contentsJSON.images = platformLaunchStoryboardImages.map(function (item) {- var newItem = {+ contentsJSON.images = platformLaunchStoryboardImages.map(item => {+ const newItem = {idiom: item.idiom,scale: item.scale};@@ -731,6 +791,10 @@ function getLaunchStoryboardContentsJSON (splashScreens, launchStoryboardImagesDnewItem['height-class'] = IMAGESET_COMPACT_SIZE_CLASS;}+ if (item.appearence) {+ newItem.appearances = [{ appearance: 'luminosity', value: item.appearence }];+ }+// Xcode doesn't want a filename property if there's no image for these traitsif (item.filename) {newItem.filename = item.filename;@@ -740,107 +804,6 @@ function getLaunchStoryboardContentsJSON (splashScreens, launchStoryboardImagesDreturn contentsJSON;}-/**- * Determines if the project's build settings may need to be updated for launch storyboard support- *- */-function checkIfBuildSettingsNeedUpdatedForLaunchStoryboard (platformConfig, infoPlist) {- var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig);- var hasLegacyLaunchImages = platformHasLegacyLaunchImages(platformConfig);- var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME];-- if (hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME && !hasLegacyLaunchImages) {- // don't need legacy launch images if we are using our launch storyboard- // so we do need to update the project file- events.emit('verbose', 'Need to update build settings because project is using our launch storyboard.');- return true;- } else if (hasLegacyLaunchImages && !currentLaunchStoryboard) {- // we do need to ensure legacy launch images are used if there's no launch storyboard present- // so we do need to update the project file- events.emit('verbose', 'Need to update build settings because project is using legacy launch images and no storyboard.');- return true;- }- events.emit('verbose', 'No need to update build settings for launch storyboard support.');- return false;-}--function updateBuildSettingsForLaunchStoryboard (proj, platformConfig, infoPlist) {- var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig);- var hasLegacyLaunchImages = platformHasLegacyLaunchImages(platformConfig);- var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME];-- if (hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME && !hasLegacyLaunchImages) {- // don't need legacy launch images if we are using our launch storyboard- events.emit('verbose', 'Removed ' + LAUNCHIMAGE_BUILD_SETTING + ' because project is using our launch storyboard.');- proj.removeBuildProperty(LAUNCHIMAGE_BUILD_SETTING);- } else if (hasLegacyLaunchImages && !currentLaunchStoryboard) {- // we do need to ensure legacy launch images are used if there's no launch storyboard present- events.emit('verbose', 'Set ' + LAUNCHIMAGE_BUILD_SETTING + ' to ' + LAUNCHIMAGE_BUILD_SETTING_VALUE + ' because project is using legacy launch images and no storyboard.');- proj.updateBuildProperty(LAUNCHIMAGE_BUILD_SETTING, LAUNCHIMAGE_BUILD_SETTING_VALUE);- } else {- events.emit('verbose', 'Did not update build settings for launch storyboard support.');- }-}--function splashScreensHaveLaunchStoryboardImages (contentsJSON) {- /* do we have any launch images do we have for our launch storyboard?- * Again, for old Node versions, the below code is equivalent to this:- * return !!contentsJSON.images.find(function (item) {- * return item.filename !== undefined;- * });- */- return !!contentsJSON.images.reduce(function (p, c) {- return (c.filename !== undefined) ? c : p;- }, undefined);-}--function platformHasLaunchStoryboardImages (platformConfig) {- var splashScreens = platformConfig.getSplashScreens('ios');- var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, ''); // note: we don't need a file path here; we're just counting- return splashScreensHaveLaunchStoryboardImages(contentsJSON);-}--function platformHasLegacyLaunchImages (platformConfig) {- var splashScreens = platformConfig.getSplashScreens('ios');- return !!splashScreens.reduce(function (p, c) {- return (c.width !== undefined || c.height !== undefined) ? c : p;- }, undefined);-}--/**- * Updates the project's plist based upon our launch storyboard images. If there are no images, then we should- * fall back to the regular launch images that might be supplied (that is, our app will be scaled on an iPad Pro),- * and if there are some images, we need to alter the UILaunchStoryboardName property to point to- * CDVLaunchScreen.- *- * There's some logic here to avoid overwriting changes the user might have made to their plist if they are using- * their own launch storyboard.- */-function updateProjectPlistForLaunchStoryboard (platformConfig, infoPlist) {- var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME];- events.emit('verbose', 'Current launch storyboard ' + currentLaunchStoryboard);-- var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig);-- if (hasLaunchStoryboardImages && !currentLaunchStoryboard) {- // only change the launch storyboard if we have images to use AND the current value is blank- // if it's not blank, we've either done this before, or the user has their own launch storyboard- events.emit('verbose', 'Changing info plist to use our launch storyboard');- infoPlist[UI_LAUNCH_STORYBOARD_NAME] = CDV_LAUNCH_STORYBOARD_NAME;- return;- }-- if (!hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME) {- // only revert to using the launch images if we have don't have any images for the launch storyboard- // but only clear it if current launch storyboard is our storyboard; the user might be using their- // own storyboard instead.- events.emit('verbose', 'Changing info plist to use legacy launch images');- delete infoPlist[UI_LAUNCH_STORYBOARD_NAME];- return;- }- events.emit('verbose', 'Not changing launch storyboard setting in info plist.');-}-/*** Returns the directory for the Launch Storyboard image set, if image sets are being used. If they aren't* being used, returns null.@@ -849,8 +812,8 @@ function updateProjectPlistForLaunchStoryboard (platformConfig, infoPlist) {* @param {string} platformProjDir The platform's project directory*/function getLaunchStoryboardImagesDir (projectRoot, platformProjDir) {- var launchStoryboardImagesDir;- var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));+ let launchStoryboardImagesDir;+ const xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/'));if (xcassetsExists) {launchStoryboardImagesDir = path.join(platformProjDir, 'Images.xcassets/LaunchStoryboard.imageset/');@@ -869,15 +832,15 @@ function getLaunchStoryboardImagesDir (projectRoot, platformProjDir) {* @param {Object} locations A dictionary containing useful location paths*/function updateLaunchStoryboardImages (cordovaProject, locations) {- var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios');- var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);- var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(cordovaProject.root, platformProjDir);+ const splashScreens = cordovaProject.projectConfig.getSplashScreens('ios');+ const platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);+ const launchStoryboardImagesDir = getLaunchStoryboardImagesDir(cordovaProject.root, platformProjDir);if (launchStoryboardImagesDir) {- var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir);- var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir);+ const resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir);+ const contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir);- events.emit('verbose', 'Updating launch storyboard images at ' + launchStoryboardImagesDir);+ events.emit('verbose', `Updating launch storyboard images at ${launchStoryboardImagesDir}`);FileUpdater.updatePaths(resourceMap, { rootDir: cordovaProject.root }, logFileOp);@@ -896,24 +859,24 @@ function updateLaunchStoryboardImages (cordovaProject, locations) {* @param {Object} locations A dictionary containing useful location paths*/function cleanLaunchStoryboardImages (projectRoot, projectConfig, locations) {- var splashScreens = projectConfig.getSplashScreens('ios');- var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);- var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(projectRoot, platformProjDir);+ const splashScreens = projectConfig.getSplashScreens('ios');+ const platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);+ const launchStoryboardImagesDir = getLaunchStoryboardImagesDir(projectRoot, platformProjDir);if (launchStoryboardImagesDir) {- var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir);- var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir);+ const resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir);+ const contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir);- Object.keys(resourceMap).forEach(function (targetPath) {+ Object.keys(resourceMap).forEach(targetPath => {resourceMap[targetPath] = null;});- events.emit('verbose', 'Cleaning storyboard image set at ' + launchStoryboardImagesDir);+ events.emit('verbose', `Cleaning storyboard image set at ${launchStoryboardImagesDir}`);// Source paths are removed from the map, so updatePaths() will delete the target files.FileUpdater.updatePaths(resourceMap, { rootDir: projectRoot, all: true }, logFileOp);// delete filename from contents.json- contentsJSON.images.forEach(function (image) {+ contentsJSON.images.forEach(image => {image.filename = undefined;});@@ -933,10 +896,9 @@ function cleanLaunchStoryboardImages (projectRoot, projectConfig, locations) {* (or empty string if both are undefined).*/function getOrientationValue (platformConfig) {+ const ORIENTATION_DEFAULT = 'default';- var ORIENTATION_DEFAULT = 'default';-- var orientation = platformConfig.getPreference('orientation');+ let orientation = platformConfig.getPreference('orientation');if (!orientation) {return '';}@@ -948,8 +910,7 @@ function getOrientationValue (platformConfig) {return orientation;}- events.emit('warn', 'Unrecognized value for Orientation preference: ' + orientation +- '. Defaulting to value: ' + ORIENTATION_DEFAULT + '.');+ events.emit('warn', `Unrecognized value for Orientation preference: ${orientation}. Defaulting to value: ${ORIENTATION_DEFAULT}.`);return ORIENTATION_DEFAULT;}@@ -975,20 +936,20 @@ function getOrientationValue (platformConfig) {}*/function processAccessAndAllowNavigationEntries (config) {- var accesses = config.getAccesses();- var allow_navigations = config.getAllowNavigations();+ const accesses = config.getAccesses();+ const allow_navigations = config.getAllowNavigations();return allow_navigations// we concat allow_navigations and accesses, after processing accesses- .concat(accesses.map(function (obj) {+ .concat(accesses.map(obj => {// map accesses to a common key interface using 'href', not originobj.href = obj.origin;delete obj.origin;return obj;}))// we reduce the array to an object with all the entries processed (key is Hostname)- .reduce(function (previousReturn, currentElement) {- var options = {+ .reduce((previousReturn, currentElement) => {+ const options = {minimum_tls_version: currentElement.minimum_tls_version,requires_forward_secrecy: currentElement.requires_forward_secrecy,requires_certificate_transparency: currentElement.requires_certificate_transparency,@@ -996,16 +957,16 @@ function processAccessAndAllowNavigationEntries (config) {allows_arbitrary_loads_in_web_content: currentElement.allows_arbitrary_loads_in_web_content,allows_local_networking: currentElement.allows_local_networking};- var obj = parseWhitelistUrlForATS(currentElement.href, options);+ const obj = parseWhitelistUrlForATS(currentElement.href, options);if (obj) {// we 'union' duplicate entries- var item = previousReturn[obj.Hostname];+ let item = previousReturn[obj.Hostname];if (!item) {item = {};}- for (var o in obj) {- if (obj.hasOwnProperty(o)) {+ for (const o in obj) {+ if (Object.prototype.hasOwnProperty.call(obj, o)) {item[o] = obj[o];}}@@ -1037,15 +998,15 @@ function processAccessAndAllowNavigationEntries (config) {*/function parseWhitelistUrlForATS (url, options) {// @todo 'url.parse' was deprecated since v11.0.0. Use 'url.URL' constructor instead.- var href = URL.parse(url); // eslint-disable-line- var retObj = {};+ const href = URL.parse(url); // eslint-disable-line+ const retObj = {};retObj.Hostname = href.hostname;// Guiding principle: we only set values in retObj if they are NOT the defaultif (url === '*') {retObj.Hostname = '*';- var val;+ let val;val = (options.allows_arbitrary_loads_in_web_content === 'true');if (options.allows_arbitrary_loads_in_web_content && val) { // default is false@@ -1067,9 +1028,9 @@ function parseWhitelistUrlForATS (url, options) {if (!retObj.Hostname) {// check origin, if it allows subdomains (wildcard in hostname), we set NSIncludesSubdomains to YES. Default is NO- var subdomain1 = '/*.'; // wildcard in hostname- var subdomain2 = '*://*.'; // wildcard in hostname and protocol- var subdomain3 = '*://'; // wildcard in protocol only+ const subdomain1 = '/*.'; // wildcard in hostname+ const subdomain2 = '*://*.'; // wildcard in hostname and protocol+ const subdomain3 = '*://'; // wildcard in protocol onlyif (!href.pathname) {return null;} else if (href.pathname.indexOf(subdomain1) === 0) {@@ -1090,12 +1051,12 @@ function parseWhitelistUrlForATS (url, options) {retObj.NSExceptionMinimumTLSVersion = options.minimum_tls_version;}- var rfs = (options.requires_forward_secrecy === 'true');+ const rfs = (options.requires_forward_secrecy === 'true');if (options.requires_forward_secrecy && !rfs) { // default is trueretObj.NSExceptionRequiresForwardSecrecy = false;}- var rct = (options.requires_certificate_transparency === 'true');+ const rct = (options.requires_certificate_transparency === 'true');if (options.requires_certificate_transparency && rct) { // default is falseretObj.NSRequiresCertificateTransparency = true;}@@ -1115,48 +1076,48 @@ function parseWhitelistUrlForATS (url, options) {in config.xml*/function writeATSEntries (config) {- var pObj = processAccessAndAllowNavigationEntries(config);+ const pObj = processAccessAndAllowNavigationEntries(config);- var ats = {};+ const ats = {};- for (var hostname in pObj) {- if (pObj.hasOwnProperty(hostname)) {- var entry = pObj[hostname];+ for (const hostname in pObj) {+ if (Object.prototype.hasOwnProperty.call(pObj, hostname)) {+ const entry = pObj[hostname];// Guiding principle: we only set values if they are availableif (hostname === '*') {// always write this, for iOS 9, since in iOS 10 it will be overriden if// any of the other three keys are written- ats['NSAllowsArbitraryLoads'] = true;+ ats.NSAllowsArbitraryLoads = true;// at least one of the overriding keys is presentif (entry.NSAllowsArbitraryLoadsInWebContent) {- ats['NSAllowsArbitraryLoadsInWebContent'] = true;+ ats.NSAllowsArbitraryLoadsInWebContent = true;}if (entry.NSAllowsArbitraryLoadsForMedia) {- ats['NSAllowsArbitraryLoadsForMedia'] = true;+ ats.NSAllowsArbitraryLoadsForMedia = true;}if (entry.NSAllowsLocalNetworking) {- ats['NSAllowsLocalNetworking'] = true;+ ats.NSAllowsLocalNetworking = true;}continue;}- var exceptionDomain = {};+ const exceptionDomain = {};- for (var key in entry) {- if (entry.hasOwnProperty(key) && key !== 'Hostname') {+ for (const key in entry) {+ if (Object.prototype.hasOwnProperty.call(entry, key) && key !== 'Hostname') {exceptionDomain[key] = entry[key];}}- if (!ats['NSExceptionDomains']) {- ats['NSExceptionDomains'] = {};+ if (!ats.NSExceptionDomains) {+ ats.NSExceptionDomains = {};}- ats['NSExceptionDomains'][hostname] = exceptionDomain;+ ats.NSExceptionDomains[hostname] = exceptionDomain;}}@@ -1165,7 +1126,7 @@ function writeATSEntries (config) {function folderExists (folderPath) {try {- var stat = fs.statSync(folderPath);+ const stat = fs.statSync(folderPath);return stat && stat.isDirectory();} catch (e) {return false;@@ -1181,10 +1142,10 @@ function default_CFBundleVersion (version) {// Converts cordova specific representation of target device to XCode valuefunction parseTargetDevicePreference (value) {if (!value) return null;- var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"' };+ const map = { universal: '"1,2"', handset: '"1"', tablet: '"2"' };if (map[value.toLowerCase()]) {return map[value.toLowerCase()];}- events.emit('warn', 'Unrecognized value for target-device preference: ' + value + '.');+ events.emit('warn', `Unrecognized value for target-device preference: ${value}.`);return null;}diff --git a/cordova/platforms/ios/cordova/lib/projectFile.js b/cordova/platforms/ios/cordova/lib/projectFile.jsindex 8a3f7e516..3e1e83048 100755--- a/cordova/platforms/ios/cordova/lib/projectFile.js+++ b/cordova/platforms/ios/cordova/lib/projectFile.js@@ -17,47 +17,46 @@under the License.*/-var xcode = require('xcode');-var plist = require('plist');-var _ = require('underscore');-var path = require('path');-var fs = require('fs');-var shell = require('shelljs');+const xcode = require('xcode');+const plist = require('plist');+const _ = require('underscore');+const path = require('path');+const fs = require('fs-extra');-var pluginHandlers = require('./plugman/pluginHandlers');-var CordovaError = require('cordova-common').CordovaError;+const pluginHandlers = require('./plugman/pluginHandlers');+const CordovaError = require('cordova-common').CordovaError;-var cachedProjectFiles = {};+const cachedProjectFiles = {};function parseProjectFile (locations) {- var project_dir = locations.root;- var pbxPath = locations.pbxproj;+ const project_dir = locations.root;+ const pbxPath = locations.pbxproj;if (cachedProjectFiles[project_dir]) {return cachedProjectFiles[project_dir];}- var xcodeproj = xcode.project(pbxPath);+ const xcodeproj = xcode.project(pbxPath);xcodeproj.parseSync();- var xcBuildConfiguration = xcodeproj.pbxXCBuildConfigurationSection();- var plist_file_entry = _.find(xcBuildConfiguration, function (entry) { return entry.buildSettings && entry.buildSettings.INFOPLIST_FILE; });- var plist_file = path.join(project_dir, plist_file_entry.buildSettings.INFOPLIST_FILE.replace(/^"(.*)"$/g, '$1').replace(/\\&/g, '&'));- var config_file = path.join(path.dirname(plist_file), 'config.xml');+ const xcBuildConfiguration = xcodeproj.pbxXCBuildConfigurationSection();+ const plist_file_entry = _.find(xcBuildConfiguration, entry => entry.buildSettings && entry.buildSettings.INFOPLIST_FILE);+ const plist_file = path.join(project_dir, plist_file_entry.buildSettings.INFOPLIST_FILE.replace(/^"(.*)"$/g, '$1').replace(/\\&/g, '&'));+ const config_file = path.join(path.dirname(plist_file), 'config.xml');if (!fs.existsSync(plist_file) || !fs.existsSync(config_file)) {throw new CordovaError('Could not find *-Info.plist file, or config.xml file.');}- var frameworks_file = path.join(project_dir, 'frameworks.json');- var frameworks = {};+ const frameworks_file = path.join(project_dir, 'frameworks.json');+ let frameworks = {};try {frameworks = require(frameworks_file);} catch (e) { }- var xcode_dir = path.dirname(plist_file);- var pluginsDir = path.resolve(xcode_dir, 'Plugins');- var resourcesDir = path.resolve(xcode_dir, 'Resources');+ const xcode_dir = path.dirname(plist_file);+ const pluginsDir = path.resolve(xcode_dir, 'Plugins');+ const resourcesDir = path.resolve(xcode_dir, 'Resources');cachedProjectFiles[project_dir] = {plugins_dir: pluginsDir,@@ -72,13 +71,21 @@ function parseProjectFile (locations) {fs.writeFileSync(pbxPath, xcodeproj.writeSync());if (Object.keys(this.frameworks).length === 0) {// If there is no framework references remain in the project, just remove this file- shell.rm('-rf', frameworks_file);+ fs.removeSync(frameworks_file);return;}fs.writeFileSync(frameworks_file, JSON.stringify(this.frameworks, null, 4));},getPackageName: function () {- return plist.parse(fs.readFileSync(plist_file, 'utf8')).CFBundleIdentifier;+ const packageName = plist.parse(fs.readFileSync(plist_file, 'utf8')).CFBundleIdentifier;+ let bundleIdentifier = packageName;++ const variables = packageName.match(/\$\((\w+)\)/); // match $(VARIABLE), if any+ if (variables && variables.length >= 2) {+ bundleIdentifier = xcodeproj.getBuildProperty(variables[1]);+ }++ return bundleIdentifier.replace(/^"/, '').replace(/"$/, '');},getInstaller: function (name) {return pluginHandlers.getInstaller(name);@@ -86,7 +93,7 @@ function parseProjectFile (locations) {getUninstaller: function (name) {return pluginHandlers.getUninstaller(name);},- frameworks: frameworks+ frameworks};return cachedProjectFiles[project_dir];}@@ -97,7 +104,7 @@ function purgeProjectFileCache (project_dir) {module.exports = {parse: parseProjectFile,- purgeProjectFileCache: purgeProjectFileCache+ purgeProjectFileCache};xcode.project.prototype.pbxEmbedFrameworksBuildPhaseObj = function (target) {@@ -105,25 +112,23 @@ xcode.project.prototype.pbxEmbedFrameworksBuildPhaseObj = function (target) {};xcode.project.prototype.addToPbxEmbedFrameworksBuildPhase = function (file) {- var sources = this.pbxEmbedFrameworksBuildPhaseObj(file.target);+ const sources = this.pbxEmbedFrameworksBuildPhaseObj(file.target);if (sources) {sources.files.push(pbxBuildPhaseObj(file));}};xcode.project.prototype.removeFromPbxEmbedFrameworksBuildPhase = function (file) {- var sources = this.pbxEmbedFrameworksBuildPhaseObj(file.target);+ const sources = this.pbxEmbedFrameworksBuildPhaseObj(file.target);if (sources) {- sources.files = _.reject(sources.files, function (file) {- return file.comment === longComment(file);- });+ sources.files = _.reject(sources.files, file => file.comment === longComment(file));}};// special handlers to add frameworks to the 'Embed Frameworks' build phase, needed for custom frameworks// see CB-9517. should probably be moved to node-xcode.-var util = require('util');+const util = require('util');function pbxBuildPhaseObj (file) {- var obj = Object.create(null);+ const obj = Object.create(null);obj.value = file.uuid;obj.comment = longComment(file);return obj;diff --git a/cordova/platforms/ios/cordova/lib/run.js b/cordova/platforms/ios/cordova/lib/run.jsindex f21fee69b..bfee64f06 100755--- a/cordova/platforms/ios/cordova/lib/run.js+++ b/cordova/platforms/ios/cordova/lib/run.js@@ -17,24 +17,23 @@under the License.*/-var Q = require('q');-var path = require('path');-var build = require('./build');-var shell = require('shelljs');-var superspawn = require('cordova-common').superspawn;-var check_reqs = require('./check_reqs');-var fs = require('fs-extra');+const path = require('path');+const build = require('./build');+const {+ CordovaError,+ events,+ superspawn: { spawn }+} = require('cordova-common');+const check_reqs = require('./check_reqs');+const fs = require('fs-extra');-var events = require('cordova-common').events;--var cordovaPath = path.join(__dirname, '..');-var projectPath = path.join(__dirname, '..', '..');--module.exports.run = function (runOptions) {+const cordovaPath = path.join(__dirname, '..');+const projectPath = path.join(__dirname, '..', '..');+module.exports.run = runOptions => {// Validate argsif (runOptions.device && runOptions.emulator) {- return Q.reject('Only one of "device"/"emulator" options should be specified');+ return Promise.reject(new CordovaError('Only one of "device"/"emulator" options should be specified'));}// support for CB-8168 `cordova/run --list`@@ -42,15 +41,13 @@ module.exports.run = function (runOptions) {if (runOptions.device) return module.exports.listDevices();if (runOptions.emulator) return module.exports.listEmulators();// if no --device or --emulator flag is specified, list both devices and emulators- return module.exports.listDevices().then(function () {- return module.exports.listEmulators();- });+ return module.exports.listDevices().then(() => module.exports.listEmulators());}- var useDevice = !!runOptions.device;+ let useDevice = !!runOptions.device;- return require('./list-devices').run()- .then(function (devices) {+ return require('./listDevices').run()+ .then(devices => {if (devices.length > 0 && !(runOptions.emulator)) {useDevice = true;// we also explicitly set device flag in options as we pass@@ -58,56 +55,56 @@ module.exports.run = function (runOptions) {runOptions.device = true;return check_reqs.check_ios_deploy();}- }).then(function () {+ }).then(() => {if (!runOptions.nobuild) {return build.run(runOptions);} else {- return Q.resolve();+ return Promise.resolve();}- }).then(function () {- return build.findXCodeProjectIn(projectPath);- }).then(function (projectName) {- var appPath = path.join(projectPath, 'build', 'emulator', projectName + '.app');- var buildOutputDir = path.join(projectPath, 'build', 'device');+ }).then(() => build.findXCodeProjectIn(projectPath))+ .then(projectName => {+ let appPath = path.join(projectPath, 'build', 'emulator', `${projectName}.app`);+ const buildOutputDir = path.join(projectPath, 'build', 'device');// select command to run and arguments depending whether// we're running on device/emulatorif (useDevice) {return module.exports.checkDeviceConnected()- .then(function () {+ .then(() => {// Unpack IPA- var ipafile = path.join(buildOutputDir, projectName + '.ipa');+ const ipafile = path.join(buildOutputDir, `${projectName}.ipa`);// unpack the existing platform/ios/build/device/appname.ipa (zipfile), will create a Payload folder- return superspawn.spawn('unzip', [ '-o', '-qq', ipafile ], { cwd: buildOutputDir, printCommand: true, stdio: 'inherit' });+ return spawn('unzip', ['-o', '-qq', ipafile], { cwd: buildOutputDir, printCommand: true, stdio: 'inherit' });})- .then(function () {+ .then(() => {// Uncompress IPA (zip file)- var appFileInflated = path.join(buildOutputDir, 'Payload', projectName + '.app');- var appFile = path.join(buildOutputDir, projectName + '.app');- var payloadFolder = path.join(buildOutputDir, 'Payload');+ const appFileInflated = path.join(buildOutputDir, 'Payload', `${projectName}.app`);+ const appFile = path.join(buildOutputDir, `${projectName}.app`);+ const payloadFolder = path.join(buildOutputDir, 'Payload');// delete the existing platform/ios/build/device/appname.appfs.removeSync(appFile);// move the platform/ios/build/device/Payload/appname.app to parent- shell.mv('-f', appFileInflated, buildOutputDir);+ fs.moveSync(appFileInflated, buildOutputDir);// delete the platform/ios/build/device/Payload folder- shell.rm('-rf', payloadFolder);+ fs.removeSync(payloadFolder);return null;})- .then(function () {- appPath = path.join(projectPath, 'build', 'device', projectName + '.app');- var extraArgs = [];- if (runOptions.argv) {- // argv.slice(2) removes node and run.js, filterSupportedArgs removes the run.js args- extraArgs = module.exports.filterSupportedArgs(runOptions.argv.slice(2));- }- return module.exports.deployToDevice(appPath, runOptions.target, extraArgs);- }, function () {+ .then(+ () => {+ appPath = path.join(projectPath, 'build', 'device', `${projectName}.app`);+ let extraArgs = [];+ if (runOptions.argv) {+ // argv.slice(2) removes node and run.js, filterSupportedArgs removes the run.js args+ extraArgs = module.exports.filterSupportedArgs(runOptions.argv.slice(2));+ }+ return module.exports.deployToDevice(appPath, runOptions.target, extraArgs);+ },// if device connection check failed use emulator then- return module.exports.deployToSim(appPath, runOptions.target);- });+ () => module.exports.deployToSim(appPath, runOptions.target)+ );} else {return module.exports.deployToSim(appPath, runOptions.target);}@@ -128,11 +125,11 @@ module.exports.listEmulators = listEmulators;* @return {Array} array with unsupported args for the 'run' command*/function filterSupportedArgs (args) {- var filtered = [];- var sargs = ['--device', '--emulator', '--nobuild', '--list', '--target', '--debug', '--release'];- var re = new RegExp(sargs.join('|'));+ const filtered = [];+ const sargs = ['--device', '--emulator', '--nobuild', '--list', '--target', '--debug', '--release'];+ const re = new RegExp(sargs.join('|'));- args.forEach(function (element) {+ args.forEach(element => {// supported args not found, we add// we do a regex search because --target can be "--target=XXX"if (element.search(re) === -1) {@@ -148,7 +145,7 @@ function filterSupportedArgs (args) {* @return {Promise} Fullfilled when any device is connected, rejected otherwise*/function checkDeviceConnected () {- return superspawn.spawn('ios-deploy', ['-c', '-t', '1'], { printCommand: true, stdio: 'inherit' });+ return spawn('ios-deploy', ['-c', '-t', '1'], { printCommand: true, stdio: 'inherit' });}/**@@ -161,9 +158,9 @@ function deployToDevice (appPath, target, extraArgs) {events.emit('log', 'Deploying to device');// Deploying to device...if (target) {- return superspawn.spawn('ios-deploy', ['--justlaunch', '-d', '-b', appPath, '-i', target].concat(extraArgs), { printCommand: true, stdio: 'inherit' });+ return spawn('ios-deploy', ['--justlaunch', '-d', '-b', appPath, '-i', target].concat(extraArgs), { printCommand: true, stdio: 'inherit' });} else {- return superspawn.spawn('ios-deploy', ['--justlaunch', '--no-wifi', '-d', '-b', appPath].concat(extraArgs), { printCommand: true, stdio: 'inherit' });+ return spawn('ios-deploy', ['--justlaunch', '--no-wifi', '-d', '-b', appPath].concat(extraArgs), { printCommand: true, stdio: 'inherit' });}}@@ -177,12 +174,12 @@ function deployToSim (appPath, target) {events.emit('log', 'Deploying to simulator');if (!target) {// Select target device for emulator- return require('./list-emulator-images').run()- .then(function (emulators) {+ return require('./listEmulatorImages').run()+ .then(emulators => {if (emulators.length > 0) {target = emulators[0];}- emulators.forEach(function (emulator) {+ emulators.forEach(emulator => {if (emulator.indexOf('iPhone') === 0) {target = emulator;}@@ -196,50 +193,50 @@ function deployToSim (appPath, target) {}function startSim (appPath, target) {- var logPath = path.join(cordovaPath, 'console.log');+ const logPath = path.join(cordovaPath, 'console.log');- return iossimLaunch(appPath, 'com.apple.CoreSimulator.SimDeviceType.' + target, logPath, '--exit');+ return iossimLaunch(appPath, `com.apple.CoreSimulator.SimDeviceType.${target}`, logPath, '--exit');}function iossimLaunch (appPath, devicetypeid, log, exit) {- var f = path.resolve(path.dirname(require.resolve('ios-sim')), 'bin', 'ios-sim');- var params = ['launch', appPath, '--devicetypeid', devicetypeid, '--log', log, exit];-- return superspawn.spawn(f, params, { cwd: projectPath, printCommand: true })- .progress(function (stdio) {- if (stdio.stderr) {- events.emit('error', `[ios-sim] ${stdio.stderr}`);- }- if (stdio.stdout) {- events.emit('log', `[ios-sim] ${stdio.stdout.trim()}`);- }- })- .then(function (result) {+ return spawn(+ require.resolve('ios-sim/bin/ios-sim'),+ ['launch', appPath, '--devicetypeid', devicetypeid, '--log', log, exit],+ { cwd: projectPath, printCommand: true }+ ).progress(stdio => {+ if (stdio.stderr) {+ events.emit('error', `[ios-sim] ${stdio.stderr}`);+ }+ if (stdio.stdout) {+ events.emit('log', `[ios-sim] ${stdio.stdout.trim()}`);+ }+ })+ .then(result => {events.emit('log', 'Simulator successfully started via `ios-sim`.');});}function listDevices () {- return require('./list-devices').run()- .then(function (devices) {+ return require('./listDevices').run()+ .then(devices => {events.emit('log', 'Available iOS Devices:');- devices.forEach(function (device) {- events.emit('log', '\t' + device);+ devices.forEach(device => {+ events.emit('log', `\t${device}`);});});}function listEmulators () {- return require('./list-emulator-images').run()- .then(function (emulators) {+ return require('./listEmulatorImages').run()+ .then(emulators => {events.emit('log', 'Available iOS Simulators:');- emulators.forEach(function (emulator) {- events.emit('log', '\t' + emulator);+ emulators.forEach(emulator => {+ events.emit('log', `\t${emulator}`);});});}-module.exports.help = function () {+module.exports.help = () => {console.log('\nUsage: run [ --device | [ --emulator [ --target=<id> ] ] ] [ --debug | --release | --nobuild ]');// TODO: add support for building different archs// console.log(" [ --archs=\"<list of target architectures>\" ] ");diff --git a/cordova/platforms/ios/cordova/lib/spawn.js b/cordova/platforms/ios/cordova/lib/spawn.jsdeleted file mode 100755index 321b04f95..000000000--- a/cordova/platforms/ios/cordova/lib/spawn.js+++ /dev/null@@ -1,51 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you under the Apache License, Version 2.0 (the- "License"); you may not use this file except in compliance- with the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing,- software distributed under the License is distributed on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- KIND, either express or implied. See the License for the- specific language governing permissions and limitations- under the License.-*/--var Q = require('q');-var proc = require('child_process');--/**- * Run specified command with arguments- * @param {String} cmd Command- * @param {Array} args Array of arguments that should be passed to command- * @param {String} opt_cwd Working directory for command- * @param {String} opt_verbosity Verbosity level for command stdout output, "verbose" by default- * @return {Promise} Promise either fullfilled or rejected with error code- * @deprecated Use `require('cordova-common').superspawn` instead.- */-module.exports = function (cmd, args, opt_cwd) {- console.warn(- 'This function is deprecated, may be removed from a future release. ' +- "Use `require('cordova-common').superspawn` instead.");- var d = Q.defer();- try {- var child = proc.spawn(cmd, args, { cwd: opt_cwd, stdio: 'inherit' });-- child.on('exit', function (code) {- if (code) {- d.reject('Error code ' + code + ' for command: ' + cmd + ' with args: ' + args);- } else {- d.resolve();- }- });- } catch (e) {- d.reject(e);- }- return d.promise;-};diff --git a/cordova/platforms/ios/cordova/lib/versions.js b/cordova/platforms/ios/cordova/lib/versions.jsindex 828042f5e..f89147854 100755--- a/cordova/platforms/ios/cordova/lib/versions.js+++ b/cordova/platforms/ios/cordova/lib/versions.js@@ -1,5 +1,3 @@-#!/usr/bin/env node-/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,77 +17,43 @@under the License.*/-var child_process = require('child_process');-var Q = require('q');-var semver = require('semver');--exports.get_apple_ios_version = function () {- var d = Q.defer();- child_process.exec('xcodebuild -showsdks', function (error, stdout, stderr) {- if (error) {- d.reject(stderr);- } else {- d.resolve(stdout);- }- });-- return d.promise.then(function (output) {- var regex = /[0-9]*\.[0-9]*/;- var versions = [];- var regexIOS = /^iOS \d+/;- output = output.split('\n');- for (var i = 0; i < output.length; i++) {- if (output[i].trim().match(regexIOS)) {- versions[versions.length] = parseFloat(output[i].match(regex)[0]);- }- }- versions.sort();- console.log(versions[0]);- return Q();- }, function (stderr) {- return Q.reject(stderr);- });+const {+ CordovaError,+ superspawn: { spawn }+} = require('cordova-common');+const semver = require('semver');++function fetchSdkVersionByType (sdkType) {+ return spawn('xcodebuild', ['-showsdks'])+ .then(output => {+ const regexSdk = new RegExp(`^${sdkType} \\d`);++ const versions = output.split('\n')+ .filter(line => line.trim().match(regexSdk))+ .map(line => line.match(/\d+\.\d+/)[0])+ .sort(exports.compareVersions);++ console.log(versions[0]);+ });+}++exports.get_apple_ios_version = () => {+ return fetchSdkVersionByType('iOS');};-exports.get_apple_osx_version = function () {- var d = Q.defer();- child_process.exec('xcodebuild -showsdks', function (error, stdout, stderr) {- if (error) {- d.reject(stderr);- } else {- d.resolve(stdout);- }- });-- return d.promise.then(function (output) {- var regex = /[0-9]*\.[0-9]*/;- var versions = [];- var regexOSX = /^macOS \d+/;- output = output.split('\n');- for (var i = 0; i < output.length; i++) {- if (output[i].trim().match(regexOSX)) {- versions[versions.length] = parseFloat(output[i].match(regex)[0]);- }- }- versions.sort();- console.log(versions[0]);- return Q();- }, function (stderr) {- return Q.reject(stderr);- });+exports.get_apple_osx_version = () => {+ return fetchSdkVersionByType('macOS');};-exports.get_apple_xcode_version = function () {- var d = Q.defer();- child_process.exec('xcodebuild -version', function (error, stdout, stderr) {- var versionMatch = /Xcode (.*)/.exec(stdout);- if (error || !versionMatch) {- d.reject(stderr);- } else {- d.resolve(versionMatch[1]);- }- });- return d.promise;+exports.get_apple_xcode_version = () => {+ return spawn('xcodebuild', ['-version'])+ .then(output => {+ const versionMatch = /Xcode (.*)/.exec(output);++ if (!versionMatch) return Promise.reject(output);++ return versionMatch[1];+ });};/**@@ -97,16 +61,8 @@ exports.get_apple_xcode_version = function () {* @return {Promise} Promise that either resolved with ios-deploy version* or rejected in case of error*/-exports.get_ios_deploy_version = function () {- var d = Q.defer();- child_process.exec('ios-deploy --version', function (error, stdout, stderr) {- if (error) {- d.reject(stderr);- } else {- d.resolve(stdout);- }- });- return d.promise;+exports.get_ios_deploy_version = () => {+ return spawn('ios-deploy', ['--version']);};/**@@ -114,16 +70,8 @@ exports.get_ios_deploy_version = function () {* @return {Promise} Promise that either resolved with pod version* or rejected in case of error*/-exports.get_cocoapods_version = function () {- var d = Q.defer();- child_process.exec('pod --version', function (error, stdout, stderr) {- if (error) {- d.reject(stderr);- } else {- d.resolve(stdout);- }- });- return d.promise;+exports.get_cocoapods_version = () => {+ return spawn('pod', ['--version']);};/**@@ -131,16 +79,8 @@ exports.get_cocoapods_version = function () {* @return {Promise} Promise that either resolved with ios-sim version* or rejected in case of error*/-exports.get_ios_sim_version = function () {- var d = Q.defer();- child_process.exec('ios-sim --version', function (error, stdout, stderr) {- if (error) {- d.reject(stderr);- } else {- d.resolve(stdout);- }- });- return d.promise;+exports.get_ios_sim_version = () => {+ return spawn('ios-sim', ['--version']);};/**@@ -149,13 +89,13 @@ exports.get_ios_sim_version = function () {* @return {Promise} Promise that either resolved with tool version* or rejected in case of error*/-exports.get_tool_version = function (toolName) {+exports.get_tool_version = toolName => {switch (toolName) {case 'xcodebuild': return exports.get_apple_xcode_version();case 'ios-sim': return exports.get_ios_sim_version();case 'ios-deploy': return exports.get_ios_deploy_version();case 'pod': return exports.get_cocoapods_version();- default: return Q.reject(toolName + ' is not valid tool name. Valid names are: \'xcodebuild\', \'ios-sim\', \'ios-deploy\', and \'pod\'');+ default: return Promise.reject(new CordovaError(`${toolName} is not valid tool name. Valid names are: 'xcodebuild', 'ios-sim', 'ios-deploy', and 'pod'`));}};diff --git a/cordova/platforms/ios/cordova/loggingHelper.js b/cordova/platforms/ios/cordova/loggingHelper.jsindex e353399c0..871b6cf36 100755--- a/cordova/platforms/ios/cordova/loggingHelper.js+++ b/cordova/platforms/ios/cordova/loggingHelper.js@@ -17,7 +17,7 @@under the License.*/-var CordovaLogger = require('cordova-common').CordovaLogger;+const CordovaLogger = require('cordova-common').CordovaLogger;module.exports = {adjustLoggerLevel: function (opts) {diff --git a/cordova/platforms/ios/cordova/run b/cordova/platforms/ios/cordova/runindex 81741c84f..9e6c8f91e 100755--- a/cordova/platforms/ios/cordova/run+++ b/cordova/platforms/ios/cordova/run@@ -31,33 +31,36 @@ if (['--help', '/?', '-h', 'help', '-help', '/help'].indexOf(process.argv[2]) >=// Parse arguments (includes build params as well)var opts = nopt({- 'verbose': Boolean,- 'silent': Boolean,- 'debug': Boolean,- 'release': Boolean,- 'nobuild': Boolean,- 'archs': String,- 'list': Boolean,- 'device': Boolean,- 'emulator': Boolean,- 'target': String,- 'codeSignIdentity': String,- 'codeSignResourceRules': String,- 'provisioningProfile': String,- 'automaticProvisioning': Boolean,- 'buildConfig': String,- 'noSign': Boolean-}, { 'd': '--verbose' }, args);+ verbose: Boolean,+ silent: Boolean,+ debug: Boolean,+ release: Boolean,+ nobuild: Boolean,+ archs: String,+ list: Boolean,+ device: Boolean,+ emulator: Boolean,+ target: String,+ codeSignIdentity: String,+ codeSignResourceRules: String,+ provisioningProfile: String,+ automaticProvisioning: Boolean,+ buildConfig: String,+ noSign: Boolean+}, { d: '--verbose' }, args);// Make options compatible with PlatformApi build method specopts.argv = opts.argv.remain;require('./loggingHelper').adjustLoggerLevel(opts);-new Api().run(opts).done(function () {- console.log('** RUN SUCCEEDED **');-}, function (err) {- var errorMessage = (err && err.stack) ? err.stack : err;- console.error(errorMessage);- process.exit(2);-});+new Api().run(opts).then(+ () => {+ console.log('** RUN SUCCEEDED **');+ },+ err => {+ var errorMessage = (err && err.stack) ? err.stack : err;+ console.error(errorMessage);+ process.exit(2);+ }+);diff --git a/cordova/platforms/ios/cordova/version b/cordova/platforms/ios/cordova/versionindex 8a81e66fb..6bb657b48 100755--- a/cordova/platforms/ios/cordova/version+++ b/cordova/platforms/ios/cordova/version@@ -26,10 +26,6 @@*/// Coho updates this line-var VERSION = '5.1.1';+const Api = require('./Api');-module.exports.version = VERSION;--if (!module.parent) {- console.log(VERSION);-}+console.log(Api.version());diff --git a/cordova/platforms/ios/frameworks.json b/cordova/platforms/ios/frameworks.jsonindex bdec65c8d..ef13ba6a9 100644--- a/cordova/platforms/ios/frameworks.json+++ b/cordova/platforms/ios/frameworks.json@@ -2,5 +2,7 @@"ImageIO.framework": 1,"CoreLocation.framework": 1,"AVFoundation.framework": 1,+ "Social.framework": 1,+ "MessageUI.framework": 1,"WebKit.framework": 1-}\ No newline at end of file+}diff --git a/cordova/platforms/ios/ios.json b/cordova/platforms/ios/ios.jsonindex a8030a7be..05cf710e5 100644--- a/cordova/platforms/ios/ios.json+++ b/cordova/platforms/ios/ios.json@@ -33,11 +33,15 @@"count": 1},{- "xml": "<feature name=\"CDVWKWebViewEngine\"><param name=\"ios-package\" value=\"CDVWKWebViewEngine\" /></feature>",+ "xml": "<feature name=\"Downloader\"><param name=\"ios-package\" value=\"Downloader\" /></feature>","count": 1},{- "xml": "<preference name=\"CordovaWebViewEngine\" value=\"CDVWKWebViewEngine\" />",+ "xml": "<feature name=\"SocialSharing\"><param name=\"ios-package\" value=\"SocialSharing\" /><param name=\"onload\" value=\"true\" /></feature>",+ "count": 1+ },+ {+ "xml": "<feature name=\"CDVWKWebViewFileXhr\"><param name=\"ios-package\" value=\"CDVWKWebViewFileXhr\" /><param name=\"onload\" value=\"true\" /></feature>","count": 1}]@@ -50,6 +54,18 @@"xml": "<array><string>audio</string></array>","count": 1}+ ],+ "NSPhotoLibraryAddUsageDescription": [+ {+ "xml": "<string>This app requires photo library access to function properly.</string>",+ "count": 1+ }+ ],+ "NSPhotoLibraryUsageDescription": [+ {+ "xml": "<string>This app requires photo library access to function properly.</string>",+ "count": 1+ }]}}@@ -57,25 +73,36 @@},"installed_plugins": {"cordova-plugin-device": {- "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ "PACKAGE_NAME": "org.tagspaces.mobile"},"cordova-plugin-background-mode": {- "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ "PACKAGE_NAME": "org.tagspaces.mobile"},"cordova-plugin-camera": {- "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ "PACKAGE_NAME": "org.tagspaces.mobile"},"cordova-plugin-file": {- "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ "PACKAGE_NAME": "org.tagspaces.mobile"},"cordova-plugin-file-opener2": {- "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ "PACKAGE_NAME": "org.tagspaces.mobile"},"cordova-plugin-whitelist": {- "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ "PACKAGE_NAME": "org.tagspaces.mobile"+ },+ "com.whebcraft.cordova.plugin.downloader": {+ "PACKAGE_NAME": "org.tagspaces.mobile"+ },+ "es6-promise-plugin": {+ "PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-wkwebview-engine": {- "PACKAGE_NAME": "$(PRODUCT_BUNDLE_IDENTIFIER)"+ "cordova-plugin-x-socialsharing": {+ "PHOTO_LIBRARY_ADD_USAGE_DESCRIPTION": "This app requires photo library access to function properly.",+ "PHOTO_LIBRARY_USAGE_DESCRIPTION": "This app requires photo library access to function properly.",+ "PACKAGE_NAME": "org.tagspaces.mobile"+ },+ "cordova-plugin-ios-xhr": {+ "PACKAGE_NAME": "org.tagspaces.mobile"}},"dependent_plugins": {},@@ -311,20 +338,50 @@]},{- "id": "cordova-plugin-wkwebview-engine.ios-wkwebview-exec",- "file": "plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.js",- "pluginId": "cordova-plugin-wkwebview-engine",+ "id": "com.whebcraft.cordova.plugin.downloader.Downloader",+ "file": "plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js",+ "pluginId": "com.whebcraft.cordova.plugin.downloader","clobbers": [- "cordova.exec"+ "plugins.Downloader"]},{- "id": "cordova-plugin-wkwebview-engine.ios-wkwebview",- "file": "plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.js",- "pluginId": "cordova-plugin-wkwebview-engine",+ "id": "es6-promise-plugin.Promise",+ "file": "plugins/es6-promise-plugin/www/promise.js",+ "pluginId": "es6-promise-plugin",+ "runs": true+ },+ {+ "id": "cordova-plugin-x-socialsharing.SocialSharing",+ "file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",+ "pluginId": "cordova-plugin-x-socialsharing","clobbers": [- "window.WkWebView"+ "window.plugins.socialsharing"]+ },+ {+ "id": "cordova-plugin-ios-xhr.formdata-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.xhr-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.fetch-bootstrap",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.fetch-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true}],"plugin_metadata": {@@ -334,6 +391,9 @@"cordova-plugin-file": "6.0.2","cordova-plugin-file-opener2": "3.0.4","cordova-plugin-whitelist": "1.3.4",- "cordova-plugin-wkwebview-engine": "1.2.1"+ "com.whebcraft.cordova.plugin.downloader": "0.1.0",+ "es6-promise-plugin": "4.2.2",+ "cordova-plugin-x-socialsharing": "5.6.8",+ "cordova-plugin-ios-xhr": "1.0.0"}}diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/.eslintrc.yml b/cordova/platforms/ios/platform_www/cordova-js-src/.eslintrc.ymldeleted file mode 100644index e3d49d8a0..000000000--- a/cordova/platforms/ios/platform_www/cordova-js-src/.eslintrc.yml+++ /dev/null@@ -1,4 +0,0 @@-env:- node: false- commonjs: true- browser: truediff --git a/cordova/platforms/ios/platform_www/cordova-js-src/exec.js b/cordova/platforms/ios/platform_www/cordova-js-src/exec.jsindex e7f6ce1c6..466220d83 100644--- a/cordova/platforms/ios/platform_www/cordova-js-src/exec.js+++ b/cordova/platforms/ios/platform_www/cordova-js-src/exec.js@@ -19,19 +19,13 @@**/-/* global require, module, atob, document */-/**- * Creates a gap bridge iframe used to notify the native code about queued+ * Creates the exec bridge used to notify the native code of* commands.*/var cordova = require('cordova');var utils = require('cordova/utils');var base64 = require('cordova/base64');-var execIframe;-var commandQueue = []; // Contains pending JS->Native messages.-var isInContextOfEvalJs = 0;-var failSafeTimerId = 0;function massageArgsJsToNative (args) {if (!args || utils.typeName(args) !== 'Array') {@@ -41,8 +35,8 @@ function massageArgsJsToNative (args) {args.forEach(function (arg, i) {if (utils.typeName(arg) === 'ArrayBuffer') {ret.push({- 'CDVType': 'ArrayBuffer',- 'data': base64.fromArrayBuffer(arg)+ CDVType: 'ArrayBuffer',+ data: base64.fromArrayBuffer(arg)});} else {ret.push(arg);@@ -61,7 +55,7 @@ function massageMessageNativeToJs (message) {return ret.buffer;};var base64ToArrayBuffer = function (b64) {- return stringToArrayBuffer(atob(b64));+ return stringToArrayBuffer(atob(b64)); // eslint-disable-line no-undef};message = base64ToArrayBuffer(message.data);}@@ -70,7 +64,7 @@ function massageMessageNativeToJs (message) {function convertMessageToArgsNativeToJs (message) {var args = [];- if (!message || !message.hasOwnProperty('CDVType')) {+ if (!message || !Object.prototype.hasOwnProperty.call(message, 'CDVType')) {args.push(message);} else if (message.CDVType === 'MultiPart') {message.messages.forEach(function (e) {@@ -82,8 +76,7 @@ function convertMessageToArgsNativeToJs (message) {return args;}-function iOSExec () {-+var iOSExec = function () {var successCallback, failCallback, service, action, actionArgs;var callbackId = null;if (typeof arguments[0] !== 'string') {@@ -100,9 +93,8 @@ function iOSExec () {// an invalid callbackId and passes it even if no callbacks were given.callbackId = 'INVALID';} else {- throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' +- 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'- );+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + // eslint-disable-line+ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);');}// If actionArgs is not provided, default to an empty array@@ -118,120 +110,25 @@ function iOSExec () {actionArgs = massageArgsJsToNative(actionArgs);- var command = [callbackId, service, action, actionArgs];-- // Stringify and queue the command. We stringify to command now to- // effectively clone the command arguments in case they are mutated before- // the command is executed.- commandQueue.push(JSON.stringify(command));-- // If we're in the context of a stringByEvaluatingJavaScriptFromString call,- // then the queue will be flushed when it returns; no need for a poke.- // Also, if there is already a command in the queue, then we've already- // poked the native side, so there is no reason to do so again.- if (!isInContextOfEvalJs && commandQueue.length === 1) {- pokeNative();- }-}--// CB-10530-function proxyChanged () {- var cexec = cordovaExec();-- return (execProxy !== cexec && // proxy objects are different- iOSExec !== cexec // proxy object is not the current iOSExec- );-}--// CB-10106-function handleBridgeChange () {- if (proxyChanged()) {- var commandString = commandQueue.shift();- while (commandString) {- var command = JSON.parse(commandString);- var callbackId = command[0];- var service = command[1];- var action = command[2];- var actionArgs = command[3];- var callbacks = cordova.callbacks[callbackId] || {};-- execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);-- commandString = commandQueue.shift();- }- return true;- }-- return false;-}--function pokeNative () {- // CB-5488 - Don't attempt to create iframe before document.body is available.- if (!document.body) {- setTimeout(pokeNative);- return;- }-- // Check if they've removed it from the DOM, and put it back if so.- if (execIframe && execIframe.contentWindow) {- execIframe.contentWindow.location = 'gap://ready';- } else {- execIframe = document.createElement('iframe');- execIframe.style.display = 'none';- execIframe.src = 'gap://ready';- document.body.appendChild(execIframe);- }- // Use a timer to protect against iframe being unloaded during the poke (CB-7735).- // This makes the bridge ~ 7% slower, but works around the poke getting lost- // when the iframe is removed from the DOM.- // An onunload listener could be used in the case where the iframe has just been- // created, but since unload events fire only once, it doesn't work in the normal- // case of iframe reuse (where unload will have already fired due to the attempted- // navigation of the page).- failSafeTimerId = setTimeout(function () {- if (commandQueue.length) {- // CB-10106 - flush the queue on bridge change- if (!handleBridgeChange()) {- pokeNative();- }- }- }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).-}--iOSExec.nativeFetchMessages = function () {- // Stop listing for window detatch once native side confirms poke.- if (failSafeTimerId) {- clearTimeout(failSafeTimerId);- failSafeTimerId = 0;- }- // Each entry in commandQueue is a JSON string already.- if (!commandQueue.length) {- return '';- }- var json = '[' + commandQueue.join(',') + ']';- commandQueue.length = 0;- return json;+ // CB-10133 DataClone DOM Exception 25 guard (fast function remover)+ var command = [callbackId, service, action, JSON.parse(JSON.stringify(actionArgs))];+ window.webkit.messageHandlers.cordova.postMessage(command);};iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {- return iOSExec.nativeEvalAndFetch(function () {- var success = status === 0 || status === 1;- var args = convertMessageToArgsNativeToJs(message);- function nc2 () {- cordova.callbackFromNative(callbackId, success, status, args, keepCallback);- }- setTimeout(nc2, 0);+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ Promise.resolve().then(function () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback); // eslint-disable-line});};+// for backwards compatibilityiOSExec.nativeEvalAndFetch = function (func) {- // This shouldn't be nested, but better to be safe.- isInContextOfEvalJs++;try {func();- return iOSExec.nativeFetchMessages();- } finally {- isInContextOfEvalJs--;+ } catch (e) {+ console.log(e);}};diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/platform.js b/cordova/platforms/ios/platform_www/cordova-js-src/platform.jsindex 2345fa5b7..83868c81b 100644--- a/cordova/platforms/ios/platform_www/cordova-js-src/platform.js+++ b/cordova/platforms/ios/platform_www/cordova-js-src/platform.js@@ -26,6 +26,14 @@ module.exports = {// see the file under plugin/ios/console.jsrequire('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');+ // Attach the wkwebkit utility to window.WkWebView+ // see the file under plugin/ios/wkwebkit.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/wkwebkit', 'window.WkWebView');++ // Attach the splashscreen utility to window.navigator.splashscreen+ // see the file under plugin/ios/launchscreen.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/launchscreen', 'navigator.splashscreen');+require('cordova/channel').onNativeReady.fire();}};diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.js b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/launchscreen.jssimilarity index 73%rename from cordova/platforms/ios/www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.jsrename to cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/launchscreen.jsindex 0dac749bd..24606969b 100644--- a/cordova/platforms/ios/www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.js+++ b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/launchscreen.js@@ -1,4 +1,3 @@-cordova.define("cordova-plugin-wkwebview-engine.ios-wkwebview", function(require, exports, module) {/*** Licensed to the Apache Software Foundation (ASF) under one@@ -22,12 +21,13 @@ cordova.define("cordova-plugin-wkwebview-engine.ios-wkwebview", function(requirevar exec = require('cordova/exec');-var WkWebKit = {- allowsBackForwardNavigationGestures: function (allow) {- exec(null, null, 'CDVWKWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);+var launchscreen = {+ show: function () {+ exec(null, null, 'LaunchScreen', 'show', []);+ },+ hide: function () {+ exec(null, null, 'LaunchScreen', 'hide', []);}};-module.exports = WkWebKit;--});+module.exports = launchscreen;diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/logger.js b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/logger.jsindex 7dc82e36a..6f59e1c8e 100644--- a/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/logger.js+++ b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/logger.js@@ -312,7 +312,6 @@ function __format (formatString, args) {}function __formatted (object, formatChar) {-try {switch (formatChar) {case 'j':diff --git a/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/wkwebkit.js b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/wkwebkit.jsnew file mode 100644index 000000000..35c819cf1--- /dev/null+++ b/cordova/platforms/ios/platform_www/cordova-js-src/plugin/ios/wkwebkit.js@@ -0,0 +1,42 @@+/*+ *+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ *+*/++var exec = require('cordova/exec');++var WkWebKit = {+ allowsBackForwardNavigationGestures: function (allow) {+ exec(null, null, 'CDVWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);+ },+ convertFilePath: function (path) {+ if (!path || !window.CDV_ASSETS_URL) {+ return path;+ }+ if (path.startsWith('/')) {+ return window.CDV_ASSETS_URL + '/_app_file_' + path;+ }+ if (path.startsWith('file://')) {+ return window.CDV_ASSETS_URL + path.replace('file://', '/_app_file_');+ }+ return path;+ }+};++module.exports = WkWebKit;diff --git a/cordova/platforms/ios/platform_www/cordova.js b/cordova/platforms/ios/platform_www/cordova.jsindex 9813b231f..464244fed 100644--- a/cordova/platforms/ios/platform_www/cordova.js+++ b/cordova/platforms/ios/platform_www/cordova.js@@ -1,5 +1,5 @@// Platform: ios-// 9c79667cd175f51fd2edf2dc91ac8be98b89076a+// 538a985db128858c0a0eb4dd40fb9c8e5433fc94/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,7 +19,7 @@under the License.*/;(function() {-var PLATFORM_VERSION_BUILD_LABEL = '5.1.1';+var PLATFORM_VERSION_BUILD_LABEL = '6.1.0';// file: src/scripts/require.jsvar require;var define;@@ -50,10 +50,10 @@ var define;require = function (id) {if (!modules[id]) {- throw 'module ' + id + ' not found';+ throw new Error('module ' + id + ' not found');} else if (id in inProgressModules) {var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;- throw 'Cycle in require graph: ' + cycle;+ throw new Error('Cycle in require graph: ' + cycle);}if (modules[id].factory) {try {@@ -70,7 +70,7 @@ var define;define = function (id, factory) {if (Object.prototype.hasOwnProperty.call(modules, id)) {- throw 'module ' + id + ' already defined';+ throw new Error('module ' + id + ' already defined');}modules[id] = {@@ -162,7 +162,7 @@ function createEvent (type, data) {event.initEvent(type, false, false);if (data) {for (var i in data) {- if (data.hasOwnProperty(i)) {+ if (Object.prototype.hasOwnProperty.call(data, i)) {event[i] = data[i];}}@@ -310,9 +310,7 @@ var cordova = {}} catch (err) {var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;- console && console.log && console.log(msg);- console && console.log && err.stack && console.log(err.stack);- cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ cordova.fireWindowEvent('cordovacallbackerror', { message: msg, error: err });throw err;}},@@ -340,12 +338,12 @@ var utils = require('cordova/utils');var moduleExports = module.exports;var typeMap = {- 'A': 'Array',- 'D': 'Date',- 'N': 'Number',- 'S': 'String',- 'F': 'Function',- 'O': 'Object'+ A: 'Array',+ D: 'Date',+ N: 'Number',+ S: 'String',+ F: 'Function',+ O: 'Object'};function extractParamName (callee, argIndex) {@@ -498,7 +496,7 @@ var utils = require('cordova/utils');function each (objects, func, context) {for (var prop in objects) {- if (objects.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(objects, prop)) {func.apply(context, [objects[prop], prop]);}}@@ -578,7 +576,7 @@ function include (parent, objects, clobber, merge) {*/function recursiveMerge (target, src) {for (var prop in src) {- if (src.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(src, prop)) {if (target.prototype && target.prototype.constructor === target) {// If the target object is a constructor override off prototype.clobber(target.prototype, prop, src[prop]);@@ -871,19 +869,13 @@ module.exports = channel;// file: ../cordova-ios/cordova-js-src/exec.jsdefine("cordova/exec", function(require, exports, module) {-/* global require, module, atob, document */-/**- * Creates a gap bridge iframe used to notify the native code about queued+ * Creates the exec bridge used to notify the native code of* commands.*/var cordova = require('cordova');var utils = require('cordova/utils');var base64 = require('cordova/base64');-var execIframe;-var commandQueue = []; // Contains pending JS->Native messages.-var isInContextOfEvalJs = 0;-var failSafeTimerId = 0;function massageArgsJsToNative (args) {if (!args || utils.typeName(args) !== 'Array') {@@ -893,8 +885,8 @@ function massageArgsJsToNative (args) {args.forEach(function (arg, i) {if (utils.typeName(arg) === 'ArrayBuffer') {ret.push({- 'CDVType': 'ArrayBuffer',- 'data': base64.fromArrayBuffer(arg)+ CDVType: 'ArrayBuffer',+ data: base64.fromArrayBuffer(arg)});} else {ret.push(arg);@@ -913,7 +905,7 @@ function massageMessageNativeToJs (message) {return ret.buffer;};var base64ToArrayBuffer = function (b64) {- return stringToArrayBuffer(atob(b64));+ return stringToArrayBuffer(atob(b64)); // eslint-disable-line no-undef};message = base64ToArrayBuffer(message.data);}@@ -922,7 +914,7 @@ function massageMessageNativeToJs (message) {function convertMessageToArgsNativeToJs (message) {var args = [];- if (!message || !message.hasOwnProperty('CDVType')) {+ if (!message || !Object.prototype.hasOwnProperty.call(message, 'CDVType')) {args.push(message);} else if (message.CDVType === 'MultiPart') {message.messages.forEach(function (e) {@@ -934,8 +926,7 @@ function convertMessageToArgsNativeToJs (message) {return args;}-function iOSExec () {-+var iOSExec = function () {var successCallback, failCallback, service, action, actionArgs;var callbackId = null;if (typeof arguments[0] !== 'string') {@@ -952,9 +943,8 @@ function iOSExec () {// an invalid callbackId and passes it even if no callbacks were given.callbackId = 'INVALID';} else {- throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' +- 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'- );+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + // eslint-disable-line+ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);');}// If actionArgs is not provided, default to an empty array@@ -970,120 +960,25 @@ function iOSExec () {actionArgs = massageArgsJsToNative(actionArgs);- var command = [callbackId, service, action, actionArgs];-- // Stringify and queue the command. We stringify to command now to- // effectively clone the command arguments in case they are mutated before- // the command is executed.- commandQueue.push(JSON.stringify(command));-- // If we're in the context of a stringByEvaluatingJavaScriptFromString call,- // then the queue will be flushed when it returns; no need for a poke.- // Also, if there is already a command in the queue, then we've already- // poked the native side, so there is no reason to do so again.- if (!isInContextOfEvalJs && commandQueue.length === 1) {- pokeNative();- }-}--// CB-10530-function proxyChanged () {- var cexec = cordovaExec();-- return (execProxy !== cexec && // proxy objects are different- iOSExec !== cexec // proxy object is not the current iOSExec- );-}--// CB-10106-function handleBridgeChange () {- if (proxyChanged()) {- var commandString = commandQueue.shift();- while (commandString) {- var command = JSON.parse(commandString);- var callbackId = command[0];- var service = command[1];- var action = command[2];- var actionArgs = command[3];- var callbacks = cordova.callbacks[callbackId] || {};-- execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);-- commandString = commandQueue.shift();- }- return true;- }-- return false;-}--function pokeNative () {- // CB-5488 - Don't attempt to create iframe before document.body is available.- if (!document.body) {- setTimeout(pokeNative);- return;- }-- // Check if they've removed it from the DOM, and put it back if so.- if (execIframe && execIframe.contentWindow) {- execIframe.contentWindow.location = 'gap://ready';- } else {- execIframe = document.createElement('iframe');- execIframe.style.display = 'none';- execIframe.src = 'gap://ready';- document.body.appendChild(execIframe);- }- // Use a timer to protect against iframe being unloaded during the poke (CB-7735).- // This makes the bridge ~ 7% slower, but works around the poke getting lost- // when the iframe is removed from the DOM.- // An onunload listener could be used in the case where the iframe has just been- // created, but since unload events fire only once, it doesn't work in the normal- // case of iframe reuse (where unload will have already fired due to the attempted- // navigation of the page).- failSafeTimerId = setTimeout(function () {- if (commandQueue.length) {- // CB-10106 - flush the queue on bridge change- if (!handleBridgeChange()) {- pokeNative();- }- }- }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).-}--iOSExec.nativeFetchMessages = function () {- // Stop listing for window detatch once native side confirms poke.- if (failSafeTimerId) {- clearTimeout(failSafeTimerId);- failSafeTimerId = 0;- }- // Each entry in commandQueue is a JSON string already.- if (!commandQueue.length) {- return '';- }- var json = '[' + commandQueue.join(',') + ']';- commandQueue.length = 0;- return json;+ // CB-10133 DataClone DOM Exception 25 guard (fast function remover)+ var command = [callbackId, service, action, JSON.parse(JSON.stringify(actionArgs))];+ window.webkit.messageHandlers.cordova.postMessage(command);};iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {- return iOSExec.nativeEvalAndFetch(function () {- var success = status === 0 || status === 1;- var args = convertMessageToArgsNativeToJs(message);- function nc2 () {- cordova.callbackFromNative(callbackId, success, status, args, keepCallback);- }- setTimeout(nc2, 0);+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ Promise.resolve().then(function () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback); // eslint-disable-line});};+// for backwards compatibilityiOSExec.nativeEvalAndFetch = function (func) {- // This shouldn't be nested, but better to be safe.- isInContextOfEvalJs++;try {func();- return iOSExec.nativeFetchMessages();- } finally {- isInContextOfEvalJs--;+ } catch (e) {+ console.log(e);}};@@ -1153,7 +1048,6 @@ var cordova = require('cordova');var modulemapper = require('cordova/modulemapper');var platform = require('cordova/platform');var pluginloader = require('cordova/pluginloader');-var utils = require('cordova/utils');var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];@@ -1173,34 +1067,6 @@ window.setTimeout(function () {}}, 5000);-// Replace navigator before any modules are required(), to ensure it happens as soon as possible.-// We replace it so that properties that can't be clobbered can instead be overridden.-function replaceNavigator (origNavigator) {- var CordovaNavigator = function () {};- CordovaNavigator.prototype = origNavigator;- var newNavigator = new CordovaNavigator();- // This work-around really only applies to new APIs that are newer than Function.bind.- // Without it, APIs such as getGamepads() break.- if (CordovaNavigator.bind) {- for (var key in origNavigator) {- if (typeof origNavigator[key] === 'function') {- newNavigator[key] = origNavigator[key].bind(origNavigator);- } else {- (function (k) {- utils.defineGetterSetter(newNavigator, key, function () {- return origNavigator[k];- });- })(key);- }- }- }- return newNavigator;-}--if (window.navigator) {- window.navigator = replaceNavigator(window.navigator);-}-if (!window.console) {window.console = {log: function () {}@@ -1266,7 +1132,6 @@ channel.join(function () {channel.join(function () {require('cordova').fireDocumentEvent('deviceready');}, channel.deviceReadyChannelsArray);-}, platformInitChannelsArray);});@@ -1378,6 +1243,14 @@ module.exports = {// see the file under plugin/ios/console.jsrequire('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');+ // Attach the wkwebkit utility to window.WkWebView+ // see the file under plugin/ios/wkwebkit.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/wkwebkit', 'window.WkWebView');++ // Attach the splashscreen utility to window.navigator.splashscreen+ // see the file under plugin/ios/launchscreen.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/launchscreen', 'navigator.splashscreen');+require('cordova/channel').onNativeReady.fire();}};@@ -1555,6 +1428,24 @@ for (var key in console) {});+// file: ../cordova-ios/cordova-js-src/plugin/ios/launchscreen.js+define("cordova/plugin/ios/launchscreen", function(require, exports, module) {++var exec = require('cordova/exec');++var launchscreen = {+ show: function () {+ exec(null, null, 'LaunchScreen', 'show', []);+ },+ hide: function () {+ exec(null, null, 'LaunchScreen', 'hide', []);+ }+};++module.exports = launchscreen;++});+// file: ../cordova-ios/cordova-js-src/plugin/ios/logger.jsdefine("cordova/plugin/ios/logger", function(require, exports, module) {@@ -1851,7 +1742,6 @@ function __format (formatString, args) {}function __formatted (object, formatChar) {-try {switch (formatChar) {case 'j':@@ -1889,6 +1779,33 @@ document.addEventListener('deviceready', logger.__onDeviceReady, false);});+// file: ../cordova-ios/cordova-js-src/plugin/ios/wkwebkit.js+define("cordova/plugin/ios/wkwebkit", function(require, exports, module) {++var exec = require('cordova/exec');++var WkWebKit = {+ allowsBackForwardNavigationGestures: function (allow) {+ exec(null, null, 'CDVWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);+ },+ convertFilePath: function (path) {+ if (!path || !window.CDV_ASSETS_URL) {+ return path;+ }+ if (path.startsWith('/')) {+ return window.CDV_ASSETS_URL + '/_app_file_' + path;+ }+ if (path.startsWith('file://')) {+ return window.CDV_ASSETS_URL + path.replace('file://', '/_app_file_');+ }+ return path;+ }+};++module.exports = WkWebKit;++});+// file: src/common/pluginloader.jsdefine("cordova/pluginloader", function(require, exports, module) {@@ -2160,7 +2077,6 @@ utils.extend = (function () {var F = function () {};// extend Child from Parentreturn function (Child, Parent) {-F.prototype = Parent.prototype;Child.prototype = new F();Child.__super__ = Parent.prototype;diff --git a/cordova/platforms/ios/platform_www/cordova_plugins.js b/cordova/platforms/ios/platform_www/cordova_plugins.jsindex 023731eb1..ae4704a8a 100644--- a/cordova/platforms/ios/platform_www/cordova_plugins.js+++ b/cordova/platforms/ios/platform_www/cordova_plugins.js@@ -231,20 +231,50 @@ cordova.define('cordova/plugin_list', function(require, exports, module) {]},{- "id": "cordova-plugin-wkwebview-engine.ios-wkwebview-exec",- "file": "plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.js",- "pluginId": "cordova-plugin-wkwebview-engine",+ "id": "com.whebcraft.cordova.plugin.downloader.Downloader",+ "file": "plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js",+ "pluginId": "com.whebcraft.cordova.plugin.downloader","clobbers": [- "cordova.exec"+ "plugins.Downloader"]},{- "id": "cordova-plugin-wkwebview-engine.ios-wkwebview",- "file": "plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.js",- "pluginId": "cordova-plugin-wkwebview-engine",+ "id": "es6-promise-plugin.Promise",+ "file": "plugins/es6-promise-plugin/www/promise.js",+ "pluginId": "es6-promise-plugin",+ "runs": true+ },+ {+ "id": "cordova-plugin-x-socialsharing.SocialSharing",+ "file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",+ "pluginId": "cordova-plugin-x-socialsharing","clobbers": [- "window.WkWebView"+ "window.plugins.socialsharing"]+ },+ {+ "id": "cordova-plugin-ios-xhr.formdata-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.xhr-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.fetch-bootstrap",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.fetch-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true}];module.exports.metadata = {@@ -254,6 +284,9 @@ cordova.define('cordova/plugin_list', function(require, exports, module) {"cordova-plugin-file": "6.0.2","cordova-plugin-file-opener2": "3.0.4","cordova-plugin-whitelist": "1.3.4",- "cordova-plugin-wkwebview-engine": "1.2.1"+ "com.whebcraft.cordova.plugin.downloader": "0.1.0",+ "es6-promise-plugin": "4.2.2",+ "cordova-plugin-x-socialsharing": "5.6.8",+ "cordova-plugin-ios-xhr": "1.0.0"};-});\ No newline at end of file+});diff --git a/cordova/platforms/ios/platform_www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js b/cordova/platforms/ios/platform_www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.jsnew file mode 100644index 000000000..b8dad0882--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js@@ -0,0 +1,25 @@+cordova.define("com.whebcraft.cordova.plugin.downloader.Downloader", function(require, exports, module) {+var Downloader = {+ download: function (arguments, successCallback, errorCallback) {+ cordova.exec(+ successCallback,+ errorCallback,+ 'Downloader',+ 'download',+ [arguments]+ );+ }+};++function install() {+ if (!window.plugins) {+ window.plugins = {};+ }++ window.plugins.Downloader = Downloader;+ return window.plugins.Downloader;+};++cordova.addConstructor(install);++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.jsnew file mode 100644index 000000000..79dbf5c89--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.js@@ -0,0 +1,10 @@+cordova.define("cordova-plugin-ios-xhr.fetch-bootstrap", function(require, exports, module) {+'use strict';++(function ()+{+ var _fetch = window.fetch;+ window.fetch = undefined;+})();++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.jsnew file mode 100644index 000000000..3db9ffdc7--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.js@@ -0,0 +1,365 @@+cordova.define("cordova-plugin-ios-xhr.formdata-polyfill", function(require, exports, module) {+/*+ * Copyright (c) 2018 Oracle and/or its affiliates.+ *+ * The Universal Permissive License (UPL), Version 1.0+ *+ * Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this+ * software, associated documentation and/or data (collectively the "Software"), free of charge and under any and+ * all copyright rights in the Software, and any and all patent rights owned or freely licensable by each+ * licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor,+ * or (ii) the Larger Works (as defined below), to deal in both+ *+ *+ * (a) the Software, and+ *+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software+ * (each a “Larger Work” to which the Software is contributed by such licensors),+ *+ * without restriction, including without limitation the rights to copy, create derivative works of, display,+ * perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and+ * have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other+ * terms.+ *+ * This license is subject to the following condition:+ *+ * The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL+ * must be included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ * DEALINGS IN THE SOFTWARE.+ */++/*+ * Native Safari FormData only implements the append method. This polyfill is used in+ * tandem with the xhr-polyfill.+ *+ * Two additional functions in this FormData implementation:+ * 1) __getNative - returns the native Safari FormData object.+ * 2) __getRequestParts - returns a promise resolving an object {contentType:string, body:string}.+ */+'use strict';+(function ()+{+ function __FormData(formElement)+ {+ this._map = new Map();++ if (!HTMLFormElement.prototype.isPrototypeOf(formElement))+ return;++ var elements = formElement.elements;+ for (var i = 0; i < elements.length; i++)+ {+ var element = elements[i];++ var name = element.name ? element.name : element.id;+ if (!name)+ continue;++ if (element.type === 'file')+ {+ for (var file of element.files)+ this.append(name, file);+ }+ else if (['select-multiple', 'select-one'].indexOf(element.value) > -1)+ {+ for (var option of element.selectedOptions)+ this.append(name, option);+ }+ else if (['checkbox', 'radio'].indexOf(element.value) > -1 && element.checked)+ {+ this.append(name, element.value);+ }+ else+ {+ this.append(name, element.value);+ }+ }+ }++ if( 'Symbol' in window && typeof Symbol() === 'symbol'){+ Object.defineProperty( __FormData.prototype, Symbol.toStringTag, {+ get : function(){+ return 'FormData';+ }+ });+ }++ __FormData.prototype.get = function (name)+ {+ var values = this.getAll(name);++ if (values && values.length > 0)+ return values[0];+ else+ return undefined;+ };++ __FormData.prototype.getAll = function (name)+ {+ var map = this._map;+ var values = map.get(name);+ if (!values)+ values = [];++ return values;+ };++ __FormData.prototype.set = function (name, value, filename)+ {+ var map = this._map;++ if (value && Blob.prototype.isPrototypeOf(value))+ {+ if (!filename)+ filename = "Blob";++ Object.defineProperty(value, "name", {value: filename});+ }++ map.set(name, [value]);+ };+++ __FormData.prototype.append = function (name, value, filename)+ {+ var map = this._map;+ var values = map.get(name);++ this.set(name, value, filename);+ if (values)+ {+ values.push(map.get(name)[0]);+ map.set(name, values);+ }+ };++ __FormData.prototype.delete = function (name)+ {+ var map = this._map;+ map.delete(name);+ };++ __FormData.prototype.has = function (name)+ {+ var map = this._map;+ return map.has(name);+ };++ __FormData.prototype.keys = function ()+ {+ var map = this._map;+ return map.keys();+ };++ __FormData.prototype.values = function ()+ {+ var map = this._map;+ var allvalues = [];++ var vit = map.values();+ var entry = vit.next();+ while (entry && !entry.done)+ {+ var values = entry.value;+ for (var i = 0; i < values.length; i++)+ allvalues.push(values[i]);++ entry = vit.next();+ }++ return __FormData._makeIterator(allvalues);+ };++ __FormData.prototype.entries = function ()+ {+ var map = this._map;+ var allentries = [];++ for (var key of map.keys())+ {+ var values = map.get(key);+ for (var i = 0; i < values.length; i++)+ {+ allentries.push([key, values[i]]);+ }+ }++ return __FormData._makeIterator(allentries);+ };++ __FormData.prototype.forEach = function(callback)+ {+ var eit = this.entries();+ var entry = eit.next();+ while(!entry.done)+ {+ callback.call(this, entry.value[1], entry.value[0], this);+ entry = eit.next();+ }+ };++ __FormData.prototype.toString = function ()+ {+ return "[object FormData]";+ };++ __FormData.prototype.__getRequestParts = function ()+ {+ var promise = new Promise(function (resolve)+ {+ __FormData._getRequestValues(this.entries()).then(function (entries)+ {+ var parts = __FormData._getMultipartRequest(entries);++ resolve(parts);+ });+ }.bind(this));++ return promise;+ };++ __FormData.prototype.__getNative = function ()+ {+ var fd = new window._FormData();+ var eit = this.entries();+ var entry = eit.next();+ while (!entry.done)+ {+ if (entry.value[1] && Blob.prototype.isPrototypeOf(entry.value[1]))+ fd.append(entry.value[0], entry.value[1], entry.value[1].name);+ else+ fd.append(entry.value[0], entry.value[1]);++ entry = eit.next();+ }++ return fd;+ };++ __FormData._getMultipartRequest = function (entries)+ {+ var boundary = "----cordovaPluginWkwebviewFileXhrFormdata" + Math.random().toString(32);+ var parts = {"contentType": "multipart/form-data; boundary=" + boundary, body: ""};+ var bodyEntries = [];++ for (var i = 0; i < entries.length; i++)+ {+ var entry = entries[i];+ for (var data of __FormData._generateMultipartFormData(entry, boundary))+ bodyEntries.push(data);+ }++ bodyEntries.push("--" + boundary + "--");+ parts.body = new Blob(bodyEntries, {type: "application/octet-stream"});++ return parts;+ };++ __FormData._makeIterator = function (array)+ {+ var i = 0;+ return {+ next: function ()+ {+ if (i < array.length)+ return {done: false, value: array[i++]};+ else+ return {done: true, value: undefined};+ }+ };+ };++ __FormData._getRequestValues = function (entriesIterator)+ {+ var promises = [];+ var entry = entriesIterator.next();+ while (!entry.done)+ {+ promises.push(__FormData._normalizeEntry(entry));+ entry = entriesIterator.next();+ }++ return Promise.all(promises);+ };++ __FormData._normalizeEntry = function (entry)+ {+ var promise = new Promise(function (resolve)+ {++ var name = entry.value[0];+ var value = entry.value[1];++ if (value &&+ (Blob.prototype.isPrototypeOf(value) ||+ File.prototype.isPrototypeOf(value)))+ {++ var filename = value.name;+ var type = value.type ? value.type : "application/octet-binary;";+ var reader = new FileReader();+ var resolve;++ reader.onload = function ()+ {+ resolve({name: name, value: reader.result, filename: filename, type: type});+ };++ reader.onerror = function ()+ {+ resolve({name: name, value: reader.error, filename: filename, type: type});+ };++ reader.readAsArrayBuffer(value);+ }+ else+ {+ promise = resolve({name: name, value: value});+ }+ });++ return promise;+ };++ __FormData._generateMultipartFormData = function (entry, boundary)+ {+ var data = [];++ data.push("--" + boundary + "\r\n");+ if (!entry['filename'])+ {+ data.push('content-disposition: form-data; name="');+ data.push(entry.name);+ data.push('"\r\n');+ data.push('\r\n');+ data.push(entry.value);+ data.push("\r\n");+ }+ else+ {+ // Describe it as form data+ data.push('content-disposition: form-data; name="');+ data.push(entry.name)+ data.push('"; filename="');+ data.push(entry.filename);+ data.push('"\r\n');+ data.push('Content-Type: ');+ data.push(entry.type);+ data.push('\r\n\r\n');+ data.push(entry.value);+ data.push('\r\n');+ }++ return data;+ };++ window._FormData = window.FormData;+ window.FormData = __FormData;+})();++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.jsnew file mode 100644index 000000000..7b5fce803--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.js@@ -0,0 +1,464 @@+cordova.define("cordova-plugin-ios-xhr.fetch-polyfill", function(require, exports, module) {+(function(self) {+ 'use strict';++ if (self.fetch) {+ return+ }++ var support = {+ searchParams: 'URLSearchParams' in self,+ iterable: 'Symbol' in self && 'iterator' in Symbol,+ blob: 'FileReader' in self && 'Blob' in self && (function() {+ try {+ new Blob()+ return true+ } catch(e) {+ return false+ }+ })(),+ formData: 'FormData' in self,+ arrayBuffer: 'ArrayBuffer' in self+ }++ if (support.arrayBuffer) {+ var viewClasses = [+ '[object Int8Array]',+ '[object Uint8Array]',+ '[object Uint8ClampedArray]',+ '[object Int16Array]',+ '[object Uint16Array]',+ '[object Int32Array]',+ '[object Uint32Array]',+ '[object Float32Array]',+ '[object Float64Array]'+ ]++ var isDataView = function(obj) {+ return obj && DataView.prototype.isPrototypeOf(obj)+ }++ var isArrayBufferView = ArrayBuffer.isView || function(obj) {+ return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1+ }+ }++ function normalizeName(name) {+ if (typeof name !== 'string') {+ name = String(name)+ }+ if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {+ throw new TypeError('Invalid character in header field name')+ }+ return name.toLowerCase()+ }++ function normalizeValue(value) {+ if (typeof value !== 'string') {+ value = String(value)+ }+ return value+ }++ // Build a destructive iterator for the value list+ function iteratorFor(items) {+ var iterator = {+ next: function() {+ var value = items.shift()+ return {done: value === undefined, value: value}+ }+ }++ if (support.iterable) {+ iterator[Symbol.iterator] = function() {+ return iterator+ }+ }++ return iterator+ }++ function Headers(headers) {+ this.map = {}++ if (headers instanceof Headers) {+ headers.forEach(function(value, name) {+ this.append(name, value)+ }, this)+ } else if (Array.isArray(headers)) {+ headers.forEach(function(header) {+ this.append(header[0], header[1])+ }, this)+ } else if (headers) {+ Object.getOwnPropertyNames(headers).forEach(function(name) {+ this.append(name, headers[name])+ }, this)+ }+ }++ Headers.prototype.append = function(name, value) {+ name = normalizeName(name)+ value = normalizeValue(value)+ var oldValue = this.map[name]+ this.map[name] = oldValue ? oldValue+','+value : value+ }++ Headers.prototype['delete'] = function(name) {+ delete this.map[normalizeName(name)]+ }++ Headers.prototype.get = function(name) {+ name = normalizeName(name)+ return this.has(name) ? this.map[name] : null+ }++ Headers.prototype.has = function(name) {+ return this.map.hasOwnProperty(normalizeName(name))+ }++ Headers.prototype.set = function(name, value) {+ this.map[normalizeName(name)] = normalizeValue(value)+ }++ Headers.prototype.forEach = function(callback, thisArg) {+ for (var name in this.map) {+ if (this.map.hasOwnProperty(name)) {+ callback.call(thisArg, this.map[name], name, this)+ }+ }+ }++ Headers.prototype.keys = function() {+ var items = []+ this.forEach(function(value, name) { items.push(name) })+ return iteratorFor(items)+ }++ Headers.prototype.values = function() {+ var items = []+ this.forEach(function(value) { items.push(value) })+ return iteratorFor(items)+ }++ Headers.prototype.entries = function() {+ var items = []+ this.forEach(function(value, name) { items.push([name, value]) })+ return iteratorFor(items)+ }++ if (support.iterable) {+ Headers.prototype[Symbol.iterator] = Headers.prototype.entries+ }++ function consumed(body) {+ if (body.bodyUsed) {+ return Promise.reject(new TypeError('Already read'))+ }+ body.bodyUsed = true+ }++ function fileReaderReady(reader) {+ return new Promise(function(resolve, reject) {+ reader.onload = function() {+ resolve(reader.result)+ }+ reader.onerror = function() {+ reject(reader.error)+ }+ })+ }++ function readBlobAsArrayBuffer(blob) {+ var reader = new FileReader()+ var promise = fileReaderReady(reader)+ reader.readAsArrayBuffer(blob)+ return promise+ }++ function readBlobAsText(blob) {+ var reader = new FileReader()+ var promise = fileReaderReady(reader)+ reader.readAsText(blob)+ return promise+ }++ function readArrayBufferAsText(buf) {+ var view = new Uint8Array(buf)+ var chars = new Array(view.length)++ for (var i = 0; i < view.length; i++) {+ chars[i] = String.fromCharCode(view[i])+ }+ return chars.join('')+ }++ function bufferClone(buf) {+ if (buf.slice) {+ return buf.slice(0)+ } else {+ var view = new Uint8Array(buf.byteLength)+ view.set(new Uint8Array(buf))+ return view.buffer+ }+ }++ function Body() {+ this.bodyUsed = false++ this._initBody = function(body) {+ this._bodyInit = body+ if (!body) {+ this._bodyText = ''+ } else if (typeof body === 'string') {+ this._bodyText = body+ } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {+ this._bodyBlob = body+ } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {+ this._bodyFormData = body+ } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {+ this._bodyText = body.toString()+ } else if (support.arrayBuffer && support.blob && isDataView(body)) {+ this._bodyArrayBuffer = bufferClone(body.buffer)+ // IE 10-11 can't handle a DataView body.+ this._bodyInit = new Blob([this._bodyArrayBuffer])+ } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {+ this._bodyArrayBuffer = bufferClone(body)+ } else {+ throw new Error('unsupported BodyInit type')+ }++ if (!this.headers.get('content-type')) {+ if (typeof body === 'string') {+ this.headers.set('content-type', 'text/plain;charset=UTF-8')+ } else if (this._bodyBlob && this._bodyBlob.type) {+ this.headers.set('content-type', this._bodyBlob.type)+ } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {+ this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')+ }+ }+ }++ if (support.blob) {+ this.blob = function() {+ var rejected = consumed(this)+ if (rejected) {+ return rejected+ }++ if (this._bodyBlob) {+ return Promise.resolve(this._bodyBlob)+ } else if (this._bodyArrayBuffer) {+ return Promise.resolve(new Blob([this._bodyArrayBuffer]))+ } else if (this._bodyFormData) {+ throw new Error('could not read FormData body as blob')+ } else {+ return Promise.resolve(new Blob([this._bodyText]))+ }+ }++ this.arrayBuffer = function() {+ if (this._bodyArrayBuffer) {+ return consumed(this) || Promise.resolve(this._bodyArrayBuffer)+ } else {+ return this.blob().then(readBlobAsArrayBuffer)+ }+ }+ }++ this.text = function() {+ var rejected = consumed(this)+ if (rejected) {+ return rejected+ }++ if (this._bodyBlob) {+ return readBlobAsText(this._bodyBlob)+ } else if (this._bodyArrayBuffer) {+ return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))+ } else if (this._bodyFormData) {+ throw new Error('could not read FormData body as text')+ } else {+ return Promise.resolve(this._bodyText)+ }+ }++ if (support.formData) {+ this.formData = function() {+ return this.text().then(decode)+ }+ }++ this.json = function() {+ return this.text().then(JSON.parse)+ }++ return this+ }++ // HTTP methods whose capitalization should be normalized+ var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']++ function normalizeMethod(method) {+ var upcased = method.toUpperCase()+ return (methods.indexOf(upcased) > -1) ? upcased : method+ }++ function Request(input, options) {+ options = options || {}+ var body = options.body++ if (input instanceof Request) {+ if (input.bodyUsed) {+ throw new TypeError('Already read')+ }+ this.url = input.url+ this.credentials = input.credentials+ if (!options.headers) {+ this.headers = new Headers(input.headers)+ }+ this.method = input.method+ this.mode = input.mode+ if (!body && input._bodyInit != null) {+ body = input._bodyInit+ input.bodyUsed = true+ }+ } else {+ this.url = String(input)+ }++ this.credentials = options.credentials || this.credentials || 'omit'+ if (options.headers || !this.headers) {+ this.headers = new Headers(options.headers)+ }+ this.method = normalizeMethod(options.method || this.method || 'GET')+ this.mode = options.mode || this.mode || null+ this.referrer = null++ if ((this.method === 'GET' || this.method === 'HEAD') && body) {+ throw new TypeError('Body not allowed for GET or HEAD requests')+ }+ this._initBody(body)+ }++ Request.prototype.clone = function() {+ return new Request(this, { body: this._bodyInit })+ }++ function decode(body) {+ var form = new FormData()+ body.trim().split('&').forEach(function(bytes) {+ if (bytes) {+ var split = bytes.split('=')+ var name = split.shift().replace(/\+/g, ' ')+ var value = split.join('=').replace(/\+/g, ' ')+ form.append(decodeURIComponent(name), decodeURIComponent(value))+ }+ })+ return form+ }++ function parseHeaders(rawHeaders) {+ var headers = new Headers()+ rawHeaders.split(/\r?\n/).forEach(function(line) {+ var parts = line.split(':')+ var key = parts.shift().trim()+ if (key) {+ var value = parts.join(':').trim()+ headers.append(key, value)+ }+ })+ return headers+ }++ Body.call(Request.prototype)++ function Response(bodyInit, options) {+ if (!options) {+ options = {}+ }++ this.type = 'default'+ this.status = 'status' in options ? options.status : 200+ this.ok = this.status >= 200 && this.status < 300+ this.statusText = 'statusText' in options ? options.statusText : 'OK'+ this.headers = new Headers(options.headers)+ this.url = options.url || ''+ this._initBody(bodyInit)+ }++ Body.call(Response.prototype)++ Response.prototype.clone = function() {+ return new Response(this._bodyInit, {+ status: this.status,+ statusText: this.statusText,+ headers: new Headers(this.headers),+ url: this.url+ })+ }++ Response.error = function() {+ var response = new Response(null, {status: 0, statusText: ''})+ response.type = 'error'+ return response+ }++ var redirectStatuses = [301, 302, 303, 307, 308]++ Response.redirect = function(url, status) {+ if (redirectStatuses.indexOf(status) === -1) {+ throw new RangeError('Invalid status code')+ }++ return new Response(null, {status: status, headers: {location: url}})+ }++ self.Headers = Headers+ self.Request = Request+ self.Response = Response++ self.fetch = function(input, init) {+ return new Promise(function(resolve, reject) {+ var request = new Request(input, init)+ var xhr = new XMLHttpRequest()++ xhr.onload = function() {+ var options = {+ status: xhr.status,+ statusText: xhr.statusText,+ headers: parseHeaders(xhr.getAllResponseHeaders() || '')+ }+ options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')+ var body = 'response' in xhr ? xhr.response : xhr.responseText+ resolve(new Response(body, options))+ }++ xhr.onerror = function() {+ reject(new TypeError('Network request failed'))+ }++ xhr.ontimeout = function() {+ reject(new TypeError('Network request failed'))+ }++ xhr.open(request.method, request.url, true)++ if (request.credentials === 'include') {+ xhr.withCredentials = true+ }++ if ('responseType' in xhr && support.blob) {+ xhr.responseType = 'blob'+ }++ request.headers.forEach(function(value, name) {+ xhr.setRequestHeader(name, value)+ })++ xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)+ })+ }+ self.fetch.polyfill = true+})(typeof self !== 'undefined' ? self : this);++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.jsnew file mode 100644index 000000000..4ba7a4269--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.js@@ -0,0 +1,1249 @@+cordova.define("cordova-plugin-ios-xhr.xhr-polyfill", function(require, exports, module) {+/*+ * Copyright (c) 2018 Oracle and/or its affiliates.+ *+ * The Universal Permissive License (UPL), Version 1.0+ *+ * Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this+ * software, associated documentation and/or data (collectively the "Software"), free of charge and under any and+ * all copyright rights in the Software, and any and all patent rights owned or freely licensable by each+ * licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor,+ * or (ii) the Larger Works (as defined below), to deal in both+ *+ *+ * (a) the Software, and+ *+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software+ * (each a “Larger Work” to which the Software is contributed by such licensors),+ *+ * without restriction, including without limitation the rights to copy, create derivative works of, display,+ * perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and+ * have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other+ * terms.+ *+ * This license is subject to the following condition:+ *+ * The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL+ * must be included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ * DEALINGS IN THE SOFTWARE.+ */+'use strict';+(function ()+{+++ var exec = require('cordova/exec');++ // Handles native file:// XHR GET requests+ function FileHandler(reqContext, config)+ {+ this._reqContext = reqContext;+ this._config = config;+ }++ FileHandler._getMimeType = function (reqContext)+ {+ if (reqContext.overrideMimeType)+ return reqContext.overrideMimeType;+ else if (reqContext.responseHeaders['content-type'])+ return reqContext.responseHeaders['content-type'];++ var url = reqContext.url;+ var ext = url.substr(url.lastIndexOf('.'));+ return FileHandler._EXT_TO_MIME[ext] ? FileHandler._EXT_TO_MIME[ext] : "";+ };++ FileHandler.getHandlerForResponseType = function (reqContext)+ {+ var responseType = reqContext.responseType;+ if (FileHandler._RESPONSE_HANDLERS[responseType])+ return FileHandler._RESPONSE_HANDLERS[responseType];+ else+ return FileHandler._RESPONSE_HANDLERS["text"];+ };++ FileHandler._EXT_TO_MIME = {+ ".img": "image/jpeg",+ ".png": "image/png",+ ".gif": "image/gif",+ ".xml": "application/xml",+ ".xsl": "application/xml",+ ".html": "text/html",+ ".htm": "text/html",+ ".svg": "image/svg+xml",+ ".svgz": "image/svg+xml",+ ".json": "application/json",+ ".js": "application/javascript"+ };++ FileHandler._RESPONSE_HANDLERS =+ {+ "text":+ {+ action: "readAsText",+ properties: ["response", "responseText"],+ convert: function (mimeType, r)+ {+ this._size = r["length"];+ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "arraybuffer":+ {+ action: "readAsArrayBuffer",+ properties: ["response"],+ convert: function (mimeType, r)+ {+ this._size = r["byteLength"];+ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "json":+ {+ action: "readAsText",+ properties: ["response"],+ convert: function (mimeType, r)+ {+ this._size = r["length"];+ try+ {+ r = JSON.parse(r);+ }+ catch (e)+ {+ }++ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "document":+ {+ action: "readAsText",+ properties: ["response", "responseXML"],+ convert: function (mimeType, r)+ {+ this._size = r["length"];+ try+ {+ r = new DOMParser().parseFromString(r, "text/xml");+ }+ catch (e)+ {+ }+ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "blob":+ {+ action: "readAsArrayBuffer",+ properties: ["response"],+ convert: function (mimeType, r)+ {+ var blob = new Blob([r], {"type": mimeType});+ this._size = blob.size;+ return blob;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ }+ };++ FileHandler.prototype._isTraceLoggingEnabled = function ()+ {+ return this._config["NativeXHRLogging"] === "full";+ };++ FileHandler._presend = function (reqContext)+ {+ reqContext.dispatchReadyStateChangeEvent(1); // OPEN+ reqContext.dispatchProgressEvent("loadstart");+ // no upload events for a GET+ };++ FileHandler._error = function (reqContext, e)+ {+ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native file XHR Response: Unable to find file %o\n%o", reqContext.url, e);++ reqContext.status = 404;+ reqContext.responseText = "File Not Found";++ reqContext.dispatchReadyStateChangeEvent(2); // HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); // LOADING+ reqContext.dispatchProgressEvent("progress");++ reqContext.dispatchReadyStateChangeEvent(4); // DONE+ reqContext.dispatchProgressEvent("error");+ reqContext.dispatchProgressEvent("loadend");+ };++ FileHandler._success = function (reqContext, rspTypeHandler, result)+ {+ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native file XHR Response:\n%o\n", reqContext.url, result);++ var mimeType = FileHandler._getMimeType(reqContext);+ var convertedResult = rspTypeHandler.convert(mimeType, result);++ var respSize = rspTypeHandler.responseSize();+ for (var i = 0; i < rspTypeHandler.properties.length; i++)+ reqContext[rspTypeHandler.properties[i]] = convertedResult;++ reqContext.status = 200;+ reqContext.statusText = "OK";+ reqContext.responseURL = reqContext.url;++ reqContext.dispatchReadyStateChangeEvent(2); // HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); // LOADING+ reqContext.dispatchProgressEvent("progress", respSize);+ reqContext.dispatchReadyStateChangeEvent(4); // DONE+ reqContext.dispatchProgressEvent("load", respSize);+ reqContext.dispatchProgressEvent("loadend", respSize);+ };++ FileHandler.prototype.send = function ()+ {+ var reqContext = this._reqContext;+ var rspTypeHandler = FileHandler.getHandlerForResponseType(reqContext);++ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native file XHR Request:\n%o", reqContext.url);++ FileHandler._presend(reqContext);++ exec(FileHandler._success.bind(this, reqContext, rspTypeHandler),+ FileHandler._error.bind(this, reqContext),+ "CDVWKWebViewFileXhr", rspTypeHandler.action, [reqContext.url]);+ };++ // handles http and https native XHR requests+ function HttpHandler(reqContext, config)+ {+ this._reqContext = reqContext;+ this._config = config;+ }++ HttpHandler._generateId = function ()+ {+ return [performance.now().toString(16), Math.random().toString(16)].join("-"); // FortifyFalsePositive+ };++ HttpHandler._convertTextToBinaryBase64String = function(mimeType, text)+ {+ var blob = new Blob([text], {type: mimeType});+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };+ });++ reader.readAsBinaryString(blob);++ return promise;+ };++ HttpHandler._REQUEST_HANDLERS =+ {+ "": {+ convert: function (reqContext)+ {+ return Promise.resolve(null);+ }+ },+ "ArrayBuffer": {+ convert: function (reqContext)+ {+ var body = reqContext.requestData;++ var type = reqContext.requestHeaders['content-type'];+ if (!type)+ type = reqContext.requestHeaders['content-type'] = "application/octet-binary;";++ var blob = new Blob([body], {type: type});+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };+ });++ reader.readAsBinaryString(blob);++ return promise;+ }+ },+ "FormData": {+ convert: function (reqContext)+ {+ var body = reqContext.requestData;+ var promise = new Promise(function (resolve, reject)+ {+ var contentType = reqContext.requestHeaders["content-type"];++ // FormData polyfill - request the body and context-type+ body.__getRequestParts().then(function (parts)+ {+ if (!contentType)+ reqContext.requestHeaders["content-type"] = parts.contentType;++ var reader = new FileReader();+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };++ reader.readAsBinaryString(parts.body);+ });+ });++ return promise;+ }+ },+ "Blob": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "application/octet-binary;";++ var body = reqContext.requestData;+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };+ });++ reader.readAsBinaryString(body);++ return promise;+ }+ },+ "string": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "text/plain;";++ var body = reqContext.requestData;+ var mimeType = reqContext.requestHeaders["content-type"];+ return HttpHandler._convertTextToBinaryBase64String(mimeType, body);+ }+ },+ "Object": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "application/json;";++ var body = JSON.stringify(reqContext.requestData);+ var mimeType = reqContext.requestHeaders["content-type"];+ return HttpHandler._convertTextToBinaryBase64String(mimeType, body);+ }+ },+ "Document": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "application/xhtml+xml;";++ var body = reqContext.requestData;+ var serializer = new XMLSerializer();+ var body = serializer.serializeToString(body);+ var mimeType = reqContext.requestHeaders["content-type"];+ return HttpHandler._convertTextToBinaryBase64String(mimeType, body);+ }+ }+ };++ HttpHandler._convertEncode64StringToText = function(mimeType, encoding, r)+ {+ var binaryString = atob(r);+ var byteNumbers = new Array(binaryString.length);+ for (var i = 0; i < binaryString.length; i++)+ byteNumbers[i] = binaryString.charCodeAt(i);++ var byteArray = new Uint8Array(byteNumbers);++ var blob = new Blob([byteArray], {type: mimeType});++ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {++ resolve(reader.result);+ };+ reader.onerror = function ()+ {+ reject(reader.error);+ };+ });++ reader.readAsText(blob, encoding);+ return promise;+ };++ HttpHandler._convertEncode64StringToArrayBuffer = function (mimeType, encoding, r)+ {+ var binaryString = atob(r);+ var byteNumbers = new Array(binaryString.length);+ for (var i = 0; i < binaryString.length; i++)+ byteNumbers[i] = binaryString.charCodeAt(i);++ var byteArray = new Uint8Array(byteNumbers);++ var blob = new Blob([byteArray], {type: mimeType});+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {++ resolve(reader.result);+ };+ reader.onerror = function ()+ {+ reject(reader.error);+ };+ });+ reader.readAsArrayBuffer(blob);+ return promise;+ };++ HttpHandler._RESPONSE_HANDLERS = {+ "text": {+ convert: HttpHandler._convertEncode64StringToText+ },+ "arraybuffer": {+ convert: HttpHandler._convertEncode64StringToArrayBuffer+ },+ "blob": {+ convert: HttpHandler._convertEncode64StringToArrayBuffer+ },+ "json": {+ convert: HttpHandler._convertEncode64StringToText+ },+ "document": {+ convert: HttpHandler._convertEncode64StringToText+ }+ };++ HttpHandler._UNDERLYING_ERROR_CODES = {+ NSURLErrorUnknown: -1,+ NSURLErrorCancelled: -999,+ NSURLErrorBadURL: -1000,+ NSURLErrorTimedOut: -1001,+ NSURLErrorUnsupportedURL: -1002,+ NSURLErrorCannotFindHost: -1003,+ NSURLErrorCannotConnectToHost: -1004,+ NSURLErrorNetworkConnectionLost: -1005,+ NSURLErrorDNSLookupFailed: -1006,+ NSURLErrorHTTPTooManyRedirects: -1007,+ NSURLErrorResourceUnavailable: -1008,+ NSURLErrorNotConnectedToInternet: -1009,+ NSURLErrorRedirectToNonExistentLocation: -1010,+ NSURLErrorBadServerResponse: -1011,+ NSURLErrorUserCancelledAuthentication: -1012,+ NSURLErrorUserAuthenticationRequired: -1013,+ NSURLErrorZeroByteResource: -1014,+ NSURLErrorCannotDecodeRawData: -1015,+ NSURLErrorCannotDecodeContentData: -1016,+ NSURLErrorCannotParseResponse: -1017,+ NSURLErrorAppTransportSecurityRequiresSecureConnection: -1022,+ NSURLErrorFileDoesNotExist: -1100,+ NSURLErrorFileIsDirectory: -1101,+ NSURLErrorNoPermissionsToReadFile: -1102,+ NSURLErrorDataLengthExceedsMaximum: -1103,+ NSURLErrorFileOutsideSafeArea: -1104,+ NSURLErrorSecureConnectionFailed: -1200,+ NSURLErrorServerCertificateHasBadDate: -1201,+ NSURLErrorServerCertificateUntrusted: -1202,+ NSURLErrorServerCertificateHasUnknownRoot: -1203,+ NSURLErrorServerCertificateNotYetValid: -1204,+ NSURLErrorClientCertificateRejected: -1205,+ NSURLErrorClientCertificateRequired: -1206,+ NSURLErrorCannotLoadFromNetwork: -2000,+ NSURLErrorCannotCreateFile: -3000,+ NSURLErrorCannotOpenFile: -3001,+ NSURLErrorCannotCloseFile: -3002,+ NSURLErrorCannotWriteToFile: -3003,+ NSURLErrorCannotRemoveFile: -3004,+ NSURLErrorCannotMoveFile: -3005,+ NSURLErrorDownloadDecodingFailedMidStream: -3006,+ NSURLErrorDownloadDecodingFailedToComplete: -3007,+ NSURLErrorInternationalRoamingOff: -1018,+ NSURLErrorCallIsActive: -1019,+ NSURLErrorDataNotAllowed: -1020,+ NSURLErrorRequestBodyStreamExhausted: -1021,+ NSURLErrorBackgroundSessionRequiresSharedContainer: -995,+ NSURLErrorBackgroundSessionInUseByAnotherProcess: -996,+ NSURLErrorBackgroundSessionWasDisconnected: -997+ };++ HttpHandler._getHandlerForRequestBodyType = function (reqContext)+ {+ var body = reqContext.requestData;+ if (!body)+ return HttpHandler._REQUEST_HANDLERS[""];+ else if (typeof body === "string")+ return HttpHandler._REQUEST_HANDLERS["string"];+ else if (Blob.prototype.isPrototypeOf(body))+ return HttpHandler._REQUEST_HANDLERS["Blob"];+ else if (FormData.prototype.isPrototypeOf(body))+ return HttpHandler._REQUEST_HANDLERS["FormData"];+ else if (ArrayBuffer.prototype.isPrototypeOf(body) ||+ body.buffer)+ return HttpHandler._REQUEST_HANDLERS["ArrayBuffer"];+ else if (Document.prototype.isPrototypeOf(body))+ return HttpHandler._REQUEST_HANDLERS["Document"];+ else+ return HttpHandler._REQUEST_HANDLERS["Object"];+ };++ HttpHandler._getHandlerForResponseType = function (reqContext)+ {+ var responseType = reqContext.responseType;+ if (HttpHandler._RESPONSE_HANDLERS[responseType])+ return HttpHandler._RESPONSE_HANDLERS[responseType];+ else+ return HttpHandler._RESPONSE_HANDLERS["text"];+ };++ HttpHandler.prototype._isTraceLoggingEnabled = function ()+ {+ return this._config["NativeXHRLogging"] === "full";+ };++ HttpHandler._resolveUri = function (uri)+ {+ if (uri.indexOf("://") > -1)+ return uri;++ var resolver = document.createElement("a");+ document.body.appendChild(resolver);+ resolver.href = uri;+ var absoluteUri = resolver.href;+ resolver.parentNode.removeChild(resolver);+ return absoluteUri;+ };++ HttpHandler.prototype.send = function ()+ {+ var reqContext = this._reqContext;+ var id = HttpHandler._generateId();++ if (reqContext.user && reqContext.password)+ {+ var token = [reqContext.user, reqContext.password].join(":");+ reqContext.requestHeaders["authorization"] = ["Basic", btoa(token)].join(" ");+ }++ window.__nativeXHRResponseQueue.set(id, this);++ var handler = HttpHandler._getHandlerForRequestBodyType(reqContext);+ handler.convert(reqContext).then(function (bodyAsBase64String)+ {+ var requestDataSize = bodyAsBase64String ? bodyAsBase64String.length : 0;+ reqContext.requestData = undefined;++ var timeoutInSecs = (isNaN(reqContext.timeout) ? undefined : (reqContext.timeout / 1000));++ var reqPayLoad = {id: id, callback: "nativeXHRResponse",+ url: HttpHandler._resolveUri(reqContext.url), method: reqContext.method,+ headers: reqContext.requestHeaders,+ body: bodyAsBase64String, timeout: timeoutInSecs};++ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native XHR Request:\n %o", reqPayLoad);++ HttpHandler._presend(reqContext, requestDataSize);++ window.webkit.messageHandlers.nativeXHR.postMessage(reqPayLoad);+ }.bind(this)).catch(HttpHandler._error.bind(this, reqContext));+ };++ HttpHandler._presend = function (reqContext, requestDataSize)+ {+ reqContext.dispatchReadyStateChangeEvent(1); // OPEN+ reqContext.dispatchProgressEvent("loadstart");++ // simulate upload progress events+ reqContext.dispatchUploadProgressEvent("loadstart");+ reqContext.dispatchUploadProgressEvent("progress", requestDataSize);+ reqContext.dispatchUploadProgressEvent("load", requestDataSize);+ reqContext.dispatchUploadProgressEvent("loadend", requestDataSize);+ };++ HttpHandler._success = function (reqContext, payload, mimeType, result)+ {+ var rspTypeHandler = FileHandler.getHandlerForResponseType(reqContext);+ var convertedResult = rspTypeHandler.convert(mimeType, result);++ // normalize header keys to lower case.+ var responseHeaders = payload.response.allHeaderFields;+ var normalizedHeaders = {};+ var keys = Object.keys(responseHeaders);+ for (var i = 0; i < keys.length; i++)+ {+ var key = keys[i];+ normalizedHeaders[key.toLowerCase()] = responseHeaders[key];+ }++ reqContext.responseHeaders = normalizedHeaders;++ reqContext.responseURL = payload.response.url;+ reqContext.status = payload.response.statusCode;+ reqContext.statusText = payload.response.localizedStatusCode;++ for (var i = 0; i < rspTypeHandler.properties.length; i++)+ reqContext[rspTypeHandler.properties[i]] = convertedResult;++ var respSize = rspTypeHandler.responseSize();++ reqContext.dispatchReadyStateChangeEvent(2); //HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); //LOADING+ reqContext.dispatchProgressEvent("progress", respSize);+ reqContext.dispatchReadyStateChangeEvent(4); //DONE++ reqContext.dispatchProgressEvent("load", respSize);+ reqContext.dispatchProgressEvent("loadend", respSize);+ };++ HttpHandler._error = function (reqContext, error, underlyingErrorCode)+ {+ var isTimeout = (HttpHandler._UNDERLYING_ERROR_CODES.NSURLErrorTimedOut === underlyingErrorCode);++ if (isTimeout)+ {+ reqContext.status = 0;+ reqContext.statusText = reqContext.responseText = null;+ }+ else+ {+ reqContext.status = 400;+ reqContext.statusText = "Bad Request";+ reqContext.responseText = error;+ }++ reqContext.dispatchReadyStateChangeEvent(2); //HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); //LOADING+ reqContext.dispatchProgressEvent("progress");+ reqContext.dispatchReadyStateChangeEvent(4); //DONE++ if (isTimeout)+ reqContext.dispatchProgressEvent("timeout");+ else+ reqContext.dispatchProgressEvent("error");++ reqContext.dispatchProgressEvent("loadend");+ };+++ HttpHandler.prototype.load = function (payload)+ {+ var reqContext = this._reqContext;++ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native XHR Response:\n%o", payload);++ if (payload.error)+ HttpHandler._error(reqContext, payload.error, payload['underlyingErrorCode']);+ else+ {+ var handler = HttpHandler._getHandlerForResponseType(reqContext);+ var mimeType = payload.response.mimeType;+ if (reqContext.overrideMimeType) // look for overrideMimeType+ mimeType = reqContext.overrideMimeType;+ else if (payload.response.allHeaderFields && payload.response.allHeaderFields["content-type"])+ mimeType = payload.response.allHeaderFields["content-type"];++ var encoding = payload.response.textEncodingName ? payload.response.textEncodingName : "UTF-8";++ handler.convert(mimeType, encoding, payload.data).then(HttpHandler._success.bind(this,+ reqContext, payload, mimeType));+ }+ };++ window.__nativeXHRResponseQueue = new Map();+ window.nativeXHRResponse = function (id, payload)+ {+ try+ {+ var handler = window.__nativeXHRResponseQueue.get(id);+ payload["id"] = id;+ handler.load(payload);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering request %o\n%o", id, e);+ }+ finally+ {+ window.__nativeXHRResponseQueue.delete(id);+ }+ };++ // sends the request using JS native XMLHttpRequest+ function DelegateHandler(reqContext, config)+ {+ this._reqContext = reqContext;+ this._reqContext.delegate = new window._XMLHttpRequest();+ this._config = config;+ }++ DelegateHandler._FROM_PROPERTIES = ["response", "responseText", "responseXML", "responseURL",+ "status", "statusText"];++ DelegateHandler._TO_PROPERTIES = ["responseType", "timeout", "withCredentials"];++ DelegateHandler._parseResponseHeaders = function (delegate, toHeaders)+ {+ var fromHeaders = delegate.getAllResponseHeaders().split(/\r?\n/);+ for (var i = 0; i < fromHeaders.length; i++)+ {+ var tokens = fromHeaders[i];+ var n = tokens.indexOf(": ");+ if (n > -1)+ {+ var key = tokens.substr(0, n).toLowerCase();+ var value = tokens.substr(n + 2);+ toHeaders[key] = value;+ }+ }+ };++ DelegateHandler._progressEventRelay = function (reqContext, event)+ {+ var respSize = isNaN(event.totalSize) ? 0 : event.totalSize;+ reqContext.dispatchProgressEvent(event.type, respSize);+ };++ DelegateHandler._uploadProgressEventRelay = function (reqContext, event)+ {+ var respSize = isNaN(event.totalSize) ? 0 : event.totalSize;+ reqContext.dispatchUploadProgressEvent(event.type, respSize);+ };++ DelegateHandler._readystatechangeEventRelay = function (reqContext, delegate, event)+ {++ if (delegate.readyState > 1) // readyState gt HEADERS_RECIEVED+ {+ if (Object.keys(reqContext.responseHeaders).length === 0)+ DelegateHandler._parseResponseHeaders(delegate, reqContext.responseHeaders);++ for (var i = 0; i < DelegateHandler._FROM_PROPERTIES.length; i++)+ {+ try+ {+ reqContext[DelegateHandler._FROM_PROPERTIES[i]] = delegate[DelegateHandler._FROM_PROPERTIES[i]];+ }+ catch (e)+ {+ }+ }++ reqContext.dispatchReadyStateChangeEvent(delegate.readyState);+ }+ };++ DelegateHandler.prototype.send = function ()+ {+ var reqContext = this._reqContext;+ var delegate = reqContext.delegate;++ delegate.onreadystatechange = DelegateHandler._readystatechangeEventRelay.bind(delegate,+ reqContext, delegate);+ ["ontimeout", "onloadstart", "onprogress", "onabort", "onerror", "onload",+ "onloadend"].forEach(function (eventType)+ {+ delegate[eventType] = DelegateHandler._progressEventRelay.bind(delegate, reqContext);+ delegate.upload[eventType] = DelegateHandler._uploadProgressEventRelay.bind(delegate,+ reqContext);+ });++ if (reqContext.overrideMimeType)+ delegate.overrideMimeType(reqContext.overrideMimeType);++ delegate.open(reqContext.method, reqContext.url, reqContext.async, reqContext.user,+ reqContext.password);++ for (var i = 0; i < DelegateHandler._TO_PROPERTIES.length; i++)+ delegate[DelegateHandler._TO_PROPERTIES[i]] = reqContext[DelegateHandler._TO_PROPERTIES[i]];++ var keys = Object.keys(reqContext.requestHeaders);+ for (var i = 0; i < keys.length; i++)+ delegate.setRequestHeader(keys[i], reqContext.requestHeaders[keys[i]]);++ var requestData = reqContext.requestData;+ reqContext.requestData = undefined;++ // returns a native FormData from the plugin's polyfill+ if (FormData.prototype.isPrototypeOf(requestData))+ requestData = requestData.__getNative();++ delegate.send(requestData);+ };++ function HandlerFactory()+ {+ }++ HandlerFactory._getConfig = function ()+ {+ var promise;+ if (HandlerFactory._config)+ {+ promise = Promise.resolve(HandlerFactory._config);+ }+ else+ {+ promise = new Promise(function (done)+ {+ function success(result)+ {+ HandlerFactory._config = result;+ done(HandlerFactory._config);+ }++ function error()+ {+ HandlerFactory._config = {"InterceptRemoteRequests": "secureOnly",+ "NativeXHRLogging": "none"};+ done(HandlerFactory._config);+ }++ exec(success, error, "CDVWKWebViewFileXhr", "getConfig", []);+ });++ }++ return promise;+ };++ HandlerFactory.getHandler = function (context)+ {+ var promise = new Promise(function (resolve)+ {+ HandlerFactory._getConfig().then(function (config)+ {+ var interceptRemoteRequests = config["InterceptRemoteRequests"];++ if (context.interceptRemoteRequests) // backdoor to override per instance+ interceptRemoteRequests = context.interceptRemoteRequests;++ if ("GET" === context.method && typeof context.url === "string" &&+ ((context.url.indexOf("://") === -1 && window.location.protocol === "file:") ||+ (context.url.toLowerCase().startsWith("file://"))))+ {+ resolve(new FileHandler(context, config));+ }+ else+ {+ if ("all" === interceptRemoteRequests ||+ ("secureOnly" === interceptRemoteRequests && context.url.startsWith("https://")))+ resolve(new HttpHandler(context, config));+ else+ resolve(new DelegateHandler(context, config));+ }+ });+ });++ return promise;+ };++ function _XMLHttpRequestUpload()+ {+ this._context = {"listeners": {}};+ }++ _XMLHttpRequestUpload.prototype.removeEventListener = function (type, listener)+ {+ var listeners = this._context.listeners;+ if (!listener)+ listeners[type] = [];+ else+ {+ var lset = listeners[type] ? listeners[type] : [];+ var i = lset.indexOf(listener);+ if (i > -1)+ lset.splice(i, 1);+ }+ };++ _XMLHttpRequestUpload.prototype.addEventListener = function (type, listener)+ {+ if (!listener)+ return;++ var listeners = this._context.listeners;+ var lset = listeners[type];+ if (!lset)+ lset = listeners[type] = [];++ if (lset.indexOf(listeners) < 0)+ lset.push(listener);+ };++ _XMLHttpRequestUpload.prototype.dispatchEvent = function (event)+ {+ if (!event)+ return;++ var type = event.type;+ var listeners = this._context.listeners;+ var lset = listeners[type] ? listeners[type] : [];++ // call property listeners+ var listener = this._context[["on", type].join("")];+ if (listener)+ {+ try+ {+ listener.call(this, event);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering upload event %o\n%o", event, e);+ }+ }+ };++ /** @type {?} */+ window._XMLHttpRequest = window.XMLHttpRequest;+ window.XMLHttpRequest = function ()+ {+ this._context = {delegate: null, requestHeaders: {}, responseHeaders: {},+ listeners: {}, readyState: 0, responseType: "text", withCredentials: false,+ upload: new _XMLHttpRequestUpload(), status: 0};++ this._context.dispatchProgressEvent = function (req, type, respSize)+ {+ if (isNaN(respSize))+ respSize = 0;++ var event = document.createEvent("Event");+ event.initEvent(type, false, false);+ ["total", "totalSize", "loaded", "position"].forEach(function (propName)+ {+ Object.defineProperty(event, propName, {value: respSize});+ });+ Object.defineProperty(event, "lengthComputable", {value: respSize === 0 ? false : true});++ req.dispatchEvent(event);+ }.bind(this._context, this);++ this._context.dispatchReadyStateChangeEvent = function (req, readyState)+ {+ var event = document.createEvent("Event");+ event.initEvent("readystatechange", false, false);++ this.readyState = readyState;+ req.dispatchEvent(event);+ }.bind(this._context, this);++ this._context.dispatchUploadProgressEvent = function (type, reqSize)+ {+ // no body sent on a GET request+ if (this.method === "GET")+ return;++ if (isNaN(reqSize))+ reqSize = 0;++ var event = document.createEvent("Event");+ event.initEvent(type, false, false);+ ["total", "totalSize", "loaded", "position"].forEach(function (propName)+ {+ Object.defineProperty(event, propName, {value: reqSize});+ });+ Object.defineProperty(event, "lengthComputable", {value: reqSize === 0 ? false : true});++ this.upload.dispatchEvent(event);+ }.bind(this._context);+ };+++ // define readonly const properties+ ["UNSENT", "OPENED", "HEADERS_RECIEVED", "LOADING", "DONE"].forEach(function (propName, i)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return i;+ }+ });+ });++ // define readonly properties.+ ["readyState", "response", "responseText", "responseURL", "responseXML",+ "status", "statusText", "upload"].forEach(function (propName)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ }+ });+ });++// define read/write properties+ ["responseType", "timeout", "withCredentials"].forEach(function (propName)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ },+ "set": function (value)+ {+ this._context[propName] = value;+ }+ });+ });++ // define read/write readychange event listener properties+ Object.defineProperty(window.XMLHttpRequest.prototype, "onreadystatechange",+ {+ "get": function ()+ {+ return this._context["onreadystatechange"];+ },+ "set": function (value)+ {+ if (typeof value === "function")+ this._context["onreadystatechange"] = value;+ }+ });++ // define read/write event progress listener properties+ ["ontimeout", "onloadstart", "onprogress", "onabort", "onerror", "onload", "onloadend"].forEach(+ function (propName)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ },+ "set": function (value)+ {+ if (typeof value === "function")+ this._context[propName] = value;+ }+ });++ Object.defineProperty(_XMLHttpRequestUpload.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ },+ "set": function (value)+ {+ if (typeof value === "function")+ this._context[propName] = value;+ }+ });+ });++ window.XMLHttpRequest.prototype.setRequestHeader = function (header, value)+ {+ // normalize value pair to strings+ header = String(header).toLowerCase();;+ value = String(value);+ this._context.requestHeaders[header] = value;+ };++ window.XMLHttpRequest.prototype.abort = function ()+ {+ if (this._context["delegate"])+ this._context.delegate.abort();+ };++ window.XMLHttpRequest.prototype.getResponseHeader = function (name)+ {+ name = name.toLowerCase();+ return this._context.responseHeaders[name];+ };++ window.XMLHttpRequest.prototype.overrideMimeType = function (mimetype)+ {+ return this._context.overrideMimeType = mimetype;+ };++ window.XMLHttpRequest.prototype.getAllResponseHeaders = function ()+ {+ var responseHeaders = this._context.responseHeaders;+ var names = Object.keys(responseHeaders);+ var list = [];+ for (var i = 0; i < names.length; i++)+ list.push([names[i], responseHeaders[names[i]]].join(":"));++ return list.join("\n");+ };++ window.XMLHttpRequest.prototype.removeEventListener = function (type, listener)+ {+ var listeners = this._context.listeners;+ if (!listener)+ listeners[type] = [];+ else+ {+ var lset = listeners[type] ? listeners[type] : [];+ var i = lset.indexOf(listener);+ if (i > -1)+ lset.splice(i, 1);+ }+ };++ window.XMLHttpRequest.prototype.addEventListener = function (type, listener)+ {+ if (!listener)+ return;++ var listeners = this._context.listeners;+ var lset = listeners[type];+ if (!lset)+ lset = listeners[type] = [];++ if (lset.indexOf(listeners) < 0)+ lset.push(listener);+ };++ window.XMLHttpRequest.prototype.dispatchEvent = function (event)+ {+ if (!event)+ return;++ var type = event.type;+ var listeners = this._context.listeners;+ var lset = listeners[type] ? listeners[type] : [];++ // call property listeners+ var listener = this._context[["on", type].join("")];+ if (listener)+ {+ try+ {+ listener.call(this, event);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering event %o\n%o", event, e);+ }+ }++ // call listeners registered via addEventListener+ for (var i = 0; i < lset.length; i++)+ {+ listener = lset[i];+ if (listener)+ {+ try+ {+ listener.call(this, event);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering event %o\n%o", event, e);+ }+ }+ }+ };++ window.XMLHttpRequest.prototype.open = function (method, url, async, user, password)+ {+ this._context.method = !method ? "GET" : method.toUpperCase(); // FortifyFalsePositive+ this._context.url = url;+ this._context.async = async === undefined ? true : async;+ this._context.user = user;+ this._context.password = password;+ };++ window.XMLHttpRequest.prototype.send = function (data)+ {+ if ("GET" !== this._context.method && "HEAD" !== this._context.method)+ this._context.requestData = data;++ HandlerFactory.getHandler(this._context).then(function (handler)+ {+ handler.send();+ });+ };++ /**+ * Override plugin config settings per request instance for the "InterceptRemoteRequests"+ * config param.+ *+ * @param {string} value enumerations are: "all", "secureOnly", "none".+ */+ window.XMLHttpRequest.prototype.__setInterceptRemoteRequests = function (value)+ {+ if (["all", "secureOnly", "none"].indexOf(value) > -1)+ {+ this._context.interceptRemoteRequests = value;+ }+ };++})();++});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.jsdeleted file mode 100644index dc7595da2..000000000--- a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.js+++ /dev/null@@ -1,177 +0,0 @@-cordova.define("cordova-plugin-wkwebview-engine.ios-wkwebview-exec", function(require, exports, module) {-/*- *- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- *-*/--/**- * Creates the exec bridge used to notify the native code of- * commands.- */-var cordova = require('cordova');-var utils = require('cordova/utils');-var base64 = require('cordova/base64');--function massageArgsJsToNative (args) {- if (!args || utils.typeName(args) !== 'Array') {- return args;- }- var ret = [];- args.forEach(function (arg, i) {- if (utils.typeName(arg) === 'ArrayBuffer') {- ret.push({- 'CDVType': 'ArrayBuffer',- 'data': base64.fromArrayBuffer(arg)- });- } else {- ret.push(arg);- }- });- return ret;-}--function massageMessageNativeToJs (message) {- if (message.CDVType === 'ArrayBuffer') {- var stringToArrayBuffer = function (str) {- var ret = new Uint8Array(str.length);- for (var i = 0; i < str.length; i++) {- ret[i] = str.charCodeAt(i);- }- return ret.buffer;- };- var base64ToArrayBuffer = function (b64) {- return stringToArrayBuffer(atob(b64)); // eslint-disable-line no-undef- };- message = base64ToArrayBuffer(message.data);- }- return message;-}--function convertMessageToArgsNativeToJs (message) {- var args = [];- if (!message || !message.hasOwnProperty('CDVType')) {- args.push(message);- } else if (message.CDVType === 'MultiPart') {- message.messages.forEach(function (e) {- args.push(massageMessageNativeToJs(e));- });- } else {- args.push(massageMessageNativeToJs(message));- }- return args;-}--var iOSExec = function () {- // detect change in bridge, if there is a change, we forward to new bridge-- // if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) {- // bridgeMode = jsToNativeModes.WK_WEBVIEW_BINDING;- // }-- var successCallback, failCallback, service, action, actionArgs;- var callbackId = null;- if (typeof arguments[0] !== 'string') {- // FORMAT ONE- successCallback = arguments[0];- failCallback = arguments[1];- service = arguments[2];- action = arguments[3];- actionArgs = arguments[4];-- // Since we need to maintain backwards compatibility, we have to pass- // an invalid callbackId even if no callback was provided since plugins- // will be expecting it. The Cordova.exec() implementation allocates- // an invalid callbackId and passes it even if no callbacks were given.- callbackId = 'INVALID';- } else {- throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + // eslint-disable-line- 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);');- }-- // If actionArgs is not provided, default to an empty array- actionArgs = actionArgs || [];-- // Register the callbacks and add the callbackId to the positional- // arguments if given.- if (successCallback || failCallback) {- callbackId = service + cordova.callbackId++;- cordova.callbacks[callbackId] =- {success: successCallback, fail: failCallback};- }-- actionArgs = massageArgsJsToNative(actionArgs);-- // CB-10133 DataClone DOM Exception 25 guard (fast function remover)- var command = [callbackId, service, action, JSON.parse(JSON.stringify(actionArgs))];- window.webkit.messageHandlers.cordova.postMessage(command);-};--iOSExec.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- });-};--// for backwards compatibility-iOSExec.nativeEvalAndFetch = function (func) {- try {- func();- } catch (e) {- console.log(e);- }-};--// Proxy the exec for bridge changes. See CB-10106--function cordovaExec () {- var cexec = require('cordova/exec');- var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function');- return (cexec_valid && execProxy !== cexec) ? cexec : iOSExec;-}--function execProxy () {- cordovaExec().apply(null, arguments);-}--execProxy.nativeFetchMessages = function () {- return cordovaExec().nativeFetchMessages.apply(null, arguments);-};--execProxy.nativeEvalAndFetch = function () {- return cordovaExec().nativeEvalAndFetch.apply(null, arguments);-};--execProxy.nativeCallback = function () {- return cordovaExec().nativeCallback.apply(null, arguments);-};--module.exports = execProxy;--if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) {- // unregister the old bridge- cordova.define.remove('cordova/exec');- // redefine bridge to our new bridge- cordova.define('cordova/exec', function (require, exports, module) {- module.exports = execProxy;- });-}--});diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-x-socialsharing/www/SocialSharing.jsnew file mode 100644index 000000000..d16bfdc1c--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js@@ -0,0 +1,160 @@+cordova.define("cordova-plugin-x-socialsharing.SocialSharing", function(require, exports, module) {+function SocialSharing() {+}++// Override this method (after deviceready) to set the location where you want the iPad popup arrow to appear.+// If not overridden with different values, the popup is not used. Example:+//+// window.plugins.socialsharing.iPadPopupCoordinates = function() {+// return "100,100,200,300";+// };+SocialSharing.prototype.iPadPopupCoordinates = function () {+ // left,top,width,height+ return "-1,-1,-1,-1";+};++SocialSharing.prototype.setIPadPopupCoordinates = function (coords) {+ console.log("Deprecated - setIPadPopupCoordinates no longer works since plugin version 5.5.0. See https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin/issues/1052");+ // left,top,width,height+ cordova.exec(function() {}, this._getErrorCallback(function() {}, "setIPadPopupCoordinates"), "SocialSharing", "setIPadPopupCoordinates", [coords]);+};++SocialSharing.prototype.available = function (callback) {+ cordova.exec(function (avail) {+ callback(avail ? true : false);+ }, null, "SocialSharing", "available", []);+};++// this is the recommended way to share as it is the most feature-rich with respect to what you pass in and get back+SocialSharing.prototype.shareWithOptions = function (options, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareWithOptions"), "SocialSharing", "shareWithOptions", [options]);+};++SocialSharing.prototype.shareW3C = function (sharedata) {+ return new Promise(function(resolve, reject) {+ var options = {+ subject: sharedata.title,+ message: sharedata.text,+ url: sharedata.url,+ iPadCoordinates: sharedata.iPadCoordinates || undefined+ };+ if(sharedata.hasOwnProperty('title') ||+ sharedata.hasOwnProperty('text') ||+ sharedata.hasOwnProperty('url')) {+ cordova.exec(resolve, reject, "SocialSharing", "shareWithOptions", [options]);+ } else {+ reject();+ }+ });+};++SocialSharing.prototype.share = function (message, subject, fileOrFileArray, url, iPadCoordinates, successCallback, errorCallback) {+ if (typeof iPadCoordinates === 'function') {+ errorCallback = successCallback;+ successCallback = iPadCoordinates;+ iPadCoordinates = "";+ }+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "share"), "SocialSharing", "share", [message, subject, this._asArray(fileOrFileArray), url, iPadCoordinates]);+};++SocialSharing.prototype.shareViaTwitter = function (message, file /* multiple not allowed by twitter */, url, successCallback, errorCallback) {+ var fileArray = this._asArray(file);+ var ecb = this._getErrorCallback(errorCallback, "shareViaTwitter");+ if (fileArray.length > 1) {+ ecb("shareViaTwitter supports max one file");+ } else {+ cordova.exec(successCallback, ecb, "SocialSharing", "shareViaTwitter", [message, null, fileArray, url]);+ }+};++SocialSharing.prototype.shareViaFacebook = function (message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaFacebook"), "SocialSharing", "shareViaFacebook", [message, null, this._asArray(fileOrFileArray), url]);+};++SocialSharing.prototype.shareViaFacebookWithPasteMessageHint = function (message, fileOrFileArray, url, pasteMessageHint, successCallback, errorCallback) {+ pasteMessageHint = pasteMessageHint || "If you like you can paste a message from your clipboard";+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaFacebookWithPasteMessageHint"), "SocialSharing", "shareViaFacebookWithPasteMessageHint", [message, null, this._asArray(fileOrFileArray), url, pasteMessageHint]);+};++SocialSharing.prototype.shareViaWhatsApp = function (message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaWhatsApp"), "SocialSharing", "shareViaWhatsApp", [message, null, this._asArray(fileOrFileArray), url, null, null]);+};++SocialSharing.prototype.shareViaWhatsAppToReceiver = function (receiver, message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaWhatsAppToReceiver"), "SocialSharing", "shareViaWhatsApp", [message, null, this._asArray(fileOrFileArray), url, receiver, null]);+};++SocialSharing.prototype.shareViaWhatsAppToPhone = function (phone, message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaWhatsAppToPhone"), "SocialSharing", "shareViaWhatsApp", [message, null, this._asArray(fileOrFileArray), url, null, phone]);+};++SocialSharing.prototype.shareViaSMS = function (options, phonenumbers, successCallback, errorCallback) {+ var opts = options;+ if (typeof options === "string") {+ opts = {"message":options}; // for backward compatibility as the options param used to be the message+ }+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaSMS"), "SocialSharing", "shareViaSMS", [opts, phonenumbers]);+};++SocialSharing.prototype.shareViaEmail = function (message, subject, toArray, ccArray, bccArray, fileOrFileArray, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaEmail"), "SocialSharing", "shareViaEmail", [message, subject, this._asArray(toArray), this._asArray(ccArray), this._asArray(bccArray), this._asArray(fileOrFileArray)]);+};++SocialSharing.prototype.canShareVia = function (via, message, subject, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "canShareVia"), "SocialSharing", "canShareVia", [message, subject, this._asArray(fileOrFileArray), url, via]);+};++SocialSharing.prototype.canShareViaEmail = function (successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "canShareViaEmail"), "SocialSharing", "canShareViaEmail", []);+};++SocialSharing.prototype.shareViaInstagram = function (message, fileOrFileArray, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaInstagram"), "SocialSharing", "shareViaInstagram", [message, null, this._asArray(fileOrFileArray), null]);+};++SocialSharing.prototype.shareVia = function (via, message, subject, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareVia"), "SocialSharing", "shareVia", [message, subject, this._asArray(fileOrFileArray), url, via]);+};++SocialSharing.prototype.saveToPhotoAlbum = function (fileOrFileArray, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "saveToPhotoAlbum"), "SocialSharing", "saveToPhotoAlbum", [this._asArray(fileOrFileArray)]);+};++SocialSharing.prototype._asArray = function (param) {+ if (param == null) {+ param = [];+ } else if (typeof param === 'string') {+ param = new Array(param);+ }+ return param;+};++SocialSharing.prototype._getErrorCallback = function (ecb, functionName) {+ if (typeof ecb === 'function') {+ return ecb;+ } else {+ return function (result) {+ console.log("The injected error callback of '" + functionName + "' received: " + JSON.stringify(result));+ }+ }+};++SocialSharing.install = function () {+ if (!window.plugins) {+ window.plugins = {};+ }++ window.plugins.socialsharing = new SocialSharing();++ // Note only polyfill navigator.share if it is not defined, since shareW3C implements L1 of the spec,+ // and an existing navigator.share method could implement L2.+ if (!navigator.share) {+ navigator.share = window.plugins.socialsharing.shareW3C;+ }++ return window.plugins.socialsharing;+};++cordova.addConstructor(SocialSharing.install);++});diff --git a/cordova/platforms/ios/platform_www/plugins/es6-promise-plugin/www/promise.js b/cordova/platforms/ios/platform_www/plugins/es6-promise-plugin/www/promise.jsnew file mode 100644index 000000000..6cce47ae8--- /dev/null+++ b/cordova/platforms/ios/platform_www/plugins/es6-promise-plugin/www/promise.js@@ -0,0 +1,13 @@+cordova.define("es6-promise-plugin.Promise", function(require, exports, module) {+/*!+ * @overview es6-promise - a tiny implementation of Promises/A+.+ * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)+ * @license Licensed under MIT license+ * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE+ * @version v4.2.2+97478eb6+ */++!function t(e,n,r){function o(u,s){if(!n[u]){if(!e[u]){var c="function"==typeof require&&require;if(!s&&c)return c(u,!0);if(i)return i(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var a=n[u]={exports:{}};e[u][0].call(a.exports,function(t){var n=e[u][1][t];return o(n?n:t)},a,a.exports,t,e,n,r)}return n[u].exports}for(var i="function"==typeof require&&require,u=0;u<r.length;u++)o(r[u]);return o}({1:[function(t){void 0===window.Promise&&t("es6-promise").polyfill()},{"es6-promise":2}],2:[function(t,e,n){(function(r,o){!function(t,r){"object"==typeof n&&"undefined"!=typeof e?e.exports=r():"function"==typeof define&&define.amd?define(r):t.ES6Promise=r()}(this,function(){"use strict";function e(t){var e=typeof t;return null!==t&&("object"===e||"function"===e)}function n(t){return"function"==typeof t}function i(t){J=t}function u(t){Q=t}function s(){return function(){return r.nextTick(h)}}function c(){return"undefined"!=typeof I?function(){I(h)}:l()}function f(){var t=0,e=new X(h),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function a(){var t=new MessageChannel;return t.port1.onmessage=h,function(){return t.port2.postMessage(0)}}function l(){var t=setTimeout;return function(){return t(h,1)}}function h(){for(var t=0;H>t;t+=2){var e=te[t],n=te[t+1];e(n),te[t]=void 0,te[t+1]=void 0}H=0}function p(){try{var e=t,n=e("vertx");return I=n.runOnLoop||n.runOnContext,c()}catch(r){return l()}}function d(t,e){var n=this,r=new this.constructor(y);void 0===r[ne]&&D(r);var o=n._state;if(o){var i=arguments[o-1];Q(function(){return L(o,r,i,n._result)})}else O(n,r,t,e);return r}function v(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(y);return E(n,t),n}function y(){}function m(){return new TypeError("You cannot resolve a promise with itself")}function _(){return new TypeError("A promises callback cannot return that same promise.")}function w(t){try{return t.then}catch(e){return ue.error=e,ue}}function g(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function b(t,e,n){Q(function(t){var r=!1,o=g(n,e,function(n){r||(r=!0,e!==n?E(t,n):j(t,n))},function(e){r||(r=!0,x(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,x(t,o))},t)}function T(t,e){e._state===oe?j(t,e._result):e._state===ie?x(t,e._result):O(e,void 0,function(e){return E(t,e)},function(e){return x(t,e)})}function A(t,e,r){e.constructor===t.constructor&&r===d&&e.constructor.resolve===v?T(t,e):r===ue?(x(t,ue.error),ue.error=null):void 0===r?j(t,e):n(r)?b(t,e,r):j(t,e)}function E(t,n){t===n?x(t,m()):e(n)?A(t,n,w(n)):j(t,n)}function S(t){t._onerror&&t._onerror(t._result),M(t)}function j(t,e){t._state===re&&(t._result=e,t._state=oe,0!==t._subscribers.length&&Q(M,t))}function x(t,e){t._state===re&&(t._state=ie,t._result=e,Q(S,t))}function O(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+oe]=n,o[i+ie]=r,0===i&&t._state&&Q(M,t)}function M(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r=void 0,o=void 0,i=t._result,u=0;u<e.length;u+=3)r=e[u],o=e[u+n],r?L(n,r,o,i):o(i);t._subscribers.length=0}}function P(){this.error=null}function C(t,e){try{return t(e)}catch(n){return se.error=n,se}}function L(t,e,r,o){var i=n(r),u=void 0,s=void 0,c=void 0,f=void 0;if(i){if(u=C(r,o),u===se?(f=!0,s=u.error,u.error=null):c=!0,e===u)return x(e,_()),void 0}else u=o,c=!0;e._state!==re||(i&&c?E(e,u):f?x(e,s):t===oe?j(e,u):t===ie&&x(e,u))}function k(t,e){try{e(function(e){E(t,e)},function(e){x(t,e)})}catch(n){x(t,n)}}function q(){return ce++}function D(t){t[ne]=ce++,t._state=void 0,t._result=void 0,t._subscribers=[]}function F(){return new Error("Array Methods must be provided an Array")}function F(){return new Error("Array Methods must be provided an Array")}function N(t){return new fe(this,t).promise}function U(t){var e=this;return G(t)?new e(function(n,r){for(var o=t.length,i=0;o>i;i++)e.resolve(t[i]).then(n,r)}):new e(function(t,e){return e(new TypeError("You must pass an array to race."))})}function Y(t){var e=this,n=new e(y);return x(n,t),n}function K(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function W(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function z(){var t=void 0;if("undefined"!=typeof o)t=o;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;if(n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(e){}if("[object Promise]"===r&&!n.cast)return}t.Promise=ae}var B=void 0;B=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var G=B,H=0,I=void 0,J=void 0,Q=function(t,e){te[H]=t,te[H+1]=e,H+=2,2===H&&(J?J(h):ee())},R="undefined"!=typeof window?window:void 0,V=R||{},X=V.MutationObserver||V.WebKitMutationObserver,Z="undefined"==typeof self&&"undefined"!=typeof r&&"[object process]"==={}.toString.call(r),$="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,te=new Array(1e3),ee=void 0;ee=Z?s():X?f():$?a():void 0===R&&"function"==typeof t?p():l();var ne=Math.random().toString(36).substring(16),re=void 0,oe=1,ie=2,ue=new P,se=new P,ce=0,fe=function(){function t(t,e){this._instanceConstructor=t,this.promise=new t(y),this.promise[ne]||D(this.promise),G(e)?(this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?j(this.promise,this._result):(this.length=this.length||0,this._enumerate(e),0===this._remaining&&j(this.promise,this._result))):x(this.promise,F())}return t.prototype._enumerate=function(t){for(var e=0;this._state===re&&e<t.length;e++)this._eachEntry(t[e],e)},t.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===v){var o=w(t);if(o===d&&t._state!==re)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===ae){var i=new n(y);A(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(r(t),e)},t.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===re&&(this._remaining--,t===ie?x(r,n):this._result[e]=n),0===this._remaining&&j(r,this._result)},t.prototype._willSettleAt=function(t,e){var n=this;O(t,void 0,function(t){return n._settledAt(oe,e,t)},function(t){return n._settledAt(ie,e,t)})},t}(),ae=function(){function t(e){this[ne]=q(),this._result=this._state=void 0,this._subscribers=[],y!==e&&("function"!=typeof e&&K(),this instanceof t?k(this,e):W())}return t.prototype.catch=function(t){return this.then(null,t)},t.prototype.finally=function(t){var e=this,n=e.constructor;return e.then(function(e){return n.resolve(t()).then(function(){return e})},function(e){return n.resolve(t()).then(function(){throw e})})},t}();return ae.prototype.then=d,ae.all=N,ae.race=U,ae.resolve=v,ae.reject=Y,ae._setScheduler=i,ae._setAsap=u,ae._asap=Q,ae.polyfill=z,ae.Promise=ae,ae})}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:3}],3:[function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(t){if(a===setTimeout)return setTimeout(t,0);if((a===n||!a)&&setTimeout)return a=setTimeout,setTimeout(t,0);try{return a(t,0)}catch(e){try{return a.call(null,t,0)}catch(e){return a.call(this,t,0)}}}function i(t){if(l===clearTimeout)return clearTimeout(t);if((l===r||!l)&&clearTimeout)return l=clearTimeout,clearTimeout(t);try{return l(t)}catch(e){try{return l.call(null,t)}catch(e){return l.call(this,t)}}}function u(){v&&p&&(v=!1,p.length?d=p.concat(d):y=-1,d.length&&s())}function s(){if(!v){var t=o(u);v=!0;for(var e=d.length;e;){for(p=d,d=[];++y<e;)p&&p[y].run();y=-1,e=d.length}p=null,v=!1,i(t)}}function c(t,e){this.fun=t,this.array=e}function f(){}var a,l,h=e.exports={};!function(){try{a="function"==typeof setTimeout?setTimeout:n}catch(t){a=n}try{l="function"==typeof clearTimeout?clearTimeout:r}catch(t){l=r}}();var p,d=[],v=!1,y=-1;h.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];d.push(new c(t,e)),1!==d.length||v||o(s)},c.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=f,h.addListener=f,h.once=f,h.off=f,h.removeListener=f,h.removeAllListeners=f,h.emit=f,h.prependListener=f,h.prependOnceListener=f,h.listeners=function(){return[]},h.binding=function(){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},{}]},{},[1]);+++});diff --git a/cordova/platforms/ios/www/cordova-js-src/.eslintrc.yml b/cordova/platforms/ios/www/cordova-js-src/.eslintrc.ymldeleted file mode 100644index e3d49d8a0..000000000--- a/cordova/platforms/ios/www/cordova-js-src/.eslintrc.yml+++ /dev/null@@ -1,4 +0,0 @@-env:- node: false- commonjs: true- browser: truediff --git a/cordova/platforms/ios/www/cordova-js-src/exec.js b/cordova/platforms/ios/www/cordova-js-src/exec.jsindex e7f6ce1c6..466220d83 100644--- a/cordova/platforms/ios/www/cordova-js-src/exec.js+++ b/cordova/platforms/ios/www/cordova-js-src/exec.js@@ -19,19 +19,13 @@**/-/* global require, module, atob, document */-/**- * Creates a gap bridge iframe used to notify the native code about queued+ * Creates the exec bridge used to notify the native code of* commands.*/var cordova = require('cordova');var utils = require('cordova/utils');var base64 = require('cordova/base64');-var execIframe;-var commandQueue = []; // Contains pending JS->Native messages.-var isInContextOfEvalJs = 0;-var failSafeTimerId = 0;function massageArgsJsToNative (args) {if (!args || utils.typeName(args) !== 'Array') {@@ -41,8 +35,8 @@ function massageArgsJsToNative (args) {args.forEach(function (arg, i) {if (utils.typeName(arg) === 'ArrayBuffer') {ret.push({- 'CDVType': 'ArrayBuffer',- 'data': base64.fromArrayBuffer(arg)+ CDVType: 'ArrayBuffer',+ data: base64.fromArrayBuffer(arg)});} else {ret.push(arg);@@ -61,7 +55,7 @@ function massageMessageNativeToJs (message) {return ret.buffer;};var base64ToArrayBuffer = function (b64) {- return stringToArrayBuffer(atob(b64));+ return stringToArrayBuffer(atob(b64)); // eslint-disable-line no-undef};message = base64ToArrayBuffer(message.data);}@@ -70,7 +64,7 @@ function massageMessageNativeToJs (message) {function convertMessageToArgsNativeToJs (message) {var args = [];- if (!message || !message.hasOwnProperty('CDVType')) {+ if (!message || !Object.prototype.hasOwnProperty.call(message, 'CDVType')) {args.push(message);} else if (message.CDVType === 'MultiPart') {message.messages.forEach(function (e) {@@ -82,8 +76,7 @@ function convertMessageToArgsNativeToJs (message) {return args;}-function iOSExec () {-+var iOSExec = function () {var successCallback, failCallback, service, action, actionArgs;var callbackId = null;if (typeof arguments[0] !== 'string') {@@ -100,9 +93,8 @@ function iOSExec () {// an invalid callbackId and passes it even if no callbacks were given.callbackId = 'INVALID';} else {- throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' +- 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'- );+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + // eslint-disable-line+ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);');}// If actionArgs is not provided, default to an empty array@@ -118,120 +110,25 @@ function iOSExec () {actionArgs = massageArgsJsToNative(actionArgs);- var command = [callbackId, service, action, actionArgs];-- // Stringify and queue the command. We stringify to command now to- // effectively clone the command arguments in case they are mutated before- // the command is executed.- commandQueue.push(JSON.stringify(command));-- // If we're in the context of a stringByEvaluatingJavaScriptFromString call,- // then the queue will be flushed when it returns; no need for a poke.- // Also, if there is already a command in the queue, then we've already- // poked the native side, so there is no reason to do so again.- if (!isInContextOfEvalJs && commandQueue.length === 1) {- pokeNative();- }-}--// CB-10530-function proxyChanged () {- var cexec = cordovaExec();-- return (execProxy !== cexec && // proxy objects are different- iOSExec !== cexec // proxy object is not the current iOSExec- );-}--// CB-10106-function handleBridgeChange () {- if (proxyChanged()) {- var commandString = commandQueue.shift();- while (commandString) {- var command = JSON.parse(commandString);- var callbackId = command[0];- var service = command[1];- var action = command[2];- var actionArgs = command[3];- var callbacks = cordova.callbacks[callbackId] || {};-- execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);-- commandString = commandQueue.shift();- }- return true;- }-- return false;-}--function pokeNative () {- // CB-5488 - Don't attempt to create iframe before document.body is available.- if (!document.body) {- setTimeout(pokeNative);- return;- }-- // Check if they've removed it from the DOM, and put it back if so.- if (execIframe && execIframe.contentWindow) {- execIframe.contentWindow.location = 'gap://ready';- } else {- execIframe = document.createElement('iframe');- execIframe.style.display = 'none';- execIframe.src = 'gap://ready';- document.body.appendChild(execIframe);- }- // Use a timer to protect against iframe being unloaded during the poke (CB-7735).- // This makes the bridge ~ 7% slower, but works around the poke getting lost- // when the iframe is removed from the DOM.- // An onunload listener could be used in the case where the iframe has just been- // created, but since unload events fire only once, it doesn't work in the normal- // case of iframe reuse (where unload will have already fired due to the attempted- // navigation of the page).- failSafeTimerId = setTimeout(function () {- if (commandQueue.length) {- // CB-10106 - flush the queue on bridge change- if (!handleBridgeChange()) {- pokeNative();- }- }- }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).-}--iOSExec.nativeFetchMessages = function () {- // Stop listing for window detatch once native side confirms poke.- if (failSafeTimerId) {- clearTimeout(failSafeTimerId);- failSafeTimerId = 0;- }- // Each entry in commandQueue is a JSON string already.- if (!commandQueue.length) {- return '';- }- var json = '[' + commandQueue.join(',') + ']';- commandQueue.length = 0;- return json;+ // CB-10133 DataClone DOM Exception 25 guard (fast function remover)+ var command = [callbackId, service, action, JSON.parse(JSON.stringify(actionArgs))];+ window.webkit.messageHandlers.cordova.postMessage(command);};iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {- return iOSExec.nativeEvalAndFetch(function () {- var success = status === 0 || status === 1;- var args = convertMessageToArgsNativeToJs(message);- function nc2 () {- cordova.callbackFromNative(callbackId, success, status, args, keepCallback);- }- setTimeout(nc2, 0);+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ Promise.resolve().then(function () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback); // eslint-disable-line});};+// for backwards compatibilityiOSExec.nativeEvalAndFetch = function (func) {- // This shouldn't be nested, but better to be safe.- isInContextOfEvalJs++;try {func();- return iOSExec.nativeFetchMessages();- } finally {- isInContextOfEvalJs--;+ } catch (e) {+ console.log(e);}};diff --git a/cordova/platforms/ios/www/cordova-js-src/platform.js b/cordova/platforms/ios/www/cordova-js-src/platform.jsindex 2345fa5b7..83868c81b 100644--- a/cordova/platforms/ios/www/cordova-js-src/platform.js+++ b/cordova/platforms/ios/www/cordova-js-src/platform.js@@ -26,6 +26,14 @@ module.exports = {// see the file under plugin/ios/console.jsrequire('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');+ // Attach the wkwebkit utility to window.WkWebView+ // see the file under plugin/ios/wkwebkit.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/wkwebkit', 'window.WkWebView');++ // Attach the splashscreen utility to window.navigator.splashscreen+ // see the file under plugin/ios/launchscreen.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/launchscreen', 'navigator.splashscreen');+require('cordova/channel').onNativeReady.fire();}};diff --git a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.js b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/launchscreen.jssimilarity index 73%rename from cordova/platforms/ios/platform_www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.jsrename to cordova/platforms/ios/www/cordova-js-src/plugin/ios/launchscreen.jsindex 0dac749bd..24606969b 100644--- a/cordova/platforms/ios/platform_www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.js+++ b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/launchscreen.js@@ -1,4 +1,3 @@-cordova.define("cordova-plugin-wkwebview-engine.ios-wkwebview", function(require, exports, module) {/*** Licensed to the Apache Software Foundation (ASF) under one@@ -22,12 +21,13 @@ cordova.define("cordova-plugin-wkwebview-engine.ios-wkwebview", function(requirevar exec = require('cordova/exec');-var WkWebKit = {- allowsBackForwardNavigationGestures: function (allow) {- exec(null, null, 'CDVWKWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);+var launchscreen = {+ show: function () {+ exec(null, null, 'LaunchScreen', 'show', []);+ },+ hide: function () {+ exec(null, null, 'LaunchScreen', 'hide', []);}};-module.exports = WkWebKit;--});+module.exports = launchscreen;diff --git a/cordova/platforms/ios/www/cordova-js-src/plugin/ios/logger.js b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/logger.jsindex 7dc82e36a..6f59e1c8e 100644--- a/cordova/platforms/ios/www/cordova-js-src/plugin/ios/logger.js+++ b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/logger.js@@ -312,7 +312,6 @@ function __format (formatString, args) {}function __formatted (object, formatChar) {-try {switch (formatChar) {case 'j':diff --git a/cordova/platforms/ios/www/cordova-js-src/plugin/ios/wkwebkit.js b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/wkwebkit.jsnew file mode 100644index 000000000..35c819cf1--- /dev/null+++ b/cordova/platforms/ios/www/cordova-js-src/plugin/ios/wkwebkit.js@@ -0,0 +1,42 @@+/*+ *+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ *+*/++var exec = require('cordova/exec');++var WkWebKit = {+ allowsBackForwardNavigationGestures: function (allow) {+ exec(null, null, 'CDVWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);+ },+ convertFilePath: function (path) {+ if (!path || !window.CDV_ASSETS_URL) {+ return path;+ }+ if (path.startsWith('/')) {+ return window.CDV_ASSETS_URL + '/_app_file_' + path;+ }+ if (path.startsWith('file://')) {+ return window.CDV_ASSETS_URL + path.replace('file://', '/_app_file_');+ }+ return path;+ }+};++module.exports = WkWebKit;diff --git a/cordova/platforms/ios/www/cordova.js b/cordova/platforms/ios/www/cordova.jsindex 9813b231f..464244fed 100644--- a/cordova/platforms/ios/www/cordova.js+++ b/cordova/platforms/ios/www/cordova.js@@ -1,5 +1,5 @@// Platform: ios-// 9c79667cd175f51fd2edf2dc91ac8be98b89076a+// 538a985db128858c0a0eb4dd40fb9c8e5433fc94/*Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements. See the NOTICE file@@ -19,7 +19,7 @@under the License.*/;(function() {-var PLATFORM_VERSION_BUILD_LABEL = '5.1.1';+var PLATFORM_VERSION_BUILD_LABEL = '6.1.0';// file: src/scripts/require.jsvar require;var define;@@ -50,10 +50,10 @@ var define;require = function (id) {if (!modules[id]) {- throw 'module ' + id + ' not found';+ throw new Error('module ' + id + ' not found');} else if (id in inProgressModules) {var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;- throw 'Cycle in require graph: ' + cycle;+ throw new Error('Cycle in require graph: ' + cycle);}if (modules[id].factory) {try {@@ -70,7 +70,7 @@ var define;define = function (id, factory) {if (Object.prototype.hasOwnProperty.call(modules, id)) {- throw 'module ' + id + ' already defined';+ throw new Error('module ' + id + ' already defined');}modules[id] = {@@ -162,7 +162,7 @@ function createEvent (type, data) {event.initEvent(type, false, false);if (data) {for (var i in data) {- if (data.hasOwnProperty(i)) {+ if (Object.prototype.hasOwnProperty.call(data, i)) {event[i] = data[i];}}@@ -310,9 +310,7 @@ var cordova = {}} catch (err) {var msg = 'Error in ' + (isSuccess ? 'Success' : 'Error') + ' callbackId: ' + callbackId + ' : ' + err;- console && console.log && console.log(msg);- console && console.log && err.stack && console.log(err.stack);- cordova.fireWindowEvent('cordovacallbackerror', { 'message': msg });+ cordova.fireWindowEvent('cordovacallbackerror', { message: msg, error: err });throw err;}},@@ -340,12 +338,12 @@ var utils = require('cordova/utils');var moduleExports = module.exports;var typeMap = {- 'A': 'Array',- 'D': 'Date',- 'N': 'Number',- 'S': 'String',- 'F': 'Function',- 'O': 'Object'+ A: 'Array',+ D: 'Date',+ N: 'Number',+ S: 'String',+ F: 'Function',+ O: 'Object'};function extractParamName (callee, argIndex) {@@ -498,7 +496,7 @@ var utils = require('cordova/utils');function each (objects, func, context) {for (var prop in objects) {- if (objects.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(objects, prop)) {func.apply(context, [objects[prop], prop]);}}@@ -578,7 +576,7 @@ function include (parent, objects, clobber, merge) {*/function recursiveMerge (target, src) {for (var prop in src) {- if (src.hasOwnProperty(prop)) {+ if (Object.prototype.hasOwnProperty.call(src, prop)) {if (target.prototype && target.prototype.constructor === target) {// If the target object is a constructor override off prototype.clobber(target.prototype, prop, src[prop]);@@ -871,19 +869,13 @@ module.exports = channel;// file: ../cordova-ios/cordova-js-src/exec.jsdefine("cordova/exec", function(require, exports, module) {-/* global require, module, atob, document */-/**- * Creates a gap bridge iframe used to notify the native code about queued+ * Creates the exec bridge used to notify the native code of* commands.*/var cordova = require('cordova');var utils = require('cordova/utils');var base64 = require('cordova/base64');-var execIframe;-var commandQueue = []; // Contains pending JS->Native messages.-var isInContextOfEvalJs = 0;-var failSafeTimerId = 0;function massageArgsJsToNative (args) {if (!args || utils.typeName(args) !== 'Array') {@@ -893,8 +885,8 @@ function massageArgsJsToNative (args) {args.forEach(function (arg, i) {if (utils.typeName(arg) === 'ArrayBuffer') {ret.push({- 'CDVType': 'ArrayBuffer',- 'data': base64.fromArrayBuffer(arg)+ CDVType: 'ArrayBuffer',+ data: base64.fromArrayBuffer(arg)});} else {ret.push(arg);@@ -913,7 +905,7 @@ function massageMessageNativeToJs (message) {return ret.buffer;};var base64ToArrayBuffer = function (b64) {- return stringToArrayBuffer(atob(b64));+ return stringToArrayBuffer(atob(b64)); // eslint-disable-line no-undef};message = base64ToArrayBuffer(message.data);}@@ -922,7 +914,7 @@ function massageMessageNativeToJs (message) {function convertMessageToArgsNativeToJs (message) {var args = [];- if (!message || !message.hasOwnProperty('CDVType')) {+ if (!message || !Object.prototype.hasOwnProperty.call(message, 'CDVType')) {args.push(message);} else if (message.CDVType === 'MultiPart') {message.messages.forEach(function (e) {@@ -934,8 +926,7 @@ function convertMessageToArgsNativeToJs (message) {return args;}-function iOSExec () {-+var iOSExec = function () {var successCallback, failCallback, service, action, actionArgs;var callbackId = null;if (typeof arguments[0] !== 'string') {@@ -952,9 +943,8 @@ function iOSExec () {// an invalid callbackId and passes it even if no callbacks were given.callbackId = 'INVALID';} else {- throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' +- 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);'- );+ throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + // eslint-disable-line+ 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);');}// If actionArgs is not provided, default to an empty array@@ -970,120 +960,25 @@ function iOSExec () {actionArgs = massageArgsJsToNative(actionArgs);- var command = [callbackId, service, action, actionArgs];-- // Stringify and queue the command. We stringify to command now to- // effectively clone the command arguments in case they are mutated before- // the command is executed.- commandQueue.push(JSON.stringify(command));-- // If we're in the context of a stringByEvaluatingJavaScriptFromString call,- // then the queue will be flushed when it returns; no need for a poke.- // Also, if there is already a command in the queue, then we've already- // poked the native side, so there is no reason to do so again.- if (!isInContextOfEvalJs && commandQueue.length === 1) {- pokeNative();- }-}--// CB-10530-function proxyChanged () {- var cexec = cordovaExec();-- return (execProxy !== cexec && // proxy objects are different- iOSExec !== cexec // proxy object is not the current iOSExec- );-}--// CB-10106-function handleBridgeChange () {- if (proxyChanged()) {- var commandString = commandQueue.shift();- while (commandString) {- var command = JSON.parse(commandString);- var callbackId = command[0];- var service = command[1];- var action = command[2];- var actionArgs = command[3];- var callbacks = cordova.callbacks[callbackId] || {};-- execProxy(callbacks.success, callbacks.fail, service, action, actionArgs);-- commandString = commandQueue.shift();- }- return true;- }-- return false;-}--function pokeNative () {- // CB-5488 - Don't attempt to create iframe before document.body is available.- if (!document.body) {- setTimeout(pokeNative);- return;- }-- // Check if they've removed it from the DOM, and put it back if so.- if (execIframe && execIframe.contentWindow) {- execIframe.contentWindow.location = 'gap://ready';- } else {- execIframe = document.createElement('iframe');- execIframe.style.display = 'none';- execIframe.src = 'gap://ready';- document.body.appendChild(execIframe);- }- // Use a timer to protect against iframe being unloaded during the poke (CB-7735).- // This makes the bridge ~ 7% slower, but works around the poke getting lost- // when the iframe is removed from the DOM.- // An onunload listener could be used in the case where the iframe has just been- // created, but since unload events fire only once, it doesn't work in the normal- // case of iframe reuse (where unload will have already fired due to the attempted- // navigation of the page).- failSafeTimerId = setTimeout(function () {- if (commandQueue.length) {- // CB-10106 - flush the queue on bridge change- if (!handleBridgeChange()) {- pokeNative();- }- }- }, 50); // Making this > 0 improves performance (marginally) in the normal case (where it doesn't fire).-}--iOSExec.nativeFetchMessages = function () {- // Stop listing for window detatch once native side confirms poke.- if (failSafeTimerId) {- clearTimeout(failSafeTimerId);- failSafeTimerId = 0;- }- // Each entry in commandQueue is a JSON string already.- if (!commandQueue.length) {- return '';- }- var json = '[' + commandQueue.join(',') + ']';- commandQueue.length = 0;- return json;+ // CB-10133 DataClone DOM Exception 25 guard (fast function remover)+ var command = [callbackId, service, action, JSON.parse(JSON.stringify(actionArgs))];+ window.webkit.messageHandlers.cordova.postMessage(command);};iOSExec.nativeCallback = function (callbackId, status, message, keepCallback, debug) {- return iOSExec.nativeEvalAndFetch(function () {- var success = status === 0 || status === 1;- var args = convertMessageToArgsNativeToJs(message);- function nc2 () {- cordova.callbackFromNative(callbackId, success, status, args, keepCallback);- }- setTimeout(nc2, 0);+ var success = status === 0 || status === 1;+ var args = convertMessageToArgsNativeToJs(message);+ Promise.resolve().then(function () {+ cordova.callbackFromNative(callbackId, success, status, args, keepCallback); // eslint-disable-line});};+// for backwards compatibilityiOSExec.nativeEvalAndFetch = function (func) {- // This shouldn't be nested, but better to be safe.- isInContextOfEvalJs++;try {func();- return iOSExec.nativeFetchMessages();- } finally {- isInContextOfEvalJs--;+ } catch (e) {+ console.log(e);}};@@ -1153,7 +1048,6 @@ var cordova = require('cordova');var modulemapper = require('cordova/modulemapper');var platform = require('cordova/platform');var pluginloader = require('cordova/pluginloader');-var utils = require('cordova/utils');var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady];@@ -1173,34 +1067,6 @@ window.setTimeout(function () {}}, 5000);-// Replace navigator before any modules are required(), to ensure it happens as soon as possible.-// We replace it so that properties that can't be clobbered can instead be overridden.-function replaceNavigator (origNavigator) {- var CordovaNavigator = function () {};- CordovaNavigator.prototype = origNavigator;- var newNavigator = new CordovaNavigator();- // This work-around really only applies to new APIs that are newer than Function.bind.- // Without it, APIs such as getGamepads() break.- if (CordovaNavigator.bind) {- for (var key in origNavigator) {- if (typeof origNavigator[key] === 'function') {- newNavigator[key] = origNavigator[key].bind(origNavigator);- } else {- (function (k) {- utils.defineGetterSetter(newNavigator, key, function () {- return origNavigator[k];- });- })(key);- }- }- }- return newNavigator;-}--if (window.navigator) {- window.navigator = replaceNavigator(window.navigator);-}-if (!window.console) {window.console = {log: function () {}@@ -1266,7 +1132,6 @@ channel.join(function () {channel.join(function () {require('cordova').fireDocumentEvent('deviceready');}, channel.deviceReadyChannelsArray);-}, platformInitChannelsArray);});@@ -1378,6 +1243,14 @@ module.exports = {// see the file under plugin/ios/console.jsrequire('cordova/modulemapper').clobbers('cordova/plugin/ios/console', 'window.console');+ // Attach the wkwebkit utility to window.WkWebView+ // see the file under plugin/ios/wkwebkit.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/wkwebkit', 'window.WkWebView');++ // Attach the splashscreen utility to window.navigator.splashscreen+ // see the file under plugin/ios/launchscreen.js+ require('cordova/modulemapper').clobbers('cordova/plugin/ios/launchscreen', 'navigator.splashscreen');+require('cordova/channel').onNativeReady.fire();}};@@ -1555,6 +1428,24 @@ for (var key in console) {});+// file: ../cordova-ios/cordova-js-src/plugin/ios/launchscreen.js+define("cordova/plugin/ios/launchscreen", function(require, exports, module) {++var exec = require('cordova/exec');++var launchscreen = {+ show: function () {+ exec(null, null, 'LaunchScreen', 'show', []);+ },+ hide: function () {+ exec(null, null, 'LaunchScreen', 'hide', []);+ }+};++module.exports = launchscreen;++});+// file: ../cordova-ios/cordova-js-src/plugin/ios/logger.jsdefine("cordova/plugin/ios/logger", function(require, exports, module) {@@ -1851,7 +1742,6 @@ function __format (formatString, args) {}function __formatted (object, formatChar) {-try {switch (formatChar) {case 'j':@@ -1889,6 +1779,33 @@ document.addEventListener('deviceready', logger.__onDeviceReady, false);});+// file: ../cordova-ios/cordova-js-src/plugin/ios/wkwebkit.js+define("cordova/plugin/ios/wkwebkit", function(require, exports, module) {++var exec = require('cordova/exec');++var WkWebKit = {+ allowsBackForwardNavigationGestures: function (allow) {+ exec(null, null, 'CDVWebViewEngine', 'allowsBackForwardNavigationGestures', [allow]);+ },+ convertFilePath: function (path) {+ if (!path || !window.CDV_ASSETS_URL) {+ return path;+ }+ if (path.startsWith('/')) {+ return window.CDV_ASSETS_URL + '/_app_file_' + path;+ }+ if (path.startsWith('file://')) {+ return window.CDV_ASSETS_URL + path.replace('file://', '/_app_file_');+ }+ return path;+ }+};++module.exports = WkWebKit;++});+// file: src/common/pluginloader.jsdefine("cordova/pluginloader", function(require, exports, module) {@@ -2160,7 +2077,6 @@ utils.extend = (function () {var F = function () {};// extend Child from Parentreturn function (Child, Parent) {-F.prototype = Parent.prototype;Child.prototype = new F();Child.__super__ = Parent.prototype;diff --git a/cordova/platforms/ios/www/cordova_plugins.js b/cordova/platforms/ios/www/cordova_plugins.jsindex 023731eb1..ae4704a8a 100644--- a/cordova/platforms/ios/www/cordova_plugins.js+++ b/cordova/platforms/ios/www/cordova_plugins.js@@ -231,20 +231,50 @@ cordova.define('cordova/plugin_list', function(require, exports, module) {]},{- "id": "cordova-plugin-wkwebview-engine.ios-wkwebview-exec",- "file": "plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.js",- "pluginId": "cordova-plugin-wkwebview-engine",+ "id": "com.whebcraft.cordova.plugin.downloader.Downloader",+ "file": "plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js",+ "pluginId": "com.whebcraft.cordova.plugin.downloader","clobbers": [- "cordova.exec"+ "plugins.Downloader"]},{- "id": "cordova-plugin-wkwebview-engine.ios-wkwebview",- "file": "plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview.js",- "pluginId": "cordova-plugin-wkwebview-engine",+ "id": "es6-promise-plugin.Promise",+ "file": "plugins/es6-promise-plugin/www/promise.js",+ "pluginId": "es6-promise-plugin",+ "runs": true+ },+ {+ "id": "cordova-plugin-x-socialsharing.SocialSharing",+ "file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",+ "pluginId": "cordova-plugin-x-socialsharing","clobbers": [- "window.WkWebView"+ "window.plugins.socialsharing"]+ },+ {+ "id": "cordova-plugin-ios-xhr.formdata-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.xhr-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.fetch-bootstrap",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true+ },+ {+ "id": "cordova-plugin-ios-xhr.fetch-polyfill",+ "file": "plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.js",+ "pluginId": "cordova-plugin-ios-xhr",+ "runs": true}];module.exports.metadata = {@@ -254,6 +284,9 @@ cordova.define('cordova/plugin_list', function(require, exports, module) {"cordova-plugin-file": "6.0.2","cordova-plugin-file-opener2": "3.0.4","cordova-plugin-whitelist": "1.3.4",- "cordova-plugin-wkwebview-engine": "1.2.1"+ "com.whebcraft.cordova.plugin.downloader": "0.1.0",+ "es6-promise-plugin": "4.2.2",+ "cordova-plugin-x-socialsharing": "5.6.8",+ "cordova-plugin-ios-xhr": "1.0.0"};-});\ No newline at end of file+});diff --git a/cordova/platforms/ios/www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js b/cordova/platforms/ios/www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.jsnew file mode 100644index 000000000..b8dad0882--- /dev/null+++ b/cordova/platforms/ios/www/plugins/com.whebcraft.cordova.plugin.downloader/www/Downloader.js@@ -0,0 +1,25 @@+cordova.define("com.whebcraft.cordova.plugin.downloader.Downloader", function(require, exports, module) {+var Downloader = {+ download: function (arguments, successCallback, errorCallback) {+ cordova.exec(+ successCallback,+ errorCallback,+ 'Downloader',+ 'download',+ [arguments]+ );+ }+};++function install() {+ if (!window.plugins) {+ window.plugins = {};+ }++ window.plugins.Downloader = Downloader;+ return window.plugins.Downloader;+};++cordova.addConstructor(install);++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.js b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.jsnew file mode 100644index 000000000..79dbf5c89--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/fetch-bootstrap.js@@ -0,0 +1,10 @@+cordova.define("cordova-plugin-ios-xhr.fetch-bootstrap", function(require, exports, module) {+'use strict';++(function ()+{+ var _fetch = window.fetch;+ window.fetch = undefined;+})();++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.js b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.jsnew file mode 100644index 000000000..3db9ffdc7--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/formdata-polyfill.js@@ -0,0 +1,365 @@+cordova.define("cordova-plugin-ios-xhr.formdata-polyfill", function(require, exports, module) {+/*+ * Copyright (c) 2018 Oracle and/or its affiliates.+ *+ * The Universal Permissive License (UPL), Version 1.0+ *+ * Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this+ * software, associated documentation and/or data (collectively the "Software"), free of charge and under any and+ * all copyright rights in the Software, and any and all patent rights owned or freely licensable by each+ * licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor,+ * or (ii) the Larger Works (as defined below), to deal in both+ *+ *+ * (a) the Software, and+ *+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software+ * (each a “Larger Work” to which the Software is contributed by such licensors),+ *+ * without restriction, including without limitation the rights to copy, create derivative works of, display,+ * perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and+ * have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other+ * terms.+ *+ * This license is subject to the following condition:+ *+ * The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL+ * must be included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ * DEALINGS IN THE SOFTWARE.+ */++/*+ * Native Safari FormData only implements the append method. This polyfill is used in+ * tandem with the xhr-polyfill.+ *+ * Two additional functions in this FormData implementation:+ * 1) __getNative - returns the native Safari FormData object.+ * 2) __getRequestParts - returns a promise resolving an object {contentType:string, body:string}.+ */+'use strict';+(function ()+{+ function __FormData(formElement)+ {+ this._map = new Map();++ if (!HTMLFormElement.prototype.isPrototypeOf(formElement))+ return;++ var elements = formElement.elements;+ for (var i = 0; i < elements.length; i++)+ {+ var element = elements[i];++ var name = element.name ? element.name : element.id;+ if (!name)+ continue;++ if (element.type === 'file')+ {+ for (var file of element.files)+ this.append(name, file);+ }+ else if (['select-multiple', 'select-one'].indexOf(element.value) > -1)+ {+ for (var option of element.selectedOptions)+ this.append(name, option);+ }+ else if (['checkbox', 'radio'].indexOf(element.value) > -1 && element.checked)+ {+ this.append(name, element.value);+ }+ else+ {+ this.append(name, element.value);+ }+ }+ }++ if( 'Symbol' in window && typeof Symbol() === 'symbol'){+ Object.defineProperty( __FormData.prototype, Symbol.toStringTag, {+ get : function(){+ return 'FormData';+ }+ });+ }++ __FormData.prototype.get = function (name)+ {+ var values = this.getAll(name);++ if (values && values.length > 0)+ return values[0];+ else+ return undefined;+ };++ __FormData.prototype.getAll = function (name)+ {+ var map = this._map;+ var values = map.get(name);+ if (!values)+ values = [];++ return values;+ };++ __FormData.prototype.set = function (name, value, filename)+ {+ var map = this._map;++ if (value && Blob.prototype.isPrototypeOf(value))+ {+ if (!filename)+ filename = "Blob";++ Object.defineProperty(value, "name", {value: filename});+ }++ map.set(name, [value]);+ };+++ __FormData.prototype.append = function (name, value, filename)+ {+ var map = this._map;+ var values = map.get(name);++ this.set(name, value, filename);+ if (values)+ {+ values.push(map.get(name)[0]);+ map.set(name, values);+ }+ };++ __FormData.prototype.delete = function (name)+ {+ var map = this._map;+ map.delete(name);+ };++ __FormData.prototype.has = function (name)+ {+ var map = this._map;+ return map.has(name);+ };++ __FormData.prototype.keys = function ()+ {+ var map = this._map;+ return map.keys();+ };++ __FormData.prototype.values = function ()+ {+ var map = this._map;+ var allvalues = [];++ var vit = map.values();+ var entry = vit.next();+ while (entry && !entry.done)+ {+ var values = entry.value;+ for (var i = 0; i < values.length; i++)+ allvalues.push(values[i]);++ entry = vit.next();+ }++ return __FormData._makeIterator(allvalues);+ };++ __FormData.prototype.entries = function ()+ {+ var map = this._map;+ var allentries = [];++ for (var key of map.keys())+ {+ var values = map.get(key);+ for (var i = 0; i < values.length; i++)+ {+ allentries.push([key, values[i]]);+ }+ }++ return __FormData._makeIterator(allentries);+ };++ __FormData.prototype.forEach = function(callback)+ {+ var eit = this.entries();+ var entry = eit.next();+ while(!entry.done)+ {+ callback.call(this, entry.value[1], entry.value[0], this);+ entry = eit.next();+ }+ };++ __FormData.prototype.toString = function ()+ {+ return "[object FormData]";+ };++ __FormData.prototype.__getRequestParts = function ()+ {+ var promise = new Promise(function (resolve)+ {+ __FormData._getRequestValues(this.entries()).then(function (entries)+ {+ var parts = __FormData._getMultipartRequest(entries);++ resolve(parts);+ });+ }.bind(this));++ return promise;+ };++ __FormData.prototype.__getNative = function ()+ {+ var fd = new window._FormData();+ var eit = this.entries();+ var entry = eit.next();+ while (!entry.done)+ {+ if (entry.value[1] && Blob.prototype.isPrototypeOf(entry.value[1]))+ fd.append(entry.value[0], entry.value[1], entry.value[1].name);+ else+ fd.append(entry.value[0], entry.value[1]);++ entry = eit.next();+ }++ return fd;+ };++ __FormData._getMultipartRequest = function (entries)+ {+ var boundary = "----cordovaPluginWkwebviewFileXhrFormdata" + Math.random().toString(32);+ var parts = {"contentType": "multipart/form-data; boundary=" + boundary, body: ""};+ var bodyEntries = [];++ for (var i = 0; i < entries.length; i++)+ {+ var entry = entries[i];+ for (var data of __FormData._generateMultipartFormData(entry, boundary))+ bodyEntries.push(data);+ }++ bodyEntries.push("--" + boundary + "--");+ parts.body = new Blob(bodyEntries, {type: "application/octet-stream"});++ return parts;+ };++ __FormData._makeIterator = function (array)+ {+ var i = 0;+ return {+ next: function ()+ {+ if (i < array.length)+ return {done: false, value: array[i++]};+ else+ return {done: true, value: undefined};+ }+ };+ };++ __FormData._getRequestValues = function (entriesIterator)+ {+ var promises = [];+ var entry = entriesIterator.next();+ while (!entry.done)+ {+ promises.push(__FormData._normalizeEntry(entry));+ entry = entriesIterator.next();+ }++ return Promise.all(promises);+ };++ __FormData._normalizeEntry = function (entry)+ {+ var promise = new Promise(function (resolve)+ {++ var name = entry.value[0];+ var value = entry.value[1];++ if (value &&+ (Blob.prototype.isPrototypeOf(value) ||+ File.prototype.isPrototypeOf(value)))+ {++ var filename = value.name;+ var type = value.type ? value.type : "application/octet-binary;";+ var reader = new FileReader();+ var resolve;++ reader.onload = function ()+ {+ resolve({name: name, value: reader.result, filename: filename, type: type});+ };++ reader.onerror = function ()+ {+ resolve({name: name, value: reader.error, filename: filename, type: type});+ };++ reader.readAsArrayBuffer(value);+ }+ else+ {+ promise = resolve({name: name, value: value});+ }+ });++ return promise;+ };++ __FormData._generateMultipartFormData = function (entry, boundary)+ {+ var data = [];++ data.push("--" + boundary + "\r\n");+ if (!entry['filename'])+ {+ data.push('content-disposition: form-data; name="');+ data.push(entry.name);+ data.push('"\r\n');+ data.push('\r\n');+ data.push(entry.value);+ data.push("\r\n");+ }+ else+ {+ // Describe it as form data+ data.push('content-disposition: form-data; name="');+ data.push(entry.name)+ data.push('"; filename="');+ data.push(entry.filename);+ data.push('"\r\n');+ data.push('Content-Type: ');+ data.push(entry.type);+ data.push('\r\n\r\n');+ data.push(entry.value);+ data.push('\r\n');+ }++ return data;+ };++ window._FormData = window.FormData;+ window.FormData = __FormData;+})();++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.js b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.jsnew file mode 100644index 000000000..7b5fce803--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/whatwg-fetch-2.0.3.js@@ -0,0 +1,464 @@+cordova.define("cordova-plugin-ios-xhr.fetch-polyfill", function(require, exports, module) {+(function(self) {+ 'use strict';++ if (self.fetch) {+ return+ }++ var support = {+ searchParams: 'URLSearchParams' in self,+ iterable: 'Symbol' in self && 'iterator' in Symbol,+ blob: 'FileReader' in self && 'Blob' in self && (function() {+ try {+ new Blob()+ return true+ } catch(e) {+ return false+ }+ })(),+ formData: 'FormData' in self,+ arrayBuffer: 'ArrayBuffer' in self+ }++ if (support.arrayBuffer) {+ var viewClasses = [+ '[object Int8Array]',+ '[object Uint8Array]',+ '[object Uint8ClampedArray]',+ '[object Int16Array]',+ '[object Uint16Array]',+ '[object Int32Array]',+ '[object Uint32Array]',+ '[object Float32Array]',+ '[object Float64Array]'+ ]++ var isDataView = function(obj) {+ return obj && DataView.prototype.isPrototypeOf(obj)+ }++ var isArrayBufferView = ArrayBuffer.isView || function(obj) {+ return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1+ }+ }++ function normalizeName(name) {+ if (typeof name !== 'string') {+ name = String(name)+ }+ if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {+ throw new TypeError('Invalid character in header field name')+ }+ return name.toLowerCase()+ }++ function normalizeValue(value) {+ if (typeof value !== 'string') {+ value = String(value)+ }+ return value+ }++ // Build a destructive iterator for the value list+ function iteratorFor(items) {+ var iterator = {+ next: function() {+ var value = items.shift()+ return {done: value === undefined, value: value}+ }+ }++ if (support.iterable) {+ iterator[Symbol.iterator] = function() {+ return iterator+ }+ }++ return iterator+ }++ function Headers(headers) {+ this.map = {}++ if (headers instanceof Headers) {+ headers.forEach(function(value, name) {+ this.append(name, value)+ }, this)+ } else if (Array.isArray(headers)) {+ headers.forEach(function(header) {+ this.append(header[0], header[1])+ }, this)+ } else if (headers) {+ Object.getOwnPropertyNames(headers).forEach(function(name) {+ this.append(name, headers[name])+ }, this)+ }+ }++ Headers.prototype.append = function(name, value) {+ name = normalizeName(name)+ value = normalizeValue(value)+ var oldValue = this.map[name]+ this.map[name] = oldValue ? oldValue+','+value : value+ }++ Headers.prototype['delete'] = function(name) {+ delete this.map[normalizeName(name)]+ }++ Headers.prototype.get = function(name) {+ name = normalizeName(name)+ return this.has(name) ? this.map[name] : null+ }++ Headers.prototype.has = function(name) {+ return this.map.hasOwnProperty(normalizeName(name))+ }++ Headers.prototype.set = function(name, value) {+ this.map[normalizeName(name)] = normalizeValue(value)+ }++ Headers.prototype.forEach = function(callback, thisArg) {+ for (var name in this.map) {+ if (this.map.hasOwnProperty(name)) {+ callback.call(thisArg, this.map[name], name, this)+ }+ }+ }++ Headers.prototype.keys = function() {+ var items = []+ this.forEach(function(value, name) { items.push(name) })+ return iteratorFor(items)+ }++ Headers.prototype.values = function() {+ var items = []+ this.forEach(function(value) { items.push(value) })+ return iteratorFor(items)+ }++ Headers.prototype.entries = function() {+ var items = []+ this.forEach(function(value, name) { items.push([name, value]) })+ return iteratorFor(items)+ }++ if (support.iterable) {+ Headers.prototype[Symbol.iterator] = Headers.prototype.entries+ }++ function consumed(body) {+ if (body.bodyUsed) {+ return Promise.reject(new TypeError('Already read'))+ }+ body.bodyUsed = true+ }++ function fileReaderReady(reader) {+ return new Promise(function(resolve, reject) {+ reader.onload = function() {+ resolve(reader.result)+ }+ reader.onerror = function() {+ reject(reader.error)+ }+ })+ }++ function readBlobAsArrayBuffer(blob) {+ var reader = new FileReader()+ var promise = fileReaderReady(reader)+ reader.readAsArrayBuffer(blob)+ return promise+ }++ function readBlobAsText(blob) {+ var reader = new FileReader()+ var promise = fileReaderReady(reader)+ reader.readAsText(blob)+ return promise+ }++ function readArrayBufferAsText(buf) {+ var view = new Uint8Array(buf)+ var chars = new Array(view.length)++ for (var i = 0; i < view.length; i++) {+ chars[i] = String.fromCharCode(view[i])+ }+ return chars.join('')+ }++ function bufferClone(buf) {+ if (buf.slice) {+ return buf.slice(0)+ } else {+ var view = new Uint8Array(buf.byteLength)+ view.set(new Uint8Array(buf))+ return view.buffer+ }+ }++ function Body() {+ this.bodyUsed = false++ this._initBody = function(body) {+ this._bodyInit = body+ if (!body) {+ this._bodyText = ''+ } else if (typeof body === 'string') {+ this._bodyText = body+ } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {+ this._bodyBlob = body+ } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {+ this._bodyFormData = body+ } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {+ this._bodyText = body.toString()+ } else if (support.arrayBuffer && support.blob && isDataView(body)) {+ this._bodyArrayBuffer = bufferClone(body.buffer)+ // IE 10-11 can't handle a DataView body.+ this._bodyInit = new Blob([this._bodyArrayBuffer])+ } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {+ this._bodyArrayBuffer = bufferClone(body)+ } else {+ throw new Error('unsupported BodyInit type')+ }++ if (!this.headers.get('content-type')) {+ if (typeof body === 'string') {+ this.headers.set('content-type', 'text/plain;charset=UTF-8')+ } else if (this._bodyBlob && this._bodyBlob.type) {+ this.headers.set('content-type', this._bodyBlob.type)+ } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {+ this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')+ }+ }+ }++ if (support.blob) {+ this.blob = function() {+ var rejected = consumed(this)+ if (rejected) {+ return rejected+ }++ if (this._bodyBlob) {+ return Promise.resolve(this._bodyBlob)+ } else if (this._bodyArrayBuffer) {+ return Promise.resolve(new Blob([this._bodyArrayBuffer]))+ } else if (this._bodyFormData) {+ throw new Error('could not read FormData body as blob')+ } else {+ return Promise.resolve(new Blob([this._bodyText]))+ }+ }++ this.arrayBuffer = function() {+ if (this._bodyArrayBuffer) {+ return consumed(this) || Promise.resolve(this._bodyArrayBuffer)+ } else {+ return this.blob().then(readBlobAsArrayBuffer)+ }+ }+ }++ this.text = function() {+ var rejected = consumed(this)+ if (rejected) {+ return rejected+ }++ if (this._bodyBlob) {+ return readBlobAsText(this._bodyBlob)+ } else if (this._bodyArrayBuffer) {+ return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))+ } else if (this._bodyFormData) {+ throw new Error('could not read FormData body as text')+ } else {+ return Promise.resolve(this._bodyText)+ }+ }++ if (support.formData) {+ this.formData = function() {+ return this.text().then(decode)+ }+ }++ this.json = function() {+ return this.text().then(JSON.parse)+ }++ return this+ }++ // HTTP methods whose capitalization should be normalized+ var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']++ function normalizeMethod(method) {+ var upcased = method.toUpperCase()+ return (methods.indexOf(upcased) > -1) ? upcased : method+ }++ function Request(input, options) {+ options = options || {}+ var body = options.body++ if (input instanceof Request) {+ if (input.bodyUsed) {+ throw new TypeError('Already read')+ }+ this.url = input.url+ this.credentials = input.credentials+ if (!options.headers) {+ this.headers = new Headers(input.headers)+ }+ this.method = input.method+ this.mode = input.mode+ if (!body && input._bodyInit != null) {+ body = input._bodyInit+ input.bodyUsed = true+ }+ } else {+ this.url = String(input)+ }++ this.credentials = options.credentials || this.credentials || 'omit'+ if (options.headers || !this.headers) {+ this.headers = new Headers(options.headers)+ }+ this.method = normalizeMethod(options.method || this.method || 'GET')+ this.mode = options.mode || this.mode || null+ this.referrer = null++ if ((this.method === 'GET' || this.method === 'HEAD') && body) {+ throw new TypeError('Body not allowed for GET or HEAD requests')+ }+ this._initBody(body)+ }++ Request.prototype.clone = function() {+ return new Request(this, { body: this._bodyInit })+ }++ function decode(body) {+ var form = new FormData()+ body.trim().split('&').forEach(function(bytes) {+ if (bytes) {+ var split = bytes.split('=')+ var name = split.shift().replace(/\+/g, ' ')+ var value = split.join('=').replace(/\+/g, ' ')+ form.append(decodeURIComponent(name), decodeURIComponent(value))+ }+ })+ return form+ }++ function parseHeaders(rawHeaders) {+ var headers = new Headers()+ rawHeaders.split(/\r?\n/).forEach(function(line) {+ var parts = line.split(':')+ var key = parts.shift().trim()+ if (key) {+ var value = parts.join(':').trim()+ headers.append(key, value)+ }+ })+ return headers+ }++ Body.call(Request.prototype)++ function Response(bodyInit, options) {+ if (!options) {+ options = {}+ }++ this.type = 'default'+ this.status = 'status' in options ? options.status : 200+ this.ok = this.status >= 200 && this.status < 300+ this.statusText = 'statusText' in options ? options.statusText : 'OK'+ this.headers = new Headers(options.headers)+ this.url = options.url || ''+ this._initBody(bodyInit)+ }++ Body.call(Response.prototype)++ Response.prototype.clone = function() {+ return new Response(this._bodyInit, {+ status: this.status,+ statusText: this.statusText,+ headers: new Headers(this.headers),+ url: this.url+ })+ }++ Response.error = function() {+ var response = new Response(null, {status: 0, statusText: ''})+ response.type = 'error'+ return response+ }++ var redirectStatuses = [301, 302, 303, 307, 308]++ Response.redirect = function(url, status) {+ if (redirectStatuses.indexOf(status) === -1) {+ throw new RangeError('Invalid status code')+ }++ return new Response(null, {status: status, headers: {location: url}})+ }++ self.Headers = Headers+ self.Request = Request+ self.Response = Response++ self.fetch = function(input, init) {+ return new Promise(function(resolve, reject) {+ var request = new Request(input, init)+ var xhr = new XMLHttpRequest()++ xhr.onload = function() {+ var options = {+ status: xhr.status,+ statusText: xhr.statusText,+ headers: parseHeaders(xhr.getAllResponseHeaders() || '')+ }+ options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')+ var body = 'response' in xhr ? xhr.response : xhr.responseText+ resolve(new Response(body, options))+ }++ xhr.onerror = function() {+ reject(new TypeError('Network request failed'))+ }++ xhr.ontimeout = function() {+ reject(new TypeError('Network request failed'))+ }++ xhr.open(request.method, request.url, true)++ if (request.credentials === 'include') {+ xhr.withCredentials = true+ }++ if ('responseType' in xhr && support.blob) {+ xhr.responseType = 'blob'+ }++ request.headers.forEach(function(value, name) {+ xhr.setRequestHeader(name, value)+ })++ xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)+ })+ }+ self.fetch.polyfill = true+})(typeof self !== 'undefined' ? self : this);++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.js b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.jsnew file mode 100644index 000000000..4ba7a4269--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-ios-xhr/src/www/ios/xhr-polyfill.js@@ -0,0 +1,1249 @@+cordova.define("cordova-plugin-ios-xhr.xhr-polyfill", function(require, exports, module) {+/*+ * Copyright (c) 2018 Oracle and/or its affiliates.+ *+ * The Universal Permissive License (UPL), Version 1.0+ *+ * Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this+ * software, associated documentation and/or data (collectively the "Software"), free of charge and under any and+ * all copyright rights in the Software, and any and all patent rights owned or freely licensable by each+ * licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor,+ * or (ii) the Larger Works (as defined below), to deal in both+ *+ *+ * (a) the Software, and+ *+ * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software+ * (each a “Larger Work” to which the Software is contributed by such licensors),+ *+ * without restriction, including without limitation the rights to copy, create derivative works of, display,+ * perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and+ * have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other+ * terms.+ *+ * This license is subject to the following condition:+ *+ * The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL+ * must be included in all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+ * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+ * DEALINGS IN THE SOFTWARE.+ */+'use strict';+(function ()+{+++ var exec = require('cordova/exec');++ // Handles native file:// XHR GET requests+ function FileHandler(reqContext, config)+ {+ this._reqContext = reqContext;+ this._config = config;+ }++ FileHandler._getMimeType = function (reqContext)+ {+ if (reqContext.overrideMimeType)+ return reqContext.overrideMimeType;+ else if (reqContext.responseHeaders['content-type'])+ return reqContext.responseHeaders['content-type'];++ var url = reqContext.url;+ var ext = url.substr(url.lastIndexOf('.'));+ return FileHandler._EXT_TO_MIME[ext] ? FileHandler._EXT_TO_MIME[ext] : "";+ };++ FileHandler.getHandlerForResponseType = function (reqContext)+ {+ var responseType = reqContext.responseType;+ if (FileHandler._RESPONSE_HANDLERS[responseType])+ return FileHandler._RESPONSE_HANDLERS[responseType];+ else+ return FileHandler._RESPONSE_HANDLERS["text"];+ };++ FileHandler._EXT_TO_MIME = {+ ".img": "image/jpeg",+ ".png": "image/png",+ ".gif": "image/gif",+ ".xml": "application/xml",+ ".xsl": "application/xml",+ ".html": "text/html",+ ".htm": "text/html",+ ".svg": "image/svg+xml",+ ".svgz": "image/svg+xml",+ ".json": "application/json",+ ".js": "application/javascript"+ };++ FileHandler._RESPONSE_HANDLERS =+ {+ "text":+ {+ action: "readAsText",+ properties: ["response", "responseText"],+ convert: function (mimeType, r)+ {+ this._size = r["length"];+ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "arraybuffer":+ {+ action: "readAsArrayBuffer",+ properties: ["response"],+ convert: function (mimeType, r)+ {+ this._size = r["byteLength"];+ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "json":+ {+ action: "readAsText",+ properties: ["response"],+ convert: function (mimeType, r)+ {+ this._size = r["length"];+ try+ {+ r = JSON.parse(r);+ }+ catch (e)+ {+ }++ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "document":+ {+ action: "readAsText",+ properties: ["response", "responseXML"],+ convert: function (mimeType, r)+ {+ this._size = r["length"];+ try+ {+ r = new DOMParser().parseFromString(r, "text/xml");+ }+ catch (e)+ {+ }+ return r;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ },+ "blob":+ {+ action: "readAsArrayBuffer",+ properties: ["response"],+ convert: function (mimeType, r)+ {+ var blob = new Blob([r], {"type": mimeType});+ this._size = blob.size;+ return blob;+ },+ responseSize: function ()+ {+ return isNaN(this._size) ? 0 : this._size;+ }+ }+ };++ FileHandler.prototype._isTraceLoggingEnabled = function ()+ {+ return this._config["NativeXHRLogging"] === "full";+ };++ FileHandler._presend = function (reqContext)+ {+ reqContext.dispatchReadyStateChangeEvent(1); // OPEN+ reqContext.dispatchProgressEvent("loadstart");+ // no upload events for a GET+ };++ FileHandler._error = function (reqContext, e)+ {+ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native file XHR Response: Unable to find file %o\n%o", reqContext.url, e);++ reqContext.status = 404;+ reqContext.responseText = "File Not Found";++ reqContext.dispatchReadyStateChangeEvent(2); // HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); // LOADING+ reqContext.dispatchProgressEvent("progress");++ reqContext.dispatchReadyStateChangeEvent(4); // DONE+ reqContext.dispatchProgressEvent("error");+ reqContext.dispatchProgressEvent("loadend");+ };++ FileHandler._success = function (reqContext, rspTypeHandler, result)+ {+ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native file XHR Response:\n%o\n", reqContext.url, result);++ var mimeType = FileHandler._getMimeType(reqContext);+ var convertedResult = rspTypeHandler.convert(mimeType, result);++ var respSize = rspTypeHandler.responseSize();+ for (var i = 0; i < rspTypeHandler.properties.length; i++)+ reqContext[rspTypeHandler.properties[i]] = convertedResult;++ reqContext.status = 200;+ reqContext.statusText = "OK";+ reqContext.responseURL = reqContext.url;++ reqContext.dispatchReadyStateChangeEvent(2); // HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); // LOADING+ reqContext.dispatchProgressEvent("progress", respSize);+ reqContext.dispatchReadyStateChangeEvent(4); // DONE+ reqContext.dispatchProgressEvent("load", respSize);+ reqContext.dispatchProgressEvent("loadend", respSize);+ };++ FileHandler.prototype.send = function ()+ {+ var reqContext = this._reqContext;+ var rspTypeHandler = FileHandler.getHandlerForResponseType(reqContext);++ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native file XHR Request:\n%o", reqContext.url);++ FileHandler._presend(reqContext);++ exec(FileHandler._success.bind(this, reqContext, rspTypeHandler),+ FileHandler._error.bind(this, reqContext),+ "CDVWKWebViewFileXhr", rspTypeHandler.action, [reqContext.url]);+ };++ // handles http and https native XHR requests+ function HttpHandler(reqContext, config)+ {+ this._reqContext = reqContext;+ this._config = config;+ }++ HttpHandler._generateId = function ()+ {+ return [performance.now().toString(16), Math.random().toString(16)].join("-"); // FortifyFalsePositive+ };++ HttpHandler._convertTextToBinaryBase64String = function(mimeType, text)+ {+ var blob = new Blob([text], {type: mimeType});+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };+ });++ reader.readAsBinaryString(blob);++ return promise;+ };++ HttpHandler._REQUEST_HANDLERS =+ {+ "": {+ convert: function (reqContext)+ {+ return Promise.resolve(null);+ }+ },+ "ArrayBuffer": {+ convert: function (reqContext)+ {+ var body = reqContext.requestData;++ var type = reqContext.requestHeaders['content-type'];+ if (!type)+ type = reqContext.requestHeaders['content-type'] = "application/octet-binary;";++ var blob = new Blob([body], {type: type});+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };+ });++ reader.readAsBinaryString(blob);++ return promise;+ }+ },+ "FormData": {+ convert: function (reqContext)+ {+ var body = reqContext.requestData;+ var promise = new Promise(function (resolve, reject)+ {+ var contentType = reqContext.requestHeaders["content-type"];++ // FormData polyfill - request the body and context-type+ body.__getRequestParts().then(function (parts)+ {+ if (!contentType)+ reqContext.requestHeaders["content-type"] = parts.contentType;++ var reader = new FileReader();+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };++ reader.readAsBinaryString(parts.body);+ });+ });++ return promise;+ }+ },+ "Blob": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "application/octet-binary;";++ var body = reqContext.requestData;+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {+ var base64str = btoa(reader.result);+ resolve(base64str);+ };+ reader.onerror = function ()+ {+ var base64str = btoa(reader.error);+ reject(base64str);+ };+ });++ reader.readAsBinaryString(body);++ return promise;+ }+ },+ "string": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "text/plain;";++ var body = reqContext.requestData;+ var mimeType = reqContext.requestHeaders["content-type"];+ return HttpHandler._convertTextToBinaryBase64String(mimeType, body);+ }+ },+ "Object": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "application/json;";++ var body = JSON.stringify(reqContext.requestData);+ var mimeType = reqContext.requestHeaders["content-type"];+ return HttpHandler._convertTextToBinaryBase64String(mimeType, body);+ }+ },+ "Document": {+ convert: function (reqContext)+ {+ if (!reqContext.requestHeaders["content-type"])+ reqContext.requestHeaders["content-type"] = "application/xhtml+xml;";++ var body = reqContext.requestData;+ var serializer = new XMLSerializer();+ var body = serializer.serializeToString(body);+ var mimeType = reqContext.requestHeaders["content-type"];+ return HttpHandler._convertTextToBinaryBase64String(mimeType, body);+ }+ }+ };++ HttpHandler._convertEncode64StringToText = function(mimeType, encoding, r)+ {+ var binaryString = atob(r);+ var byteNumbers = new Array(binaryString.length);+ for (var i = 0; i < binaryString.length; i++)+ byteNumbers[i] = binaryString.charCodeAt(i);++ var byteArray = new Uint8Array(byteNumbers);++ var blob = new Blob([byteArray], {type: mimeType});++ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {++ resolve(reader.result);+ };+ reader.onerror = function ()+ {+ reject(reader.error);+ };+ });++ reader.readAsText(blob, encoding);+ return promise;+ };++ HttpHandler._convertEncode64StringToArrayBuffer = function (mimeType, encoding, r)+ {+ var binaryString = atob(r);+ var byteNumbers = new Array(binaryString.length);+ for (var i = 0; i < binaryString.length; i++)+ byteNumbers[i] = binaryString.charCodeAt(i);++ var byteArray = new Uint8Array(byteNumbers);++ var blob = new Blob([byteArray], {type: mimeType});+ var reader = new FileReader();+ var promise = new Promise(function (resolve, reject)+ {+ reader.onload = function ()+ {++ resolve(reader.result);+ };+ reader.onerror = function ()+ {+ reject(reader.error);+ };+ });+ reader.readAsArrayBuffer(blob);+ return promise;+ };++ HttpHandler._RESPONSE_HANDLERS = {+ "text": {+ convert: HttpHandler._convertEncode64StringToText+ },+ "arraybuffer": {+ convert: HttpHandler._convertEncode64StringToArrayBuffer+ },+ "blob": {+ convert: HttpHandler._convertEncode64StringToArrayBuffer+ },+ "json": {+ convert: HttpHandler._convertEncode64StringToText+ },+ "document": {+ convert: HttpHandler._convertEncode64StringToText+ }+ };++ HttpHandler._UNDERLYING_ERROR_CODES = {+ NSURLErrorUnknown: -1,+ NSURLErrorCancelled: -999,+ NSURLErrorBadURL: -1000,+ NSURLErrorTimedOut: -1001,+ NSURLErrorUnsupportedURL: -1002,+ NSURLErrorCannotFindHost: -1003,+ NSURLErrorCannotConnectToHost: -1004,+ NSURLErrorNetworkConnectionLost: -1005,+ NSURLErrorDNSLookupFailed: -1006,+ NSURLErrorHTTPTooManyRedirects: -1007,+ NSURLErrorResourceUnavailable: -1008,+ NSURLErrorNotConnectedToInternet: -1009,+ NSURLErrorRedirectToNonExistentLocation: -1010,+ NSURLErrorBadServerResponse: -1011,+ NSURLErrorUserCancelledAuthentication: -1012,+ NSURLErrorUserAuthenticationRequired: -1013,+ NSURLErrorZeroByteResource: -1014,+ NSURLErrorCannotDecodeRawData: -1015,+ NSURLErrorCannotDecodeContentData: -1016,+ NSURLErrorCannotParseResponse: -1017,+ NSURLErrorAppTransportSecurityRequiresSecureConnection: -1022,+ NSURLErrorFileDoesNotExist: -1100,+ NSURLErrorFileIsDirectory: -1101,+ NSURLErrorNoPermissionsToReadFile: -1102,+ NSURLErrorDataLengthExceedsMaximum: -1103,+ NSURLErrorFileOutsideSafeArea: -1104,+ NSURLErrorSecureConnectionFailed: -1200,+ NSURLErrorServerCertificateHasBadDate: -1201,+ NSURLErrorServerCertificateUntrusted: -1202,+ NSURLErrorServerCertificateHasUnknownRoot: -1203,+ NSURLErrorServerCertificateNotYetValid: -1204,+ NSURLErrorClientCertificateRejected: -1205,+ NSURLErrorClientCertificateRequired: -1206,+ NSURLErrorCannotLoadFromNetwork: -2000,+ NSURLErrorCannotCreateFile: -3000,+ NSURLErrorCannotOpenFile: -3001,+ NSURLErrorCannotCloseFile: -3002,+ NSURLErrorCannotWriteToFile: -3003,+ NSURLErrorCannotRemoveFile: -3004,+ NSURLErrorCannotMoveFile: -3005,+ NSURLErrorDownloadDecodingFailedMidStream: -3006,+ NSURLErrorDownloadDecodingFailedToComplete: -3007,+ NSURLErrorInternationalRoamingOff: -1018,+ NSURLErrorCallIsActive: -1019,+ NSURLErrorDataNotAllowed: -1020,+ NSURLErrorRequestBodyStreamExhausted: -1021,+ NSURLErrorBackgroundSessionRequiresSharedContainer: -995,+ NSURLErrorBackgroundSessionInUseByAnotherProcess: -996,+ NSURLErrorBackgroundSessionWasDisconnected: -997+ };++ HttpHandler._getHandlerForRequestBodyType = function (reqContext)+ {+ var body = reqContext.requestData;+ if (!body)+ return HttpHandler._REQUEST_HANDLERS[""];+ else if (typeof body === "string")+ return HttpHandler._REQUEST_HANDLERS["string"];+ else if (Blob.prototype.isPrototypeOf(body))+ return HttpHandler._REQUEST_HANDLERS["Blob"];+ else if (FormData.prototype.isPrototypeOf(body))+ return HttpHandler._REQUEST_HANDLERS["FormData"];+ else if (ArrayBuffer.prototype.isPrototypeOf(body) ||+ body.buffer)+ return HttpHandler._REQUEST_HANDLERS["ArrayBuffer"];+ else if (Document.prototype.isPrototypeOf(body))+ return HttpHandler._REQUEST_HANDLERS["Document"];+ else+ return HttpHandler._REQUEST_HANDLERS["Object"];+ };++ HttpHandler._getHandlerForResponseType = function (reqContext)+ {+ var responseType = reqContext.responseType;+ if (HttpHandler._RESPONSE_HANDLERS[responseType])+ return HttpHandler._RESPONSE_HANDLERS[responseType];+ else+ return HttpHandler._RESPONSE_HANDLERS["text"];+ };++ HttpHandler.prototype._isTraceLoggingEnabled = function ()+ {+ return this._config["NativeXHRLogging"] === "full";+ };++ HttpHandler._resolveUri = function (uri)+ {+ if (uri.indexOf("://") > -1)+ return uri;++ var resolver = document.createElement("a");+ document.body.appendChild(resolver);+ resolver.href = uri;+ var absoluteUri = resolver.href;+ resolver.parentNode.removeChild(resolver);+ return absoluteUri;+ };++ HttpHandler.prototype.send = function ()+ {+ var reqContext = this._reqContext;+ var id = HttpHandler._generateId();++ if (reqContext.user && reqContext.password)+ {+ var token = [reqContext.user, reqContext.password].join(":");+ reqContext.requestHeaders["authorization"] = ["Basic", btoa(token)].join(" ");+ }++ window.__nativeXHRResponseQueue.set(id, this);++ var handler = HttpHandler._getHandlerForRequestBodyType(reqContext);+ handler.convert(reqContext).then(function (bodyAsBase64String)+ {+ var requestDataSize = bodyAsBase64String ? bodyAsBase64String.length : 0;+ reqContext.requestData = undefined;++ var timeoutInSecs = (isNaN(reqContext.timeout) ? undefined : (reqContext.timeout / 1000));++ var reqPayLoad = {id: id, callback: "nativeXHRResponse",+ url: HttpHandler._resolveUri(reqContext.url), method: reqContext.method,+ headers: reqContext.requestHeaders,+ body: bodyAsBase64String, timeout: timeoutInSecs};++ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native XHR Request:\n %o", reqPayLoad);++ HttpHandler._presend(reqContext, requestDataSize);++ window.webkit.messageHandlers.nativeXHR.postMessage(reqPayLoad);+ }.bind(this)).catch(HttpHandler._error.bind(this, reqContext));+ };++ HttpHandler._presend = function (reqContext, requestDataSize)+ {+ reqContext.dispatchReadyStateChangeEvent(1); // OPEN+ reqContext.dispatchProgressEvent("loadstart");++ // simulate upload progress events+ reqContext.dispatchUploadProgressEvent("loadstart");+ reqContext.dispatchUploadProgressEvent("progress", requestDataSize);+ reqContext.dispatchUploadProgressEvent("load", requestDataSize);+ reqContext.dispatchUploadProgressEvent("loadend", requestDataSize);+ };++ HttpHandler._success = function (reqContext, payload, mimeType, result)+ {+ var rspTypeHandler = FileHandler.getHandlerForResponseType(reqContext);+ var convertedResult = rspTypeHandler.convert(mimeType, result);++ // normalize header keys to lower case.+ var responseHeaders = payload.response.allHeaderFields;+ var normalizedHeaders = {};+ var keys = Object.keys(responseHeaders);+ for (var i = 0; i < keys.length; i++)+ {+ var key = keys[i];+ normalizedHeaders[key.toLowerCase()] = responseHeaders[key];+ }++ reqContext.responseHeaders = normalizedHeaders;++ reqContext.responseURL = payload.response.url;+ reqContext.status = payload.response.statusCode;+ reqContext.statusText = payload.response.localizedStatusCode;++ for (var i = 0; i < rspTypeHandler.properties.length; i++)+ reqContext[rspTypeHandler.properties[i]] = convertedResult;++ var respSize = rspTypeHandler.responseSize();++ reqContext.dispatchReadyStateChangeEvent(2); //HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); //LOADING+ reqContext.dispatchProgressEvent("progress", respSize);+ reqContext.dispatchReadyStateChangeEvent(4); //DONE++ reqContext.dispatchProgressEvent("load", respSize);+ reqContext.dispatchProgressEvent("loadend", respSize);+ };++ HttpHandler._error = function (reqContext, error, underlyingErrorCode)+ {+ var isTimeout = (HttpHandler._UNDERLYING_ERROR_CODES.NSURLErrorTimedOut === underlyingErrorCode);++ if (isTimeout)+ {+ reqContext.status = 0;+ reqContext.statusText = reqContext.responseText = null;+ }+ else+ {+ reqContext.status = 400;+ reqContext.statusText = "Bad Request";+ reqContext.responseText = error;+ }++ reqContext.dispatchReadyStateChangeEvent(2); //HEADERS_RECIEVED+ reqContext.dispatchReadyStateChangeEvent(3); //LOADING+ reqContext.dispatchProgressEvent("progress");+ reqContext.dispatchReadyStateChangeEvent(4); //DONE++ if (isTimeout)+ reqContext.dispatchProgressEvent("timeout");+ else+ reqContext.dispatchProgressEvent("error");++ reqContext.dispatchProgressEvent("loadend");+ };+++ HttpHandler.prototype.load = function (payload)+ {+ var reqContext = this._reqContext;++ if (this._isTraceLoggingEnabled())+ console.log("xhr-polyfill.js - native XHR Response:\n%o", payload);++ if (payload.error)+ HttpHandler._error(reqContext, payload.error, payload['underlyingErrorCode']);+ else+ {+ var handler = HttpHandler._getHandlerForResponseType(reqContext);+ var mimeType = payload.response.mimeType;+ if (reqContext.overrideMimeType) // look for overrideMimeType+ mimeType = reqContext.overrideMimeType;+ else if (payload.response.allHeaderFields && payload.response.allHeaderFields["content-type"])+ mimeType = payload.response.allHeaderFields["content-type"];++ var encoding = payload.response.textEncodingName ? payload.response.textEncodingName : "UTF-8";++ handler.convert(mimeType, encoding, payload.data).then(HttpHandler._success.bind(this,+ reqContext, payload, mimeType));+ }+ };++ window.__nativeXHRResponseQueue = new Map();+ window.nativeXHRResponse = function (id, payload)+ {+ try+ {+ var handler = window.__nativeXHRResponseQueue.get(id);+ payload["id"] = id;+ handler.load(payload);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering request %o\n%o", id, e);+ }+ finally+ {+ window.__nativeXHRResponseQueue.delete(id);+ }+ };++ // sends the request using JS native XMLHttpRequest+ function DelegateHandler(reqContext, config)+ {+ this._reqContext = reqContext;+ this._reqContext.delegate = new window._XMLHttpRequest();+ this._config = config;+ }++ DelegateHandler._FROM_PROPERTIES = ["response", "responseText", "responseXML", "responseURL",+ "status", "statusText"];++ DelegateHandler._TO_PROPERTIES = ["responseType", "timeout", "withCredentials"];++ DelegateHandler._parseResponseHeaders = function (delegate, toHeaders)+ {+ var fromHeaders = delegate.getAllResponseHeaders().split(/\r?\n/);+ for (var i = 0; i < fromHeaders.length; i++)+ {+ var tokens = fromHeaders[i];+ var n = tokens.indexOf(": ");+ if (n > -1)+ {+ var key = tokens.substr(0, n).toLowerCase();+ var value = tokens.substr(n + 2);+ toHeaders[key] = value;+ }+ }+ };++ DelegateHandler._progressEventRelay = function (reqContext, event)+ {+ var respSize = isNaN(event.totalSize) ? 0 : event.totalSize;+ reqContext.dispatchProgressEvent(event.type, respSize);+ };++ DelegateHandler._uploadProgressEventRelay = function (reqContext, event)+ {+ var respSize = isNaN(event.totalSize) ? 0 : event.totalSize;+ reqContext.dispatchUploadProgressEvent(event.type, respSize);+ };++ DelegateHandler._readystatechangeEventRelay = function (reqContext, delegate, event)+ {++ if (delegate.readyState > 1) // readyState gt HEADERS_RECIEVED+ {+ if (Object.keys(reqContext.responseHeaders).length === 0)+ DelegateHandler._parseResponseHeaders(delegate, reqContext.responseHeaders);++ for (var i = 0; i < DelegateHandler._FROM_PROPERTIES.length; i++)+ {+ try+ {+ reqContext[DelegateHandler._FROM_PROPERTIES[i]] = delegate[DelegateHandler._FROM_PROPERTIES[i]];+ }+ catch (e)+ {+ }+ }++ reqContext.dispatchReadyStateChangeEvent(delegate.readyState);+ }+ };++ DelegateHandler.prototype.send = function ()+ {+ var reqContext = this._reqContext;+ var delegate = reqContext.delegate;++ delegate.onreadystatechange = DelegateHandler._readystatechangeEventRelay.bind(delegate,+ reqContext, delegate);+ ["ontimeout", "onloadstart", "onprogress", "onabort", "onerror", "onload",+ "onloadend"].forEach(function (eventType)+ {+ delegate[eventType] = DelegateHandler._progressEventRelay.bind(delegate, reqContext);+ delegate.upload[eventType] = DelegateHandler._uploadProgressEventRelay.bind(delegate,+ reqContext);+ });++ if (reqContext.overrideMimeType)+ delegate.overrideMimeType(reqContext.overrideMimeType);++ delegate.open(reqContext.method, reqContext.url, reqContext.async, reqContext.user,+ reqContext.password);++ for (var i = 0; i < DelegateHandler._TO_PROPERTIES.length; i++)+ delegate[DelegateHandler._TO_PROPERTIES[i]] = reqContext[DelegateHandler._TO_PROPERTIES[i]];++ var keys = Object.keys(reqContext.requestHeaders);+ for (var i = 0; i < keys.length; i++)+ delegate.setRequestHeader(keys[i], reqContext.requestHeaders[keys[i]]);++ var requestData = reqContext.requestData;+ reqContext.requestData = undefined;++ // returns a native FormData from the plugin's polyfill+ if (FormData.prototype.isPrototypeOf(requestData))+ requestData = requestData.__getNative();++ delegate.send(requestData);+ };++ function HandlerFactory()+ {+ }++ HandlerFactory._getConfig = function ()+ {+ var promise;+ if (HandlerFactory._config)+ {+ promise = Promise.resolve(HandlerFactory._config);+ }+ else+ {+ promise = new Promise(function (done)+ {+ function success(result)+ {+ HandlerFactory._config = result;+ done(HandlerFactory._config);+ }++ function error()+ {+ HandlerFactory._config = {"InterceptRemoteRequests": "secureOnly",+ "NativeXHRLogging": "none"};+ done(HandlerFactory._config);+ }++ exec(success, error, "CDVWKWebViewFileXhr", "getConfig", []);+ });++ }++ return promise;+ };++ HandlerFactory.getHandler = function (context)+ {+ var promise = new Promise(function (resolve)+ {+ HandlerFactory._getConfig().then(function (config)+ {+ var interceptRemoteRequests = config["InterceptRemoteRequests"];++ if (context.interceptRemoteRequests) // backdoor to override per instance+ interceptRemoteRequests = context.interceptRemoteRequests;++ if ("GET" === context.method && typeof context.url === "string" &&+ ((context.url.indexOf("://") === -1 && window.location.protocol === "file:") ||+ (context.url.toLowerCase().startsWith("file://"))))+ {+ resolve(new FileHandler(context, config));+ }+ else+ {+ if ("all" === interceptRemoteRequests ||+ ("secureOnly" === interceptRemoteRequests && context.url.startsWith("https://")))+ resolve(new HttpHandler(context, config));+ else+ resolve(new DelegateHandler(context, config));+ }+ });+ });++ return promise;+ };++ function _XMLHttpRequestUpload()+ {+ this._context = {"listeners": {}};+ }++ _XMLHttpRequestUpload.prototype.removeEventListener = function (type, listener)+ {+ var listeners = this._context.listeners;+ if (!listener)+ listeners[type] = [];+ else+ {+ var lset = listeners[type] ? listeners[type] : [];+ var i = lset.indexOf(listener);+ if (i > -1)+ lset.splice(i, 1);+ }+ };++ _XMLHttpRequestUpload.prototype.addEventListener = function (type, listener)+ {+ if (!listener)+ return;++ var listeners = this._context.listeners;+ var lset = listeners[type];+ if (!lset)+ lset = listeners[type] = [];++ if (lset.indexOf(listeners) < 0)+ lset.push(listener);+ };++ _XMLHttpRequestUpload.prototype.dispatchEvent = function (event)+ {+ if (!event)+ return;++ var type = event.type;+ var listeners = this._context.listeners;+ var lset = listeners[type] ? listeners[type] : [];++ // call property listeners+ var listener = this._context[["on", type].join("")];+ if (listener)+ {+ try+ {+ listener.call(this, event);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering upload event %o\n%o", event, e);+ }+ }+ };++ /** @type {?} */+ window._XMLHttpRequest = window.XMLHttpRequest;+ window.XMLHttpRequest = function ()+ {+ this._context = {delegate: null, requestHeaders: {}, responseHeaders: {},+ listeners: {}, readyState: 0, responseType: "text", withCredentials: false,+ upload: new _XMLHttpRequestUpload(), status: 0};++ this._context.dispatchProgressEvent = function (req, type, respSize)+ {+ if (isNaN(respSize))+ respSize = 0;++ var event = document.createEvent("Event");+ event.initEvent(type, false, false);+ ["total", "totalSize", "loaded", "position"].forEach(function (propName)+ {+ Object.defineProperty(event, propName, {value: respSize});+ });+ Object.defineProperty(event, "lengthComputable", {value: respSize === 0 ? false : true});++ req.dispatchEvent(event);+ }.bind(this._context, this);++ this._context.dispatchReadyStateChangeEvent = function (req, readyState)+ {+ var event = document.createEvent("Event");+ event.initEvent("readystatechange", false, false);++ this.readyState = readyState;+ req.dispatchEvent(event);+ }.bind(this._context, this);++ this._context.dispatchUploadProgressEvent = function (type, reqSize)+ {+ // no body sent on a GET request+ if (this.method === "GET")+ return;++ if (isNaN(reqSize))+ reqSize = 0;++ var event = document.createEvent("Event");+ event.initEvent(type, false, false);+ ["total", "totalSize", "loaded", "position"].forEach(function (propName)+ {+ Object.defineProperty(event, propName, {value: reqSize});+ });+ Object.defineProperty(event, "lengthComputable", {value: reqSize === 0 ? false : true});++ this.upload.dispatchEvent(event);+ }.bind(this._context);+ };+++ // define readonly const properties+ ["UNSENT", "OPENED", "HEADERS_RECIEVED", "LOADING", "DONE"].forEach(function (propName, i)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return i;+ }+ });+ });++ // define readonly properties.+ ["readyState", "response", "responseText", "responseURL", "responseXML",+ "status", "statusText", "upload"].forEach(function (propName)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ }+ });+ });++// define read/write properties+ ["responseType", "timeout", "withCredentials"].forEach(function (propName)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ },+ "set": function (value)+ {+ this._context[propName] = value;+ }+ });+ });++ // define read/write readychange event listener properties+ Object.defineProperty(window.XMLHttpRequest.prototype, "onreadystatechange",+ {+ "get": function ()+ {+ return this._context["onreadystatechange"];+ },+ "set": function (value)+ {+ if (typeof value === "function")+ this._context["onreadystatechange"] = value;+ }+ });++ // define read/write event progress listener properties+ ["ontimeout", "onloadstart", "onprogress", "onabort", "onerror", "onload", "onloadend"].forEach(+ function (propName)+ {+ Object.defineProperty(window.XMLHttpRequest.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ },+ "set": function (value)+ {+ if (typeof value === "function")+ this._context[propName] = value;+ }+ });++ Object.defineProperty(_XMLHttpRequestUpload.prototype, propName,+ {+ "get": function ()+ {+ return this._context[propName];+ },+ "set": function (value)+ {+ if (typeof value === "function")+ this._context[propName] = value;+ }+ });+ });++ window.XMLHttpRequest.prototype.setRequestHeader = function (header, value)+ {+ // normalize value pair to strings+ header = String(header).toLowerCase();;+ value = String(value);+ this._context.requestHeaders[header] = value;+ };++ window.XMLHttpRequest.prototype.abort = function ()+ {+ if (this._context["delegate"])+ this._context.delegate.abort();+ };++ window.XMLHttpRequest.prototype.getResponseHeader = function (name)+ {+ name = name.toLowerCase();+ return this._context.responseHeaders[name];+ };++ window.XMLHttpRequest.prototype.overrideMimeType = function (mimetype)+ {+ return this._context.overrideMimeType = mimetype;+ };++ window.XMLHttpRequest.prototype.getAllResponseHeaders = function ()+ {+ var responseHeaders = this._context.responseHeaders;+ var names = Object.keys(responseHeaders);+ var list = [];+ for (var i = 0; i < names.length; i++)+ list.push([names[i], responseHeaders[names[i]]].join(":"));++ return list.join("\n");+ };++ window.XMLHttpRequest.prototype.removeEventListener = function (type, listener)+ {+ var listeners = this._context.listeners;+ if (!listener)+ listeners[type] = [];+ else+ {+ var lset = listeners[type] ? listeners[type] : [];+ var i = lset.indexOf(listener);+ if (i > -1)+ lset.splice(i, 1);+ }+ };++ window.XMLHttpRequest.prototype.addEventListener = function (type, listener)+ {+ if (!listener)+ return;++ var listeners = this._context.listeners;+ var lset = listeners[type];+ if (!lset)+ lset = listeners[type] = [];++ if (lset.indexOf(listeners) < 0)+ lset.push(listener);+ };++ window.XMLHttpRequest.prototype.dispatchEvent = function (event)+ {+ if (!event)+ return;++ var type = event.type;+ var listeners = this._context.listeners;+ var lset = listeners[type] ? listeners[type] : [];++ // call property listeners+ var listener = this._context[["on", type].join("")];+ if (listener)+ {+ try+ {+ listener.call(this, event);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering event %o\n%o", event, e);+ }+ }++ // call listeners registered via addEventListener+ for (var i = 0; i < lset.length; i++)+ {+ listener = lset[i];+ if (listener)+ {+ try+ {+ listener.call(this, event);+ }+ catch (e)+ {+ console.log("xhr-polyfill.js - exception delivering event %o\n%o", event, e);+ }+ }+ }+ };++ window.XMLHttpRequest.prototype.open = function (method, url, async, user, password)+ {+ this._context.method = !method ? "GET" : method.toUpperCase(); // FortifyFalsePositive+ this._context.url = url;+ this._context.async = async === undefined ? true : async;+ this._context.user = user;+ this._context.password = password;+ };++ window.XMLHttpRequest.prototype.send = function (data)+ {+ if ("GET" !== this._context.method && "HEAD" !== this._context.method)+ this._context.requestData = data;++ HandlerFactory.getHandler(this._context).then(function (handler)+ {+ handler.send();+ });+ };++ /**+ * Override plugin config settings per request instance for the "InterceptRemoteRequests"+ * config param.+ *+ * @param {string} value enumerations are: "all", "secureOnly", "none".+ */+ window.XMLHttpRequest.prototype.__setInterceptRemoteRequests = function (value)+ {+ if (["all", "secureOnly", "none"].indexOf(value) > -1)+ {+ this._context.interceptRemoteRequests = value;+ }+ };++})();++});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.js b/cordova/platforms/ios/www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.jsdeleted file mode 100644index dc7595da2..000000000--- a/cordova/platforms/ios/www/plugins/cordova-plugin-wkwebview-engine/src/www/ios/ios-wkwebview-exec.js+++ /dev/null@@ -1,177 +0,0 @@-cordova.define("cordova-plugin-wkwebview-engine.ios-wkwebview-exec", function(require, exports, module) {-/*- *- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- *-*/--/**- * Creates the exec bridge used to notify the native code of- * commands.- */-var cordova = require('cordova');-var utils = require('cordova/utils');-var base64 = require('cordova/base64');--function massageArgsJsToNative (args) {- if (!args || utils.typeName(args) !== 'Array') {- return args;- }- var ret = [];- args.forEach(function (arg, i) {- if (utils.typeName(arg) === 'ArrayBuffer') {- ret.push({- 'CDVType': 'ArrayBuffer',- 'data': base64.fromArrayBuffer(arg)- });- } else {- ret.push(arg);- }- });- return ret;-}--function massageMessageNativeToJs (message) {- if (message.CDVType === 'ArrayBuffer') {- var stringToArrayBuffer = function (str) {- var ret = new Uint8Array(str.length);- for (var i = 0; i < str.length; i++) {- ret[i] = str.charCodeAt(i);- }- return ret.buffer;- };- var base64ToArrayBuffer = function (b64) {- return stringToArrayBuffer(atob(b64)); // eslint-disable-line no-undef- };- message = base64ToArrayBuffer(message.data);- }- return message;-}--function convertMessageToArgsNativeToJs (message) {- var args = [];- if (!message || !message.hasOwnProperty('CDVType')) {- args.push(message);- } else if (message.CDVType === 'MultiPart') {- message.messages.forEach(function (e) {- args.push(massageMessageNativeToJs(e));- });- } else {- args.push(massageMessageNativeToJs(message));- }- return args;-}--var iOSExec = function () {- // detect change in bridge, if there is a change, we forward to new bridge-- // if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) {- // bridgeMode = jsToNativeModes.WK_WEBVIEW_BINDING;- // }-- var successCallback, failCallback, service, action, actionArgs;- var callbackId = null;- if (typeof arguments[0] !== 'string') {- // FORMAT ONE- successCallback = arguments[0];- failCallback = arguments[1];- service = arguments[2];- action = arguments[3];- actionArgs = arguments[4];-- // Since we need to maintain backwards compatibility, we have to pass- // an invalid callbackId even if no callback was provided since plugins- // will be expecting it. The Cordova.exec() implementation allocates- // an invalid callbackId and passes it even if no callbacks were given.- callbackId = 'INVALID';- } else {- throw new Error('The old format of this exec call has been removed (deprecated since 2.1). Change to: ' + // eslint-disable-line- 'cordova.exec(null, null, \'Service\', \'action\', [ arg1, arg2 ]);');- }-- // If actionArgs is not provided, default to an empty array- actionArgs = actionArgs || [];-- // Register the callbacks and add the callbackId to the positional- // arguments if given.- if (successCallback || failCallback) {- callbackId = service + cordova.callbackId++;- cordova.callbacks[callbackId] =- {success: successCallback, fail: failCallback};- }-- actionArgs = massageArgsJsToNative(actionArgs);-- // CB-10133 DataClone DOM Exception 25 guard (fast function remover)- var command = [callbackId, service, action, JSON.parse(JSON.stringify(actionArgs))];- window.webkit.messageHandlers.cordova.postMessage(command);-};--iOSExec.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- });-};--// for backwards compatibility-iOSExec.nativeEvalAndFetch = function (func) {- try {- func();- } catch (e) {- console.log(e);- }-};--// Proxy the exec for bridge changes. See CB-10106--function cordovaExec () {- var cexec = require('cordova/exec');- var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function');- return (cexec_valid && execProxy !== cexec) ? cexec : iOSExec;-}--function execProxy () {- cordovaExec().apply(null, arguments);-}--execProxy.nativeFetchMessages = function () {- return cordovaExec().nativeFetchMessages.apply(null, arguments);-};--execProxy.nativeEvalAndFetch = function () {- return cordovaExec().nativeEvalAndFetch.apply(null, arguments);-};--execProxy.nativeCallback = function () {- return cordovaExec().nativeCallback.apply(null, arguments);-};--module.exports = execProxy;--if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.cordova && window.webkit.messageHandlers.cordova.postMessage) {- // unregister the old bridge- cordova.define.remove('cordova/exec');- // redefine bridge to our new bridge- cordova.define('cordova/exec', function (require, exports, module) {- module.exports = execProxy;- });-}--});diff --git a/cordova/platforms/ios/www/plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js b/cordova/platforms/ios/www/plugins/cordova-plugin-x-socialsharing/www/SocialSharing.jsnew file mode 100644index 000000000..d16bfdc1c--- /dev/null+++ b/cordova/platforms/ios/www/plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js@@ -0,0 +1,160 @@+cordova.define("cordova-plugin-x-socialsharing.SocialSharing", function(require, exports, module) {+function SocialSharing() {+}++// Override this method (after deviceready) to set the location where you want the iPad popup arrow to appear.+// If not overridden with different values, the popup is not used. Example:+//+// window.plugins.socialsharing.iPadPopupCoordinates = function() {+// return "100,100,200,300";+// };+SocialSharing.prototype.iPadPopupCoordinates = function () {+ // left,top,width,height+ return "-1,-1,-1,-1";+};++SocialSharing.prototype.setIPadPopupCoordinates = function (coords) {+ console.log("Deprecated - setIPadPopupCoordinates no longer works since plugin version 5.5.0. See https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin/issues/1052");+ // left,top,width,height+ cordova.exec(function() {}, this._getErrorCallback(function() {}, "setIPadPopupCoordinates"), "SocialSharing", "setIPadPopupCoordinates", [coords]);+};++SocialSharing.prototype.available = function (callback) {+ cordova.exec(function (avail) {+ callback(avail ? true : false);+ }, null, "SocialSharing", "available", []);+};++// this is the recommended way to share as it is the most feature-rich with respect to what you pass in and get back+SocialSharing.prototype.shareWithOptions = function (options, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareWithOptions"), "SocialSharing", "shareWithOptions", [options]);+};++SocialSharing.prototype.shareW3C = function (sharedata) {+ return new Promise(function(resolve, reject) {+ var options = {+ subject: sharedata.title,+ message: sharedata.text,+ url: sharedata.url,+ iPadCoordinates: sharedata.iPadCoordinates || undefined+ };+ if(sharedata.hasOwnProperty('title') ||+ sharedata.hasOwnProperty('text') ||+ sharedata.hasOwnProperty('url')) {+ cordova.exec(resolve, reject, "SocialSharing", "shareWithOptions", [options]);+ } else {+ reject();+ }+ });+};++SocialSharing.prototype.share = function (message, subject, fileOrFileArray, url, iPadCoordinates, successCallback, errorCallback) {+ if (typeof iPadCoordinates === 'function') {+ errorCallback = successCallback;+ successCallback = iPadCoordinates;+ iPadCoordinates = "";+ }+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "share"), "SocialSharing", "share", [message, subject, this._asArray(fileOrFileArray), url, iPadCoordinates]);+};++SocialSharing.prototype.shareViaTwitter = function (message, file /* multiple not allowed by twitter */, url, successCallback, errorCallback) {+ var fileArray = this._asArray(file);+ var ecb = this._getErrorCallback(errorCallback, "shareViaTwitter");+ if (fileArray.length > 1) {+ ecb("shareViaTwitter supports max one file");+ } else {+ cordova.exec(successCallback, ecb, "SocialSharing", "shareViaTwitter", [message, null, fileArray, url]);+ }+};++SocialSharing.prototype.shareViaFacebook = function (message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaFacebook"), "SocialSharing", "shareViaFacebook", [message, null, this._asArray(fileOrFileArray), url]);+};++SocialSharing.prototype.shareViaFacebookWithPasteMessageHint = function (message, fileOrFileArray, url, pasteMessageHint, successCallback, errorCallback) {+ pasteMessageHint = pasteMessageHint || "If you like you can paste a message from your clipboard";+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaFacebookWithPasteMessageHint"), "SocialSharing", "shareViaFacebookWithPasteMessageHint", [message, null, this._asArray(fileOrFileArray), url, pasteMessageHint]);+};++SocialSharing.prototype.shareViaWhatsApp = function (message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaWhatsApp"), "SocialSharing", "shareViaWhatsApp", [message, null, this._asArray(fileOrFileArray), url, null, null]);+};++SocialSharing.prototype.shareViaWhatsAppToReceiver = function (receiver, message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaWhatsAppToReceiver"), "SocialSharing", "shareViaWhatsApp", [message, null, this._asArray(fileOrFileArray), url, receiver, null]);+};++SocialSharing.prototype.shareViaWhatsAppToPhone = function (phone, message, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaWhatsAppToPhone"), "SocialSharing", "shareViaWhatsApp", [message, null, this._asArray(fileOrFileArray), url, null, phone]);+};++SocialSharing.prototype.shareViaSMS = function (options, phonenumbers, successCallback, errorCallback) {+ var opts = options;+ if (typeof options === "string") {+ opts = {"message":options}; // for backward compatibility as the options param used to be the message+ }+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaSMS"), "SocialSharing", "shareViaSMS", [opts, phonenumbers]);+};++SocialSharing.prototype.shareViaEmail = function (message, subject, toArray, ccArray, bccArray, fileOrFileArray, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaEmail"), "SocialSharing", "shareViaEmail", [message, subject, this._asArray(toArray), this._asArray(ccArray), this._asArray(bccArray), this._asArray(fileOrFileArray)]);+};++SocialSharing.prototype.canShareVia = function (via, message, subject, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "canShareVia"), "SocialSharing", "canShareVia", [message, subject, this._asArray(fileOrFileArray), url, via]);+};++SocialSharing.prototype.canShareViaEmail = function (successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "canShareViaEmail"), "SocialSharing", "canShareViaEmail", []);+};++SocialSharing.prototype.shareViaInstagram = function (message, fileOrFileArray, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareViaInstagram"), "SocialSharing", "shareViaInstagram", [message, null, this._asArray(fileOrFileArray), null]);+};++SocialSharing.prototype.shareVia = function (via, message, subject, fileOrFileArray, url, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "shareVia"), "SocialSharing", "shareVia", [message, subject, this._asArray(fileOrFileArray), url, via]);+};++SocialSharing.prototype.saveToPhotoAlbum = function (fileOrFileArray, successCallback, errorCallback) {+ cordova.exec(successCallback, this._getErrorCallback(errorCallback, "saveToPhotoAlbum"), "SocialSharing", "saveToPhotoAlbum", [this._asArray(fileOrFileArray)]);+};++SocialSharing.prototype._asArray = function (param) {+ if (param == null) {+ param = [];+ } else if (typeof param === 'string') {+ param = new Array(param);+ }+ return param;+};++SocialSharing.prototype._getErrorCallback = function (ecb, functionName) {+ if (typeof ecb === 'function') {+ return ecb;+ } else {+ return function (result) {+ console.log("The injected error callback of '" + functionName + "' received: " + JSON.stringify(result));+ }+ }+};++SocialSharing.install = function () {+ if (!window.plugins) {+ window.plugins = {};+ }++ window.plugins.socialsharing = new SocialSharing();++ // Note only polyfill navigator.share if it is not defined, since shareW3C implements L1 of the spec,+ // and an existing navigator.share method could implement L2.+ if (!navigator.share) {+ navigator.share = window.plugins.socialsharing.shareW3C;+ }++ return window.plugins.socialsharing;+};++cordova.addConstructor(SocialSharing.install);++});diff --git a/cordova/platforms/ios/www/plugins/es6-promise-plugin/www/promise.js b/cordova/platforms/ios/www/plugins/es6-promise-plugin/www/promise.jsnew file mode 100644index 000000000..6cce47ae8--- /dev/null+++ b/cordova/platforms/ios/www/plugins/es6-promise-plugin/www/promise.js@@ -0,0 +1,13 @@+cordova.define("es6-promise-plugin.Promise", function(require, exports, module) {+/*!+ * @overview es6-promise - a tiny implementation of Promises/A+.+ * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)+ * @license Licensed under MIT license+ * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE+ * @version v4.2.2+97478eb6+ */++!function t(e,n,r){function o(u,s){if(!n[u]){if(!e[u]){var c="function"==typeof require&&require;if(!s&&c)return c(u,!0);if(i)return i(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var a=n[u]={exports:{}};e[u][0].call(a.exports,function(t){var n=e[u][1][t];return o(n?n:t)},a,a.exports,t,e,n,r)}return n[u].exports}for(var i="function"==typeof require&&require,u=0;u<r.length;u++)o(r[u]);return o}({1:[function(t){void 0===window.Promise&&t("es6-promise").polyfill()},{"es6-promise":2}],2:[function(t,e,n){(function(r,o){!function(t,r){"object"==typeof n&&"undefined"!=typeof e?e.exports=r():"function"==typeof define&&define.amd?define(r):t.ES6Promise=r()}(this,function(){"use strict";function e(t){var e=typeof t;return null!==t&&("object"===e||"function"===e)}function n(t){return"function"==typeof t}function i(t){J=t}function u(t){Q=t}function s(){return function(){return r.nextTick(h)}}function c(){return"undefined"!=typeof I?function(){I(h)}:l()}function f(){var t=0,e=new X(h),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function a(){var t=new MessageChannel;return t.port1.onmessage=h,function(){return t.port2.postMessage(0)}}function l(){var t=setTimeout;return function(){return t(h,1)}}function h(){for(var t=0;H>t;t+=2){var e=te[t],n=te[t+1];e(n),te[t]=void 0,te[t+1]=void 0}H=0}function p(){try{var e=t,n=e("vertx");return I=n.runOnLoop||n.runOnContext,c()}catch(r){return l()}}function d(t,e){var n=this,r=new this.constructor(y);void 0===r[ne]&&D(r);var o=n._state;if(o){var i=arguments[o-1];Q(function(){return L(o,r,i,n._result)})}else O(n,r,t,e);return r}function v(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(y);return E(n,t),n}function y(){}function m(){return new TypeError("You cannot resolve a promise with itself")}function _(){return new TypeError("A promises callback cannot return that same promise.")}function w(t){try{return t.then}catch(e){return ue.error=e,ue}}function g(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function b(t,e,n){Q(function(t){var r=!1,o=g(n,e,function(n){r||(r=!0,e!==n?E(t,n):j(t,n))},function(e){r||(r=!0,x(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,x(t,o))},t)}function T(t,e){e._state===oe?j(t,e._result):e._state===ie?x(t,e._result):O(e,void 0,function(e){return E(t,e)},function(e){return x(t,e)})}function A(t,e,r){e.constructor===t.constructor&&r===d&&e.constructor.resolve===v?T(t,e):r===ue?(x(t,ue.error),ue.error=null):void 0===r?j(t,e):n(r)?b(t,e,r):j(t,e)}function E(t,n){t===n?x(t,m()):e(n)?A(t,n,w(n)):j(t,n)}function S(t){t._onerror&&t._onerror(t._result),M(t)}function j(t,e){t._state===re&&(t._result=e,t._state=oe,0!==t._subscribers.length&&Q(M,t))}function x(t,e){t._state===re&&(t._state=ie,t._result=e,Q(S,t))}function O(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+oe]=n,o[i+ie]=r,0===i&&t._state&&Q(M,t)}function M(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r=void 0,o=void 0,i=t._result,u=0;u<e.length;u+=3)r=e[u],o=e[u+n],r?L(n,r,o,i):o(i);t._subscribers.length=0}}function P(){this.error=null}function C(t,e){try{return t(e)}catch(n){return se.error=n,se}}function L(t,e,r,o){var i=n(r),u=void 0,s=void 0,c=void 0,f=void 0;if(i){if(u=C(r,o),u===se?(f=!0,s=u.error,u.error=null):c=!0,e===u)return x(e,_()),void 0}else u=o,c=!0;e._state!==re||(i&&c?E(e,u):f?x(e,s):t===oe?j(e,u):t===ie&&x(e,u))}function k(t,e){try{e(function(e){E(t,e)},function(e){x(t,e)})}catch(n){x(t,n)}}function q(){return ce++}function D(t){t[ne]=ce++,t._state=void 0,t._result=void 0,t._subscribers=[]}function F(){return new Error("Array Methods must be provided an Array")}function F(){return new Error("Array Methods must be provided an Array")}function N(t){return new fe(this,t).promise}function U(t){var e=this;return G(t)?new e(function(n,r){for(var o=t.length,i=0;o>i;i++)e.resolve(t[i]).then(n,r)}):new e(function(t,e){return e(new TypeError("You must pass an array to race."))})}function Y(t){var e=this,n=new e(y);return x(n,t),n}function K(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function W(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function z(){var t=void 0;if("undefined"!=typeof o)t=o;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;if(n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(e){}if("[object Promise]"===r&&!n.cast)return}t.Promise=ae}var B=void 0;B=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var G=B,H=0,I=void 0,J=void 0,Q=function(t,e){te[H]=t,te[H+1]=e,H+=2,2===H&&(J?J(h):ee())},R="undefined"!=typeof window?window:void 0,V=R||{},X=V.MutationObserver||V.WebKitMutationObserver,Z="undefined"==typeof self&&"undefined"!=typeof r&&"[object process]"==={}.toString.call(r),$="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,te=new Array(1e3),ee=void 0;ee=Z?s():X?f():$?a():void 0===R&&"function"==typeof t?p():l();var ne=Math.random().toString(36).substring(16),re=void 0,oe=1,ie=2,ue=new P,se=new P,ce=0,fe=function(){function t(t,e){this._instanceConstructor=t,this.promise=new t(y),this.promise[ne]||D(this.promise),G(e)?(this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?j(this.promise,this._result):(this.length=this.length||0,this._enumerate(e),0===this._remaining&&j(this.promise,this._result))):x(this.promise,F())}return t.prototype._enumerate=function(t){for(var e=0;this._state===re&&e<t.length;e++)this._eachEntry(t[e],e)},t.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===v){var o=w(t);if(o===d&&t._state!==re)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===ae){var i=new n(y);A(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(r(t),e)},t.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===re&&(this._remaining--,t===ie?x(r,n):this._result[e]=n),0===this._remaining&&j(r,this._result)},t.prototype._willSettleAt=function(t,e){var n=this;O(t,void 0,function(t){return n._settledAt(oe,e,t)},function(t){return n._settledAt(ie,e,t)})},t}(),ae=function(){function t(e){this[ne]=q(),this._result=this._state=void 0,this._subscribers=[],y!==e&&("function"!=typeof e&&K(),this instanceof t?k(this,e):W())}return t.prototype.catch=function(t){return this.then(null,t)},t.prototype.finally=function(t){var e=this,n=e.constructor;return e.then(function(e){return n.resolve(t()).then(function(){return e})},function(e){return n.resolve(t()).then(function(){throw e})})},t}();return ae.prototype.then=d,ae.all=N,ae.race=U,ae.resolve=v,ae.reject=Y,ae._setScheduler=i,ae._setAsap=u,ae._asap=Q,ae.polyfill=z,ae.Promise=ae,ae})}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:3}],3:[function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(t){if(a===setTimeout)return setTimeout(t,0);if((a===n||!a)&&setTimeout)return a=setTimeout,setTimeout(t,0);try{return a(t,0)}catch(e){try{return a.call(null,t,0)}catch(e){return a.call(this,t,0)}}}function i(t){if(l===clearTimeout)return clearTimeout(t);if((l===r||!l)&&clearTimeout)return l=clearTimeout,clearTimeout(t);try{return l(t)}catch(e){try{return l.call(null,t)}catch(e){return l.call(this,t)}}}function u(){v&&p&&(v=!1,p.length?d=p.concat(d):y=-1,d.length&&s())}function s(){if(!v){var t=o(u);v=!0;for(var e=d.length;e;){for(p=d,d=[];++y<e;)p&&p[y].run();y=-1,e=d.length}p=null,v=!1,i(t)}}function c(t,e){this.fun=t,this.array=e}function f(){}var a,l,h=e.exports={};!function(){try{a="function"==typeof setTimeout?setTimeout:n}catch(t){a=n}try{l="function"==typeof clearTimeout?clearTimeout:r}catch(t){l=r}}();var p,d=[],v=!1,y=-1;h.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];d.push(new c(t,e)),1!==d.length||v||o(s)},c.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=f,h.addListener=f,h.once=f,h.off=f,h.removeListener=f,h.removeAllListeners=f,h.emit=f,h.prependListener=f,h.prependOnceListener=f,h.listeners=function(){return[]},h.binding=function(){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},{}]},{},[1]);+++});diff --git a/cordova/yarn.lock b/cordova/yarn.lockindex 918e63026..6a1ac7f5f 100644--- a/cordova/yarn.lock+++ b/cordova/yarn.lock@@ -2,15 +2,50 @@# yarn lockfile v1+"@globules-io/cordova-plugin-ios-xhr@^1.0.3":+ version "1.0.3"+ resolved "https://registry.yarnpkg.com/@globules-io/cordova-plugin-ios-xhr/-/cordova-plugin-ios-xhr-1.0.3.tgz#e1a0abb1ce9a0d1a925fb4b3ceb38045f2426475"+ integrity sha512-mFpnSuNkoPWel2K0uGFONj31tx4ud+E3nCKKe1uj1jYaj43gtRA1HDbPReqQyut8buQkShZKskYK/ofbdRRyxQ==++"@netflix/nerror@^1.1.3":+ version "1.1.3"+ resolved "https://registry.yarnpkg.com/@netflix/nerror/-/nerror-1.1.3.tgz#9d88eccca442f1d544f2761d15ea557dc0a44ed2"+ integrity sha512-b+MGNyP9/LXkapreJzNUzcvuzZslj/RGgdVVJ16P2wSlYatfLycPObImqVJSmNAdyeShvNeM/pl3sVZsObFueg==+ dependencies:+ assert-plus "^1.0.0"+ extsprintf "^1.4.0"+ lodash "^4.17.15"++"@nodelib/[email protected]":+ version "2.1.3"+ resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz#3a582bdb53804c6ba6d146579c46e52130cf4a3b"+ integrity sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw==+ dependencies:+ "@nodelib/fs.stat" "2.0.3"+ run-parallel "^1.1.9"++"@nodelib/[email protected]", "@nodelib/fs.stat@^2.0.2":+ version "2.0.3"+ resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz#34dc5f4cabbc720f4e60f75a747e7ecd6c175bd3"+ integrity sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA==++"@nodelib/fs.walk@^1.2.3":+ version "1.2.4"+ resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz#011b9202a70a6366e436ca5c065844528ab04976"+ integrity sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ==+ dependencies:+ "@nodelib/fs.scandir" "2.1.3"+ fastq "^1.6.0"+abbrev@1:version "1.1.1"resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8"integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==- version "1.4.0"- resolved "https://registry.yarnpkg.com/android-versions/-/android-versions-1.4.0.tgz#807ea2941d7e5780e6dd61c5d9b7b6f3c0706e09"- integrity sha512-GnomfYsBq+nZh3c3UH/4r9Jt6FuTxdhUJbeHIdYOH5xBhQ8I0ZzC2/RM5IFFIjrzuNWSHb8JWP1lPK0/a26jrg==+android-versions@^1.5.0:+ version "1.5.0"+ resolved "https://registry.yarnpkg.com/android-versions/-/android-versions-1.5.0.tgz#7790bc74e0812aafd69fb1ad0cb4db4474a525d6"+ integrity sha512-/GWUAqa2OJNlDF5VGSe3SR1QMHEPXxx54Ur56r0qQC0H9FlBr7kyBF2SgVEhzFCPbrW4UcYgVuWrq/2Ty3QvXg==dependencies:semver "^5.4.1"@@ -19,6 +54,16 @@ ansi@^0.3.1:resolved "https://registry.yarnpkg.com/ansi/-/ansi-0.3.1.tgz#0c42d4fb17160d5a9af1e484bace1c66922c1b21"integrity sha1-DELU+xcWDVqa8eSEus4cZpIsGyE=+assert-plus@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525"+ integrity sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=++at-least-node@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2"+ integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==+balanced-match@^1.0.0:version "1.0.0"resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"@@ -28,22 +73,12 @@ balanced-match@^1.0.0:version "1.0.0"resolved "git+https://github.com/sytolk/cordova-plugin-downloader.git#b33d614ac9d4dc4c50e38ebde5a9b11e987ca145"- version "1.2.0"- resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.2.0.tgz#a39992d723584811982be5e290bb6a53d86700f1"- integrity sha1-o5mS1yNYSBGYK+XikLtqU9hnAPE=-base64-js@^1.2.3:version "1.3.1"resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.3.1.tgz#58ece8cb75dd07e71ed08c736abc5fac4dbf8df1"integrity sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==- version "1.6.32"- resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.32.tgz#5867458b25ecd5bcb36b627c30bb501a13c07e89"- integrity sha512-ljKJdR3wk9thHfLj4DtrNiOSTxvGFaMjWrG4pW75juXC4j7+XuKJVFdg4kgFMYp85PVkO05dFMj2dk2xVsH4xw==--big-integer@^1.6.44, big-integer@^1.6.7:+big-integer@^1.6.44:version "1.6.48"resolved "https://registry.yarnpkg.com/big-integer/-/big-integer-1.6.48.tgz#8fd88bd1632cba4a1c8c3e3d7159f08bb95b4b9e"integrity sha512-j51egjPa7/i+RdiRuJbPdJ2FIUYYPhvYLjzoYbcMMm62ooO6F94fETG4MTs46zPAF9Brs04OajboA/qTGuz78w==@@ -55,7 +90,7 @@ [email protected]:dependencies:stream-buffers "~2.2.0"[email protected], bplist-parser@^0.2.0:version "0.2.0"resolved "https://registry.yarnpkg.com/bplist-parser/-/bplist-parser-0.2.0.tgz#43a9d183e5bf9d545200ceac3e712f79ebbe8d0e"integrity sha512-z0M+byMThzQmD9NILRniCUXYsYpjwnlO8N5uCFaCqIOpqRsJCrQL9NK3JsD67CN5a08nF5oIL2bD6loTdHOuKw==@@ -67,13 +102,6 @@ bplist-parser@^0.0.6:resolved "https://registry.yarnpkg.com/bplist-parser/-/bplist-parser-0.0.6.tgz#38da3471817df9d44ab3892e27707bbbd75a11b9"integrity sha1-ONo0cYF9+dRKs4kuJ3B7u9daEbk=-bplist-parser@^0.1.0:- version "0.1.1"- resolved "https://registry.yarnpkg.com/bplist-parser/-/bplist-parser-0.1.1.tgz#d60d5dcc20cba6dc7e1f299b35d3e1f95dafbae6"- integrity sha1-1g1dzCDLptx+HymbNdPh+V2vuuY=- dependencies:- big-integer "^1.6.7"-brace-expansion@^1.1.7:version "1.1.11"resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"@@ -82,82 +110,65 @@ brace-expansion@^1.1.7:balanced-match "^1.0.0"concat-map "0.0.1"+braces@^3.0.1:+ version "3.0.2"+ resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107"+ integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==+ dependencies:+ fill-range "^7.0.1"+version "0.0.1"resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=-cordova-android@^7.1.4:- version "7.1.4"- resolved "https://registry.yarnpkg.com/cordova-android/-/cordova-android-7.1.4.tgz#25261ad66cc64f42a30b70be005901fa30e2430e"- integrity sha512-Rtvu002I83uzfVyCsE6p2krFKVHt9TSAqZUATes+zH+o9cdxYGrLHY+PKCQo4SLCdSMdrkIHCDnQPTYTp/d7+g==- dependencies:- android-versions "1.4.0"- base64-js "1.2.0"- big-integer "1.6.32"- cordova-common "2.2.5"- elementtree "0.1.6"- glob "5.0.15"- nopt "3.0.1"- path-is-absolute "1.0.1"- plist "2.1.0"- properties-parser "0.2.3"- q "1.4.1"- sax "0.3.5"- semver "5.5.0"- shelljs "0.5.3"- xmlbuilder "8.2.2"-- version "2.2.5"- resolved "https://registry.yarnpkg.com/cordova-common/-/cordova-common-2.2.5.tgz#f93cef2ad494cfcbf56c46e3d612aaa9cb5fcc32"- integrity sha1-+TzvKtSUz8v1bEbj1hKqqctfzDI=+cordova-android@^9.0.0:+ version "9.0.0"+ resolved "https://registry.yarnpkg.com/cordova-android/-/cordova-android-9.0.0.tgz#8b9285b8062286c41d6b6e910f143bdc266a934c"+ integrity sha512-2ZEgApK4LPMYW0zh/mLAH3CabzCaKE0yxQTzA2wTf0Eo2HHTJnRtDCf9spGf3nPOkubyXS6+pvzz5QzNHpVTqQ==dependencies:- ansi "^0.3.1"- bplist-parser "^0.1.0"- cordova-registry-mapper "^1.1.8"- elementtree "0.1.6"- glob "^5.0.13"- minimatch "^3.0.0"- plist "^2.1.0"- q "^1.4.1"- shelljs "^0.5.3"- underscore "^1.8.3"- unorm "^1.3.3"--cordova-common@^3.1.0:- version "3.2.1"- resolved "https://registry.yarnpkg.com/cordova-common/-/cordova-common-3.2.1.tgz#f4fdbeb40d9049fe28a09fa901756ed66d246661"- integrity sha512-xg0EnjnA6EipxXG8cupdlYQYeDA6+ghbN+Pjq88xN1LInwP6Bo7IyGBdSV5QnfjOvzShF9BBwSxBAv0FOO0C2Q==+ android-versions "^1.5.0"+ cordova-common "^4.0.1"+ execa "^4.0.2"+ fs-extra "^9.0.1"+ nopt "^4.0.3"+ properties-parser "^0.3.1"+ which "^2.0.2"++cordova-common@^4.0.1:+ version "4.0.2"+ resolved "https://registry.yarnpkg.com/cordova-common/-/cordova-common-4.0.2.tgz#c5be3f3811f5731cd1d7eb5193b0789a8d5a854f"+ integrity sha512-od7aNShyuBajzPY83mUEO8tERwwWdFklXETHiXP5Ft87CWeo/tSuwNPFztyTy8XYc74yXdogXKPTJeUHuVzB8Q==dependencies:+ "@netflix/nerror" "^1.1.3"ansi "^0.3.1"- bplist-parser "^0.1.0"- cross-spawn "^6.0.5"- elementtree "0.1.7"- endent "^1.1.1"- fs-extra "^8.0.0"- glob "^7.1.2"- minimatch "^3.0.0"+ bplist-parser "^0.2.0"+ cross-spawn "^7.0.1"+ elementtree "^0.1.7"+ endent "^1.4.1"+ fast-glob "^3.2.2"+ fs-extra "^9.0.0"+ glob "^7.1.6"plist "^3.0.1"- q "^1.4.1"- strip-bom "^3.0.0"- underscore "^1.8.3"- which "^1.3.0"--cordova-ios@^5.1.1:- version "5.1.1"- resolved "https://registry.yarnpkg.com/cordova-ios/-/cordova-ios-5.1.1.tgz#31b8a8e5a45bc604e46dab60fa25faf50543356f"- integrity sha512-asZMCj44JMe/PMrDIRC97GStPCH+GpaMNVe8hdmu8WWXJzMzRNRRJ339YYU89jitWf9ZKMdyBgrnSnQi5bJ/ZQ==+ q "^1.5.1"+ read-chunk "^3.2.0"+ strip-bom "^4.0.0"+ underscore "^1.9.2"++cordova-ios@^6.1.0:+ version "6.1.0"+ resolved "https://registry.yarnpkg.com/cordova-ios/-/cordova-ios-6.1.0.tgz#24f52007dddadabcfcec3a0cade7ff7646d43ecc"+ integrity sha512-FlX17lC2w78CqEQXypSeFIW3vUFF7VkCjNNLN+EbvOlLld5LUIbNJWepBdKlEg1/ZMmTwAuucMuKSZTr37ra+Q==dependencies:- cordova-common "^3.1.0"- ios-sim "^8.0.1"- nopt "^4.0.1"+ cordova-common "^4.0.1"+ fs-extra "^9.0.0"+ ios-sim "^8.0.2"+ nopt "^4.0.3"plist "^3.0.1"- q "^1.5.1"- semver "^6.3.0"- shelljs "^0.5.3"- unorm "^1.4.1"- xcode "^2.0.0"+ semver "^7.3.2"+ unorm "^1.6.0"+ which "^2.0.2"+ xcode "^3.0.1"xml-escape "^1.1.0"cordova-plugin-background-mode@^0.7.3:@@ -190,52 +201,35 @@ cordova-plugin-whitelist@^1.3.4:resolved "https://registry.yarnpkg.com/cordova-plugin-whitelist/-/cordova-plugin-whitelist-1.3.4.tgz#31938545c7c3e7de35c20ab08c2c3afa06e8a3f9"integrity sha512-EYC5eQFVkoYXq39l7tYKE6lEjHJ04mvTmKXxGL7quHLdFPfJMNzru/UYpn92AOfpl3PQaZmou78C7EgmFOwFQQ==-cordova-plugin-wkwebview-engine@^1.2.1:- version "1.2.1"- resolved "https://registry.yarnpkg.com/cordova-plugin-wkwebview-engine/-/cordova-plugin-wkwebview-engine-1.2.1.tgz#f8972282969355d2d2f3458b23f604210e45eaf3"- integrity sha512-usp6pu+tJ1y0btVAXOjE5+tMjbvTY6hsiLfHJPMdyzkgHvxoNSePZ/NavTGj4CBJJlUjnMsN3TUq25+SeTZCow==--cordova-plugin-x-socialsharing@^5.6.8:- version "5.6.8"- resolved "https://registry.yarnpkg.com/cordova-plugin-x-socialsharing/-/cordova-plugin-x-socialsharing-5.6.8.tgz#81993336fa4260eb76a23ed1680cd63e1c72b040"- integrity sha512-R31ZQq00YNzLBwUM4VTE/uKhh/T0GEMuz/MZOw/Pu5AYIAAQkd7EMqFVhMtKs7wfHl1koiRz8+6nLDb19r2tBQ==--cordova-registry-mapper@^1.1.8:- version "1.1.15"- resolved "https://registry.yarnpkg.com/cordova-registry-mapper/-/cordova-registry-mapper-1.1.15.tgz#e244b9185b8175473bff6079324905115f83dc7c"- integrity sha1-4kS5GFuBdUc7/2B5MkkFEV+D3Hw=--cross-spawn@^6.0.5:- version "6.0.5"- resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4"- integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==+cross-spawn@^7.0.0, cross-spawn@^7.0.1:+ version "7.0.3"+ resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6"+ integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==dependencies:- nice-try "^1.0.4"- path-key "^2.0.1"- semver "^5.5.0"- shebang-command "^1.2.0"- which "^1.2.9"+ path-key "^3.1.0"+ shebang-command "^2.0.0"+ which "^2.0.1"dedent@^0.7.0:version "0.7.0"resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c"integrity sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=- version "0.1.6"- resolved "https://registry.yarnpkg.com/elementtree/-/elementtree-0.1.6.tgz#2ac4c46ea30516c8c4cbdb5e3ac7418e592de20c"- integrity sha1-KsTEbqMFFsjEy9teOsdBjlkt4gw=- dependencies:- sax "0.3.5"-+elementtree@^0.1.7:version "0.1.7"resolved "https://registry.yarnpkg.com/elementtree/-/elementtree-0.1.7.tgz#9ac91be6e52fb6e6244c4e54a4ac3ed8ae8e29c0"integrity sha1-mskb5uUvtuYkTE5UpKw+2K6OKcA=dependencies:sax "1.1.4"-endent@^1.1.1:+end-of-stream@^1.1.0:+ version "1.4.4"+ resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0"+ integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==+ dependencies:+ once "^1.4.0"++endent@^1.4.1:version "1.4.1"resolved "https://registry.yarnpkg.com/endent/-/endent-1.4.1.tgz#c58cc13dfc432d0b2c7faf74c13ffdca60b2d1c8"integrity sha512-buHTb5c8AC9NshtP6dgmNLYkiT+olskbq1z6cEGvfGCF3Qphbu/1zz5Xu+yjTDln8RbxNhPoUyJ5H8MSrp1olQ==@@ -249,37 +243,87 @@ es6-promise-plugin@^4.2.2:resolved "https://registry.yarnpkg.com/es6-promise-plugin/-/es6-promise-plugin-4.2.2.tgz#cfa0cc1383d91f999a62a2bbf4bd97bec305e0ac"integrity sha512-uoA4aVplXI9oqUYJFBAVRwAqIN9/n9JgrTAUGX3qPbnSZVE5yY1+6/MsoN5f4xsaPO62WjPHOdtts6okMN6tNA==+execa@^4.0.2:+ version "4.0.3"+ resolved "https://registry.yarnpkg.com/execa/-/execa-4.0.3.tgz#0a34dabbad6d66100bd6f2c576c8669403f317f2"+ integrity sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A==+ dependencies:+ cross-spawn "^7.0.0"+ get-stream "^5.0.0"+ human-signals "^1.1.1"+ is-stream "^2.0.0"+ merge-stream "^2.0.0"+ npm-run-path "^4.0.0"+ onetime "^5.1.0"+ signal-exit "^3.0.2"+ strip-final-newline "^2.0.0"++extsprintf@^1.4.0:+ version "1.4.0"+ resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f"+ integrity sha1-4mifjzVvrWLMplo6kcXfX5VRaS8=++fast-glob@^3.2.2:+ version "3.2.4"+ resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.4.tgz#d20aefbf99579383e7f3cc66529158c9b98554d3"+ integrity sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ==+ dependencies:+ "@nodelib/fs.stat" "^2.0.2"+ "@nodelib/fs.walk" "^1.2.3"+ glob-parent "^5.1.0"+ merge2 "^1.3.0"+ micromatch "^4.0.2"+ picomatch "^2.2.1"+fast-json-parse@^1.0.3:version "1.0.3"resolved "https://registry.yarnpkg.com/fast-json-parse/-/fast-json-parse-1.0.3.tgz#43e5c61ee4efa9265633046b770fb682a7577c4d"integrity sha512-FRWsaZRWEJ1ESVNbDWmsAlqDk96gPQezzLghafp5J4GUKjbCz3OkAHuZs5TuPEtkbVQERysLp9xv6c24fBm8Aw==-fs-extra@^8.0.0:- version "8.1.0"- resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0"- integrity sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==+fastq@^1.6.0:+ version "1.8.0"+ resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.8.0.tgz#550e1f9f59bbc65fe185cb6a9b4d95357107f481"+ integrity sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q==+ dependencies:+ reusify "^1.0.4"++fill-range@^7.0.1:+ version "7.0.1"+ resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40"+ integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==dependencies:+ to-regex-range "^5.0.1"++fs-extra@^9.0.0, fs-extra@^9.0.1:+ version "9.0.1"+ resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.0.1.tgz#910da0062437ba4c39fedd863f1675ccfefcb9fc"+ integrity sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ==+ dependencies:+ at-least-node "^1.0.0"graceful-fs "^4.2.0"- jsonfile "^4.0.0"- universalify "^0.1.0"+ jsonfile "^6.0.1"+ universalify "^1.0.0"fs.realpath@^1.0.0:version "1.0.0"resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8=[email protected], glob@^5.0.13:- version "5.0.15"- resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1"- integrity sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=+get-stream@^5.0.0:+ version "5.2.0"+ resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3"+ integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==dependencies:- inflight "^1.0.4"- inherits "2"- minimatch "2 || 3"- once "^1.3.0"- path-is-absolute "^1.0.0"+ pump "^3.0.0"-glob@^7.1.2:+glob-parent@^5.1.0:+ version "5.1.1"+ resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.1.tgz#b6c1ef417c4e5663ea498f1c45afac6916bbc229"+ integrity sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==+ dependencies:+ is-glob "^4.0.1"++glob@^7.1.6:version "7.1.6"resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6"integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==@@ -296,6 +340,11 @@ graceful-fs@^4.1.6, graceful-fs@^4.2.0:resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb"integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==+human-signals@^1.1.1:+ version "1.1.1"+ resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3"+ integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==+inflight@^1.0.4:version "1.0.6"resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"@@ -309,7 +358,7 @@ inherits@2:resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==-ios-sim@^8.0.1:+ios-sim@^8.0.2:version "8.0.2"resolved "https://registry.yarnpkg.com/ios-sim/-/ios-sim-8.0.2.tgz#e2394acb6db4378f75f4c3ff8610bbf4f4795c43"integrity sha512-P7nEG771bfd+JoMRjnis1gpZOkjTUUxu+4Ek1Z+eoaEEoT9byllU9pxfQ8Df7hL3gSkIQxNwTSLhos2I8tWUQA==@@ -319,30 +368,77 @@ ios-sim@^8.0.1:plist "^3.0.1"simctl "^2"+is-extglob@^2.1.1:+ version "2.1.1"+ resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2"+ integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=++is-glob@^4.0.1:+ version "4.0.1"+ resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc"+ integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==+ dependencies:+ is-extglob "^2.1.1"++is-number@^7.0.0:+ version "7.0.0"+ resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b"+ integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==++is-stream@^2.0.0:+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.0.tgz#bde9c32680d6fae04129d6ac9d921ce7815f78e3"+ integrity sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==+isexe@^2.0.0:version "2.0.0"resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=-jsonfile@^4.0.0:- version "4.0.0"- resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb"- integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=+jsonfile@^6.0.1:+ version "6.0.1"+ resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.0.1.tgz#98966cba214378c8c84b82e085907b40bf614179"+ integrity sha512-jR2b5v7d2vIOust+w3wtFKZIfpC2pnRmFAhAC/BuweZFQR8qZzxH1OyrQ10HmdVYiXWkYUqPVsz91cG7EL2FBg==+ dependencies:+ universalify "^1.0.0"optionalDependencies:graceful-fs "^4.1.6"-"minimatch@2 || 3", minimatch@^3.0.0, minimatch@^3.0.4:+lodash@^4.17.15:+ version "4.17.19"+ resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b"+ integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==++merge-stream@^2.0.0:+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60"+ integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==++merge2@^1.3.0:+ version "1.4.1"+ resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae"+ integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==++micromatch@^4.0.2:+ version "4.0.2"+ resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259"+ integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==+ dependencies:+ braces "^3.0.1"+ picomatch "^2.0.5"++mimic-fn@^2.1.0:+ version "2.1.0"+ resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b"+ integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==++minimatch@^3.0.4:version "3.0.4"resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==dependencies:brace-expansion "^1.1.7"-nice-try@^1.0.4:- version "1.0.5"- resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366"- integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==-version "1.0.9"resolved "https://registry.yarnpkg.com/nopt/-/nopt-1.0.9.tgz#3bc0d7cba7bfb0d5a676dbed7c0ebe48a4fd454e"@@ -350,14 +446,7 @@ [email protected]:dependencies:abbrev "1"- version "3.0.1"- resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.1.tgz#bce5c42446a3291f47622a370abbf158fbbacbfd"- integrity sha1-vOXEJEajKR9HYio3CrvxWPu6y/0=- dependencies:- abbrev "1"--nopt@^4.0.1:+nopt@^4.0.3:version "4.0.3"resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.3.tgz#a375cad9d02fd921278d954c2254d5aa57e15e48"integrity sha512-CvaGwVMztSMJLOeXPrez7fyfObdZqNUK1cPAEzLHrTybIua9pMdmmPR5YwtfNftIOMv3DPUhFaxsZMNTQO20Kg==@@ -365,18 +454,32 @@ nopt@^4.0.1:abbrev "1"osenv "^0.1.4"+npm-run-path@^4.0.0:+ version "4.0.1"+ resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea"+ integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==+ dependencies:+ path-key "^3.0.0"+objectorarray@^1.0.4:version "1.0.4"resolved "https://registry.yarnpkg.com/objectorarray/-/objectorarray-1.0.4.tgz#d69b2f0ff7dc2701903d308bb85882f4ddb49483"integrity sha512-91k8bjcldstRz1bG6zJo8lWD7c6QXcB4nTDUqiEvIL1xAsLoZlOOZZG+nd6YPz+V7zY1580J4Xxh1vZtyv4i/w==-once@^1.3.0:+once@^1.3.0, once@^1.3.1, once@^1.4.0:version "1.4.0"resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=dependencies:wrappy "1"+onetime@^5.1.0:+ version "5.1.2"+ resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e"+ integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==+ dependencies:+ mimic-fn "^2.1.0"+os-homedir@^1.0.0:version "1.0.2"resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3"@@ -395,24 +498,35 @@ osenv@^0.1.4:os-homedir "^1.0.0"os-tmpdir "^1.0.0"[email protected], path-is-absolute@^1.0.0:+p-finally@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/p-finally/-/p-finally-1.0.0.tgz#3fbcfb15b899a44123b34b6dcc18b724336a2cae"+ integrity sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=++p-try@^2.1.0:+ version "2.2.0"+ resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6"+ integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==++path-is-absolute@^1.0.0:version "1.0.1"resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18=-path-key@^2.0.1:- version "2.0.1"- resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40"- integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=+path-key@^3.0.0, path-key@^3.1.0:+ version "3.1.1"+ resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375"+ integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==[email protected], plist@^2.1.0:- version "2.1.0"- resolved "https://registry.yarnpkg.com/plist/-/plist-2.1.0.tgz#57ccdb7a0821df21831217a3cad54e3e146a1025"- integrity sha1-V8zbeggh3yGDEhejytVOPhRqECU=- dependencies:- base64-js "1.2.0"- xmlbuilder "8.2.2"- xmldom "0.1.x"+picomatch@^2.0.5, picomatch@^2.2.1:+ version "2.2.2"+ resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad"+ integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==++pify@^4.0.1:+ version "4.0.1"+ resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231"+ integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==plist@^3.0.1:version "3.0.1"@@ -423,68 +537,81 @@ plist@^3.0.1:xmlbuilder "^9.0.7"xmldom "0.1.x"- version "0.2.3"- resolved "https://registry.yarnpkg.com/properties-parser/-/properties-parser-0.2.3.tgz#f7591255f707abbff227c7b56b637dbb0373a10f"- integrity sha1-91kSVfcHq7/yJ8e1a2N9uwNzoQ8=+properties-parser@^0.3.1:+ version "0.3.1"+ resolved "https://registry.yarnpkg.com/properties-parser/-/properties-parser-0.3.1.tgz#1316e9539ffbfd93845e369b211022abd478771a"+ integrity sha1-ExbpU5/7/ZOEXjabIRAiq9R4dxo=+ dependencies:+ string.prototype.codepointat "^0.2.0"- version "1.4.1"- resolved "https://registry.yarnpkg.com/q/-/q-1.4.1.tgz#55705bcd93c5f3673530c2c2cbc0c2b3addc286e"- integrity sha1-VXBbzZPF82c1MMLCy8DCs63cKG4=+pump@^3.0.0:+ version "3.0.0"+ resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64"+ integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==+ dependencies:+ end-of-stream "^1.1.0"+ once "^1.3.1"-q@^1.4.1, q@^1.5.1:+q@^1.5.1:version "1.5.1"resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7"integrity sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=- version "0.3.5"- resolved "https://registry.yarnpkg.com/sax/-/sax-0.3.5.tgz#88fcfc1f73c0c8bbd5b7c776b6d3f3501eed073d"- integrity sha1-iPz8H3PAyLvVt8d2ttPzUB7tBz0=+read-chunk@^3.2.0:+ version "3.2.0"+ resolved "https://registry.yarnpkg.com/read-chunk/-/read-chunk-3.2.0.tgz#2984afe78ca9bfbbdb74b19387bf9e86289c16ca"+ integrity sha512-CEjy9LCzhmD7nUpJ1oVOE6s/hBkejlcJEgLQHVnQznOSilOPb+kpKktlLfFDK3/WP43+F80xkUTM2VOkYoSYvQ==+ dependencies:+ pify "^4.0.1"+ with-open-file "^0.1.6"++reusify@^1.0.4:+ version "1.0.4"+ resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76"+ integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==++run-parallel@^1.1.9:+ version "1.1.9"+ resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.9.tgz#c9dd3a7cf9f4b2c4b6244e173a6ed866e61dd679"+ integrity sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q==version "1.1.4"resolved "https://registry.yarnpkg.com/sax/-/sax-1.1.4.tgz#74b6d33c9ae1e001510f179a91168588f1aedaa9"integrity sha1-dLbTPJrh4AFRDxeakRaFiPGu2qk=- version "5.5.0"- resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab"- integrity sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==--semver@^5.4.1, semver@^5.5.0:+semver@^5.4.1:version "5.7.1"resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==-semver@^6.3.0:- version "6.3.0"- resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d"- integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==+semver@^7.3.2:+ version "7.3.2"+ resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.2.tgz#604962b052b81ed0786aae84389ffba70ffd3938"+ integrity sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ==-shebang-command@^1.2.0:- version "1.2.0"- resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea"- integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=+shebang-command@^2.0.0:+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea"+ integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==dependencies:- shebang-regex "^1.0.0"--shebang-regex@^1.0.0:- version "1.0.0"- resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3"- integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=+ shebang-regex "^3.0.0"[email protected], shelljs@^0.5.3:- version "0.5.3"- resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.5.3.tgz#c54982b996c76ef0c1e6b59fbdc5825f5b713113"- integrity sha1-xUmCuZbHbvDB5rWfvcWCX1txMRM=+shebang-regex@^3.0.0:+ version "3.0.0"+ resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172"+ integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==shelljs@^0.2.6:version "0.2.6"resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.2.6.tgz#90492d72ffcc8159976baba62fb0f6884f0c3378"integrity sha1-kEktcv/MgVmXa6umL7D2iE8MM3g=+signal-exit@^3.0.2:+ version "3.0.3"+ resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.3.tgz#a1410c2edd8f077b08b4e253c8eacfcaf057461c"+ integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==+simctl@^2:version "2.0.0"resolved "https://registry.yarnpkg.com/simctl/-/simctl-2.0.0.tgz#e3f1c6908735969e23e0922b0cb1161843dd0c59"@@ -493,7 +620,7 @@ simctl@^2:shelljs "^0.2.6"tail "^0.4.0"-simple-plist@^1.0.0:+simple-plist@^1.1.0:version "1.1.0"resolved "https://registry.yarnpkg.com/simple-plist/-/simple-plist-1.1.0.tgz#8354ab63eb3922a054c78ce96c209c532e907a23"integrity sha512-2i5Tc0BYAqppM7jVzmNrI+aEUntPolIq4fDgji6WuNNn1D/qYdn2KwoLhZdzQkE04lu9L5tUoeJsjuJAvd+lFg==@@ -507,66 +634,87 @@ stream-buffers@~2.2.0:resolved "https://registry.yarnpkg.com/stream-buffers/-/stream-buffers-2.2.0.tgz#91d5f5130d1cef96dcfa7f726945188741d09ee4"integrity sha1-kdX1Ew0c75bc+n9yaUUYh0HQnuQ=-strip-bom@^3.0.0:- version "3.0.0"- resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3"- integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=+string.prototype.codepointat@^0.2.0:+ version "0.2.1"+ resolved "https://registry.yarnpkg.com/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz#004ad44c8afc727527b108cd462b4d971cd469bc"+ integrity sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==++strip-bom@^4.0.0:+ version "4.0.0"+ resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878"+ integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==++strip-final-newline@^2.0.0:+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad"+ integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==tail@^0.4.0:version "0.4.0"resolved "https://registry.yarnpkg.com/tail/-/tail-0.4.0.tgz#d29de72750cc99db1e053aff13c359ecfb713002"integrity sha1-0p3nJ1DMmdseBTr/E8NZ7PtxMAI=-underscore@^1.8.3:+to-regex-range@^5.0.1:+ version "5.0.1"+ resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4"+ integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==+ dependencies:+ is-number "^7.0.0"++underscore@^1.9.2:version "1.10.2"resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.10.2.tgz#73d6aa3668f3188e4adb0f1943bd12cfd7efaaaf"integrity sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg==-universalify@^0.1.0:- version "0.1.2"- resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66"- integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==+universalify@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/universalify/-/universalify-1.0.0.tgz#b61a1da173e8435b2fe3c67d29b9adf8594bd16d"+ integrity sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug==-unorm@^1.3.3, unorm@^1.4.1:+unorm@^1.6.0:version "1.6.0"resolved "https://registry.yarnpkg.com/unorm/-/unorm-1.6.0.tgz#029b289661fba714f1a9af439eb51d9b16c205af"integrity sha512-b2/KCUlYZUeA7JFUuRJZPUtr4gZvBh7tavtv4fvk4+KV9pfGiR6CQAQAWl49ZpR3ts2dk4FYkP7EIgDJoiOLDA==-uuid@^3.3.2:- version "3.4.0"- resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"- integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==+uuid@^7.0.3:+ version "7.0.3"+ resolved "https://registry.yarnpkg.com/uuid/-/uuid-7.0.3.tgz#c5c9f2c8cf25dc0a372c4df1441c41f5bd0c680b"+ integrity sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==-which@^1.2.9, which@^1.3.0:- version "1.3.1"- resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"- integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==+which@^2.0.1, which@^2.0.2:+ version "2.0.2"+ resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1"+ integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==dependencies:isexe "^2.0.0"+with-open-file@^0.1.6:+ version "0.1.7"+ resolved "https://registry.yarnpkg.com/with-open-file/-/with-open-file-0.1.7.tgz#e2de8d974e8a8ae6e58886be4fe8e7465b58a729"+ integrity sha512-ecJS2/oHtESJ1t3ZfMI3B7KIDKyfN0O16miWxdn30zdh66Yd3LsRFebXZXq6GU4xfxLf6nVxp9kIqElb5fqczA==+ dependencies:+ p-finally "^1.0.0"+ p-try "^2.1.0"+ pify "^4.0.1"+wrappy@1:version "1.0.2"resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=-xcode@^2.0.0:- version "2.1.0"- resolved "https://registry.yarnpkg.com/xcode/-/xcode-2.1.0.tgz#bab64a7e954bb50ca8d19da7e09531c65a43ecfe"- integrity sha512-uCrmPITrqTEzhn0TtT57fJaNaw8YJs1aCzs+P/QqxsDbvPZSv7XMPPwXrKvHtD6pLjBM/NaVwraWJm8q83Y4iQ==+xcode@^3.0.1:+ version "3.0.1"+ resolved "https://registry.yarnpkg.com/xcode/-/xcode-3.0.1.tgz#3efb62aac641ab2c702458f9a0302696146aa53c"+ integrity sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA==dependencies:- simple-plist "^1.0.0"- uuid "^3.3.2"+ simple-plist "^1.1.0"+ uuid "^7.0.3"xml-escape@^1.1.0:version "1.1.0"resolved "https://registry.yarnpkg.com/xml-escape/-/xml-escape-1.1.0.tgz#3904c143fa8eb3a0030ec646d2902a2f1b706c44"integrity sha1-OQTBQ/qOs6ADDsZG0pAqLxtwbEQ=- version "8.2.2"- resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-8.2.2.tgz#69248673410b4ba42e1a6136551d2922335aa773"- integrity sha1-aSSGc0ELS6QuGmE2VR0pIjNap3M=-xmlbuilder@^9.0.7:version "9.0.7"resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-9.0.7.tgz#132ee63d2ec5565c557e20f4c22df9aca686b10d"