diff --git a/capacitor.config.json b/capacitor.config.json new file mode 100644 index 0000000..1bde2ab --- /dev/null +++ b/capacitor.config.json @@ -0,0 +1,10 @@ +{ + "appId": "org.erplibre.table.tournante", + "appName": "Gestion Table Tournante Libre", + "webDir": "dist", + "bundledWebRuntime": false, + "server": { + "url": "http://localhost:3000", + "cleartextTraffic": true + } +} \ No newline at end of file diff --git a/capacitor.config.ts b/capacitor.config.ts deleted file mode 100644 index 4d7638d..0000000 --- a/capacitor.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { CapacitorConfig } from '@capacitor/cli'; - -const config: CapacitorConfig = { - appId: 'org.erplibre.table.tournante', - appName: 'Gestion Table Tournante Libre', - webDir: 'www', - server: { - androidScheme: 'https' - } -}; - -export default config; diff --git a/node_modules/.bin/tsc b/node_modules/.bin/tsc deleted file mode 120000 index 0863208..0000000 --- a/node_modules/.bin/tsc +++ /dev/null @@ -1 +0,0 @@ -../typescript/bin/tsc \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 71313ad..28a1689 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -4,6 +4,15 @@ "lockfileVersion": 3, "requires": true, "packages": { + "node_modules/@capacitor/android": { + "version": "5.7.8", + "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-5.7.8.tgz", + "integrity": "sha512-ooWclwcuW0dy3YfqgoozkHkjatX8H2fb2/RwRsJa3cew1P1lUXIXri3Dquuy4LdqFAJA7UHcJ19Bl/6UKdsZYA==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^5.7.0" + } + }, "node_modules/@capacitor/app": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/@capacitor/app/-/app-5.0.8.tgz", @@ -55,6 +64,15 @@ "tslib": "^2.1.0" } }, + "node_modules/@capacitor/ios": { + "version": "5.7.8", + "resolved": "https://registry.npmjs.org/@capacitor/ios/-/ios-5.7.8.tgz", + "integrity": "sha512-XhGrziBnlRmCJ97LdPXOJquHPpYTwSJZIxYSXuPl7SDDuAEve8vs2wY76gLdaaFH2Z6ctdugUX+jR6VNu+ds+w==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^5.7.0" + } + }, "node_modules/@ionic/cli-framework-output": { "version": "2.2.8", "resolved": "https://registry.npmjs.org/@ionic/cli-framework-output/-/cli-framework-output-2.2.8.tgz", @@ -256,23 +274,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@typescript/typescript-linux-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", - "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=16.20.0" - } - }, "node_modules/@xmldom/xmldom": { "version": "0.9.12", "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz", @@ -1125,41 +1126,6 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, - "node_modules/typescript": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", - "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc" - }, - "engines": { - "node": ">=16.20.0" - }, - "optionalDependencies": { - "@typescript/typescript-aix-ppc64": "7.0.2", - "@typescript/typescript-darwin-arm64": "7.0.2", - "@typescript/typescript-darwin-x64": "7.0.2", - "@typescript/typescript-freebsd-arm64": "7.0.2", - "@typescript/typescript-freebsd-x64": "7.0.2", - "@typescript/typescript-linux-arm": "7.0.2", - "@typescript/typescript-linux-arm64": "7.0.2", - "@typescript/typescript-linux-loong64": "7.0.2", - "@typescript/typescript-linux-mips64el": "7.0.2", - "@typescript/typescript-linux-ppc64": "7.0.2", - "@typescript/typescript-linux-riscv64": "7.0.2", - "@typescript/typescript-linux-s390x": "7.0.2", - "@typescript/typescript-linux-x64": "7.0.2", - "@typescript/typescript-netbsd-arm64": "7.0.2", - "@typescript/typescript-netbsd-x64": "7.0.2", - "@typescript/typescript-openbsd-arm64": "7.0.2", - "@typescript/typescript-openbsd-x64": "7.0.2", - "@typescript/typescript-sunos-x64": "7.0.2", - "@typescript/typescript-win32-arm64": "7.0.2", - "@typescript/typescript-win32-x64": "7.0.2" - } - }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", diff --git a/node_modules/@capacitor/android/LICENSE b/node_modules/@capacitor/android/LICENSE new file mode 100644 index 0000000..c3e903b --- /dev/null +++ b/node_modules/@capacitor/android/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-present Drifty Co. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall 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. diff --git a/node_modules/@capacitor/android/capacitor/build.gradle b/node_modules/@capacitor/android/capacitor/build.gradle new file mode 100644 index 0000000..5e2a401 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/build.gradle @@ -0,0 +1,96 @@ +ext { + androidxActivityVersion = project.hasProperty('androidxActivityVersion') ? rootProject.ext.androidxActivityVersion : '1.7.0' + androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.6.1' + androidxCoordinatorLayoutVersion = project.hasProperty('androidxCoordinatorLayoutVersion') ? rootProject.ext.androidxCoordinatorLayoutVersion : '1.2.0' + androidxCoreVersion = project.hasProperty('androidxCoreVersion') ? rootProject.ext.androidxCoreVersion : '1.10.0' + androidxFragmentVersion = project.hasProperty('androidxFragmentVersion') ? rootProject.ext.androidxFragmentVersion : '1.5.6' + androidxWebkitVersion = project.hasProperty('androidxWebkitVersion') ? rootProject.ext.androidxWebkitVersion : '1.6.1' + junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2' + androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.1.5' + androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.5.1' + cordovaAndroidVersion = project.hasProperty('cordovaAndroidVersion') ? rootProject.ext.cordovaAndroidVersion : '10.1.1' +} + + +buildscript { + ext.kotlin_version = project.hasProperty("kotlin_version") ? rootProject.ext.kotlin_version : '1.8.20' + repositories { + google() + mavenCentral() + maven { + url "https://plugins.gradle.org/m2/" + } + } + dependencies { + classpath 'com.android.tools.build:gradle:8.0.0' + + if (System.getenv("CAP_PUBLISH") == "true") { + classpath 'io.github.gradle-nexus:publish-plugin:1.3.0' + } + } +} + +tasks.withType(Javadoc).all { enabled = false } + +apply plugin: 'com.android.library' + +if (System.getenv("CAP_PUBLISH") == "true") { + apply plugin: 'io.github.gradle-nexus.publish-plugin' + apply from: file('../scripts/publish-root.gradle') + apply from: file('../scripts/publish-module.gradle') +} + +android { + namespace "com.getcapacitor.android" + compileSdkVersion project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 33 + defaultConfig { + minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22 + targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 33 + versionCode 1 + versionName "1.0" + consumerProguardFiles 'proguard-rules.pro' + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + lintOptions { + baseline file("lint-baseline.xml") + abortOnError true + warningsAsErrors true + lintConfig file('lint.xml') + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + publishing { + singleVariant("release") + } +} + +repositories { + google() + mavenCentral() +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version") + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.core:core:$androidxCoreVersion" + implementation "androidx.activity:activity:$androidxActivityVersion" + implementation "androidx.fragment:fragment:$androidxFragmentVersion" + implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" + implementation "androidx.webkit:webkit:$androidxWebkitVersion" + testImplementation "junit:junit:$junitVersion" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" + implementation "org.apache.cordova:framework:$cordovaAndroidVersion" + testImplementation 'org.json:json:20231013' + testImplementation 'org.mockito:mockito-inline:5.2.0' +} + diff --git a/node_modules/@capacitor/android/capacitor/lint-baseline.xml b/node_modules/@capacitor/android/capacitor/lint-baseline.xml new file mode 100644 index 0000000..c1ed9cc --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/lint-baseline.xml @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/node_modules/@capacitor/android/capacitor/lint.xml b/node_modules/@capacitor/android/capacitor/lint.xml new file mode 100644 index 0000000..b00604b --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/lint.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/node_modules/@capacitor/android/capacitor/proguard-rules.pro b/node_modules/@capacitor/android/capacitor/proguard-rules.pro new file mode 100644 index 0000000..96db065 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/proguard-rules.pro @@ -0,0 +1,28 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Rules for Capacitor v3 plugins and annotations + -keep @com.getcapacitor.annotation.CapacitorPlugin public class * { + @com.getcapacitor.annotation.PermissionCallback ; + @com.getcapacitor.annotation.ActivityCallback ; + @com.getcapacitor.annotation.Permission ; + @com.getcapacitor.PluginMethod public ; + } + + -keep public class * extends com.getcapacitor.Plugin { *; } + +# Rules for Capacitor v2 plugins and annotations +# These are deprecated but can still be used with Capacitor for now +-keep @com.getcapacitor.NativePlugin public class * { + @com.getcapacitor.PluginMethod public ; +} + +# Rules for Cordova plugins +-keep public class * extends org.apache.cordova.* { + public ; + public ; +} \ No newline at end of file diff --git a/node_modules/@capacitor/android/capacitor/src/main/AndroidManifest.xml b/node_modules/@capacitor/android/capacitor/src/main/AndroidManifest.xml new file mode 100644 index 0000000..74b7379 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/node_modules/@capacitor/android/capacitor/src/main/assets/native-bridge.js b/node_modules/@capacitor/android/capacitor/src/main/assets/native-bridge.js new file mode 100644 index 0000000..44ca340 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/assets/native-bridge.js @@ -0,0 +1,1043 @@ + +/*! Capacitor: https://capacitorjs.com/ - MIT License */ +/* Generated File. Do not edit. */ + +var nativeBridge = (function (exports) { + 'use strict'; + + var ExceptionCode; + (function (ExceptionCode) { + /** + * API is not implemented. + * + * This usually means the API can't be used because it is not implemented for + * the current platform. + */ + ExceptionCode["Unimplemented"] = "UNIMPLEMENTED"; + /** + * API is not available. + * + * This means the API can't be used right now because: + * - it is currently missing a prerequisite, such as network connectivity + * - it requires a particular platform or browser version + */ + ExceptionCode["Unavailable"] = "UNAVAILABLE"; + })(ExceptionCode || (ExceptionCode = {})); + class CapacitorException extends Error { + constructor(message, code, data) { + super(message); + this.message = message; + this.code = code; + this.data = data; + } + } + + // For removing exports for iOS/Android, keep let for reassignment + // eslint-disable-next-line + let dummy = {}; + const readFileAsBase64 = (file) => new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + const data = reader.result; + resolve(btoa(data)); + }; + reader.onerror = reject; + reader.readAsBinaryString(file); + }); + const convertFormData = async (formData) => { + const newFormData = []; + for (const pair of formData.entries()) { + const [key, value] = pair; + if (value instanceof File) { + const base64File = await readFileAsBase64(value); + newFormData.push({ + key, + value: base64File, + type: 'base64File', + contentType: value.type, + fileName: value.name, + }); + } + else { + newFormData.push({ key, value, type: 'string' }); + } + } + return newFormData; + }; + const convertBody = async (body, contentType) => { + if (body instanceof ReadableStream || body instanceof Uint8Array) { + let encodedData; + if (body instanceof ReadableStream) { + const reader = body.getReader(); + const chunks = []; + while (true) { + const { done, value } = await reader.read(); + if (done) + break; + chunks.push(value); + } + const concatenated = new Uint8Array(chunks.reduce((acc, chunk) => acc + chunk.length, 0)); + let position = 0; + for (const chunk of chunks) { + concatenated.set(chunk, position); + position += chunk.length; + } + encodedData = concatenated; + } + else { + encodedData = body; + } + let data = new TextDecoder().decode(encodedData); + let type; + if (contentType === 'application/json') { + try { + data = JSON.parse(data); + } + catch (ignored) { + // ignore + } + type = 'json'; + } + else if (contentType === 'multipart/form-data') { + type = 'formData'; + } + else if (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('image')) { + type = 'image'; + } + else if (contentType === 'application/octet-stream') { + type = 'binary'; + } + else { + type = 'text'; + } + return { + data, + type, + headers: { 'Content-Type': contentType || 'application/octet-stream' }, + }; + } + else if (body instanceof URLSearchParams) { + return { + data: body.toString(), + type: 'text', + }; + } + else if (body instanceof FormData) { + const formData = await convertFormData(body); + const boundary = `${Date.now()}`; + return { + data: formData, + type: 'formData', + headers: { + 'Content-Type': `multipart/form-data; boundary=--${boundary}`, + }, + }; + } + else if (body instanceof File) { + const fileData = await readFileAsBase64(body); + return { + data: fileData, + type: 'file', + headers: { 'Content-Type': body.type }, + }; + } + return { data: body, type: 'json' }; + }; + const CAPACITOR_HTTP_INTERCEPTOR = '/_capacitor_http_interceptor_'; + const CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM = 'u'; + // TODO: export as Cap function + const isRelativeOrProxyUrl = (url) => !url || + !(url.startsWith('http:') || url.startsWith('https:')) || + url.indexOf(CAPACITOR_HTTP_INTERCEPTOR) > -1; + // TODO: export as Cap function + const createProxyUrl = (url, win) => { + var _a, _b; + if (isRelativeOrProxyUrl(url)) + return url; + const bridgeUrl = new URL((_b = (_a = win.Capacitor) === null || _a === void 0 ? void 0 : _a.getServerUrl()) !== null && _b !== void 0 ? _b : ''); + bridgeUrl.pathname = CAPACITOR_HTTP_INTERCEPTOR; + bridgeUrl.searchParams.append(CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM, url); + return bridgeUrl.toString(); + }; + const initBridge = (w) => { + const getPlatformId = (win) => { + var _a, _b; + if (win === null || win === void 0 ? void 0 : win.androidBridge) { + return 'android'; + } + else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) { + return 'ios'; + } + else { + return 'web'; + } + }; + const convertFileSrcServerUrl = (webviewServerUrl, filePath) => { + if (typeof filePath === 'string') { + if (filePath.startsWith('/')) { + return webviewServerUrl + '/_capacitor_file_' + filePath; + } + else if (filePath.startsWith('file://')) { + return (webviewServerUrl + filePath.replace('file://', '/_capacitor_file_')); + } + else if (filePath.startsWith('content://')) { + return (webviewServerUrl + + filePath.replace('content:/', '/_capacitor_content_')); + } + } + return filePath; + }; + const initEvents = (win, cap) => { + cap.addListener = (pluginName, eventName, callback) => { + const callbackId = cap.nativeCallback(pluginName, 'addListener', { + eventName: eventName, + }, callback); + return { + remove: async () => { + var _a; + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.debug('Removing listener', pluginName, eventName); + cap.removeListener(pluginName, callbackId, eventName, callback); + }, + }; + }; + cap.removeListener = (pluginName, callbackId, eventName, callback) => { + cap.nativeCallback(pluginName, 'removeListener', { + callbackId: callbackId, + eventName: eventName, + }, callback); + }; + cap.createEvent = (eventName, eventData) => { + const doc = win.document; + if (doc) { + const ev = doc.createEvent('Events'); + ev.initEvent(eventName, false, false); + if (eventData && typeof eventData === 'object') { + for (const i in eventData) { + // eslint-disable-next-line no-prototype-builtins + if (eventData.hasOwnProperty(i)) { + ev[i] = eventData[i]; + } + } + } + return ev; + } + return null; + }; + cap.triggerEvent = (eventName, target, eventData) => { + const doc = win.document; + const cordova = win.cordova; + eventData = eventData || {}; + const ev = cap.createEvent(eventName, eventData); + if (ev) { + if (target === 'document') { + if (cordova === null || cordova === void 0 ? void 0 : cordova.fireDocumentEvent) { + cordova.fireDocumentEvent(eventName, eventData); + return true; + } + else if (doc === null || doc === void 0 ? void 0 : doc.dispatchEvent) { + return doc.dispatchEvent(ev); + } + } + else if (target === 'window' && win.dispatchEvent) { + return win.dispatchEvent(ev); + } + else if (doc === null || doc === void 0 ? void 0 : doc.querySelector) { + const targetEl = doc.querySelector(target); + if (targetEl) { + return targetEl.dispatchEvent(ev); + } + } + } + return false; + }; + win.Capacitor = cap; + }; + const initLegacyHandlers = (win, cap) => { + // define cordova if it's not there already + win.cordova = win.cordova || {}; + const doc = win.document; + const nav = win.navigator; + if (nav) { + nav.app = nav.app || {}; + nav.app.exitApp = () => { + var _a; + if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) { + win.console.warn('App plugin not installed'); + } + else { + cap.nativeCallback('App', 'exitApp', {}); + } + }; + } + if (doc) { + const docAddEventListener = doc.addEventListener; + doc.addEventListener = (...args) => { + var _a; + const eventName = args[0]; + const handler = args[1]; + if (eventName === 'deviceready' && handler) { + Promise.resolve().then(handler); + } + else if (eventName === 'backbutton' && cap.Plugins.App) { + // Add a dummy listener so Capacitor doesn't do the default + // back button action + if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) { + win.console.warn('App plugin not installed'); + } + else { + cap.Plugins.App.addListener('backButton', () => { + // ignore + }); + } + } + return docAddEventListener.apply(doc, args); + }; + } + // deprecated in v3, remove from v4 + cap.platform = cap.getPlatform(); + cap.isNative = cap.isNativePlatform(); + win.Capacitor = cap; + }; + const initVendor = (win, cap) => { + const Ionic = (win.Ionic = win.Ionic || {}); + const IonicWebView = (Ionic.WebView = Ionic.WebView || {}); + const Plugins = cap.Plugins; + IonicWebView.getServerBasePath = (callback) => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.getServerBasePath().then((result) => { + callback(result.path); + }); + }; + IonicWebView.setServerAssetPath = (path) => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.setServerAssetPath({ path }); + }; + IonicWebView.setServerBasePath = (path) => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.setServerBasePath({ path }); + }; + IonicWebView.persistServerBasePath = () => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.persistServerBasePath(); + }; + IonicWebView.convertFileSrc = (url) => cap.convertFileSrc(url); + win.Capacitor = cap; + win.Ionic.WebView = IonicWebView; + }; + const initLogger = (win, cap) => { + const BRIDGED_CONSOLE_METHODS = [ + 'debug', + 'error', + 'info', + 'log', + 'trace', + 'warn', + ]; + const createLogFromNative = (c) => (result) => { + if (isFullConsole(c)) { + const success = result.success === true; + const tagStyles = success + ? 'font-style: italic; font-weight: lighter; color: gray' + : 'font-style: italic; font-weight: lighter; color: red'; + c.groupCollapsed('%cresult %c' + + result.pluginId + + '.' + + result.methodName + + ' (#' + + result.callbackId + + ')', tagStyles, 'font-style: italic; font-weight: bold; color: #444'); + if (result.success === false) { + c.error(result.error); + } + else { + c.dir(result.data); + } + c.groupEnd(); + } + else { + if (result.success === false) { + c.error('LOG FROM NATIVE', result.error); + } + else { + c.log('LOG FROM NATIVE', result.data); + } + } + }; + const createLogToNative = (c) => (call) => { + if (isFullConsole(c)) { + c.groupCollapsed('%cnative %c' + + call.pluginId + + '.' + + call.methodName + + ' (#' + + call.callbackId + + ')', 'font-weight: lighter; color: gray', 'font-weight: bold; color: #000'); + c.dir(call); + c.groupEnd(); + } + else { + c.log('LOG TO NATIVE: ', call); + } + }; + const isFullConsole = (c) => { + if (!c) { + return false; + } + return (typeof c.groupCollapsed === 'function' || + typeof c.groupEnd === 'function' || + typeof c.dir === 'function'); + }; + const serializeConsoleMessage = (msg) => { + try { + if (typeof msg === 'object') { + msg = JSON.stringify(msg); + } + return String(msg); + } + catch (e) { + return ''; + } + }; + const platform = getPlatformId(win); + if (platform == 'android' || platform == 'ios') { + // patch document.cookie on Android/iOS + win.CapacitorCookiesDescriptor = + Object.getOwnPropertyDescriptor(Document.prototype, 'cookie') || + Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'cookie'); + let doPatchCookies = false; + // check if capacitor cookies is disabled before patching + if (platform === 'ios') { + // Use prompt to synchronously get capacitor cookies config. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorCookies.isEnabled', + }; + const isCookiesEnabled = prompt(JSON.stringify(payload)); + if (isCookiesEnabled === 'true') { + doPatchCookies = true; + } + } + else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { + const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled(); + if (isCookiesEnabled === true) { + doPatchCookies = true; + } + } + if (doPatchCookies) { + Object.defineProperty(document, 'cookie', { + get: function () { + var _a, _b, _c; + if (platform === 'ios') { + // Use prompt to synchronously get cookies. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorCookies.get', + }; + const res = prompt(JSON.stringify(payload)); + return res; + } + else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { + // return original document.cookie since Android does not support filtering of `httpOnly` cookies + return (_c = (_b = (_a = win.CapacitorCookiesDescriptor) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(document)) !== null && _c !== void 0 ? _c : ''; + } + }, + set: function (val) { + const cookiePairs = val.split(';'); + const domainSection = val.toLowerCase().split('domain=')[1]; + const domain = cookiePairs.length > 1 && + domainSection != null && + domainSection.length > 0 + ? domainSection.split(';')[0].trim() + : ''; + if (platform === 'ios') { + // Use prompt to synchronously set cookies. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorCookies.set', + action: val, + domain, + }; + prompt(JSON.stringify(payload)); + } + else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { + win.CapacitorCookiesAndroidInterface.setCookie(domain, val); + } + }, + }); + } + // patch fetch / XHR on Android/iOS + // store original fetch & XHR functions + win.CapacitorWebFetch = window.fetch; + win.CapacitorWebXMLHttpRequest = { + abort: window.XMLHttpRequest.prototype.abort, + constructor: window.XMLHttpRequest.prototype.constructor, + fullObject: window.XMLHttpRequest, + getAllResponseHeaders: window.XMLHttpRequest.prototype.getAllResponseHeaders, + getResponseHeader: window.XMLHttpRequest.prototype.getResponseHeader, + open: window.XMLHttpRequest.prototype.open, + prototype: window.XMLHttpRequest.prototype, + send: window.XMLHttpRequest.prototype.send, + setRequestHeader: window.XMLHttpRequest.prototype.setRequestHeader, + }; + let doPatchHttp = false; + // check if capacitor http is disabled before patching + if (platform === 'ios') { + // Use prompt to synchronously get capacitor http config. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorHttp', + }; + const isHttpEnabled = prompt(JSON.stringify(payload)); + if (isHttpEnabled === 'true') { + doPatchHttp = true; + } + } + else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') { + const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled(); + if (isHttpEnabled === true) { + doPatchHttp = true; + } + } + if (doPatchHttp) { + // fetch patch + window.fetch = async (resource, options) => { + const request = new Request(resource, options); + if (request.url.startsWith(`${cap.getServerUrl()}/`)) { + return win.CapacitorWebFetch(resource, options); + } + const { method } = request; + if (method.toLocaleUpperCase() === 'GET' || + method.toLocaleUpperCase() === 'HEAD' || + method.toLocaleUpperCase() === 'OPTIONS' || + method.toLocaleUpperCase() === 'TRACE') { + if (typeof resource === 'string') { + return await win.CapacitorWebFetch(createProxyUrl(resource, win), options); + } + else if (resource instanceof Request) { + const modifiedRequest = new Request(createProxyUrl(resource.url, win), resource); + return await win.CapacitorWebFetch(modifiedRequest, options); + } + } + const tag = `CapacitorHttp fetch ${Date.now()} ${resource}`; + console.time(tag); + try { + const { body } = request; + const optionHeaders = Object.fromEntries(request.headers.entries()); + const { data: requestData, type, headers, } = await convertBody((options === null || options === void 0 ? void 0 : options.body) || body || undefined, optionHeaders['Content-Type'] || optionHeaders['content-type']); + const nativeResponse = await cap.nativePromise('CapacitorHttp', 'request', { + url: request.url, + method: method, + data: requestData, + dataType: type, + headers: Object.assign(Object.assign({}, headers), optionHeaders), + }); + const contentType = nativeResponse.headers['Content-Type'] || + nativeResponse.headers['content-type']; + let data = (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('application/json')) + ? JSON.stringify(nativeResponse.data) + : nativeResponse.data; + // use null data for 204 No Content HTTP response + if (nativeResponse.status === 204) { + data = null; + } + // intercept & parse response before returning + const response = new Response(data, { + headers: nativeResponse.headers, + status: nativeResponse.status, + }); + /* + * copy url to response, `cordova-plugin-ionic` uses this url from the response + * we need `Object.defineProperty` because url is an inherited getter on the Response + * see: https://stackoverflow.com/a/57382543 + * */ + Object.defineProperty(response, 'url', { + value: nativeResponse.url, + }); + console.timeEnd(tag); + return response; + } + catch (error) { + console.timeEnd(tag); + return Promise.reject(error); + } + }; + window.XMLHttpRequest = function () { + const xhr = new win.CapacitorWebXMLHttpRequest.constructor(); + Object.defineProperties(xhr, { + _headers: { + value: {}, + writable: true, + }, + _method: { + value: xhr.method, + writable: true, + }, + }); + const prototype = win.CapacitorWebXMLHttpRequest.prototype; + const isProgressEventAvailable = () => typeof ProgressEvent !== 'undefined' && + ProgressEvent.prototype instanceof Event; + // XHR patch abort + prototype.abort = function () { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.abort.call(this); + } + this.readyState = 0; + setTimeout(() => { + this.dispatchEvent(new Event('abort')); + this.dispatchEvent(new Event('loadend')); + }); + }; + // XHR patch open + prototype.open = function (method, url) { + this._method = method.toLocaleUpperCase(); + this._url = url; + if (!this._method || + this._method === 'GET' || + this._method === 'HEAD' || + this._method === 'OPTIONS' || + this._method === 'TRACE') { + if (isRelativeOrProxyUrl(url)) { + return win.CapacitorWebXMLHttpRequest.open.call(this, method, url); + } + this._url = createProxyUrl(this._url, win); + return win.CapacitorWebXMLHttpRequest.open.call(this, method, this._url); + } + Object.defineProperties(this, { + readyState: { + get: function () { + var _a; + return (_a = this._readyState) !== null && _a !== void 0 ? _a : 0; + }, + set: function (val) { + this._readyState = val; + setTimeout(() => { + this.dispatchEvent(new Event('readystatechange')); + }); + }, + }, + }); + setTimeout(() => { + this.dispatchEvent(new Event('loadstart')); + }); + this.readyState = 1; + }; + // XHR patch set request header + prototype.setRequestHeader = function (header, value) { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.setRequestHeader.call(this, header, value); + } + this._headers[header] = value; + }; + // XHR patch send + prototype.send = function (body) { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.send.call(this, body); + } + const tag = `CapacitorHttp XMLHttpRequest ${Date.now()} ${this._url}`; + console.time(tag); + try { + this.readyState = 2; + Object.defineProperties(this, { + response: { + value: '', + writable: true, + }, + responseText: { + value: '', + writable: true, + }, + responseURL: { + value: '', + writable: true, + }, + status: { + value: 0, + writable: true, + }, + }); + convertBody(body).then(({ data, type, headers }) => { + const otherHeaders = this._headers != null && Object.keys(this._headers).length > 0 + ? this._headers + : undefined; + // intercept request & pass to the bridge + cap + .nativePromise('CapacitorHttp', 'request', { + url: this._url, + method: this._method, + data: data !== null ? data : undefined, + headers: Object.assign(Object.assign({}, headers), otherHeaders), + dataType: type, + }) + .then((nativeResponse) => { + var _a; + // intercept & parse response before returning + if (this.readyState == 2) { + //TODO: Add progress event emission on native side + if (isProgressEventAvailable()) { + this.dispatchEvent(new ProgressEvent('progress', { + lengthComputable: true, + loaded: nativeResponse.data.length, + total: nativeResponse.data.length, + })); + } + this._headers = nativeResponse.headers; + this.status = nativeResponse.status; + const responseString = typeof nativeResponse.data !== 'string' + ? JSON.stringify(nativeResponse.data) + : nativeResponse.data; + if (this.responseType === '' || + this.responseType === 'text') { + this.response = responseString; + } + else if (this.responseType === 'blob') { + this.response = new Blob([responseString], { + type: 'application/json', + }); + } + else if (this.responseType === 'arraybuffer') { + const encoder = new TextEncoder(); + const uint8Array = encoder.encode(responseString); + this.response = uint8Array.buffer; + } + else { + this.response = nativeResponse.data; + } + this.responseText = ((_a = nativeResponse.headers['Content-Type']) === null || _a === void 0 ? void 0 : _a.startsWith('application/json')) + ? JSON.stringify(nativeResponse.data) + : nativeResponse.data; + this.responseURL = nativeResponse.url; + this.readyState = 4; + setTimeout(() => { + this.dispatchEvent(new Event('load')); + this.dispatchEvent(new Event('loadend')); + }); + } + console.timeEnd(tag); + }) + .catch((error) => { + this.status = error.status; + this._headers = error.headers; + this.response = error.data; + this.responseText = JSON.stringify(error.data); + this.responseURL = error.url; + this.readyState = 4; + if (isProgressEventAvailable()) { + this.dispatchEvent(new ProgressEvent('progress', { + lengthComputable: false, + loaded: 0, + total: 0, + })); + } + setTimeout(() => { + this.dispatchEvent(new Event('error')); + this.dispatchEvent(new Event('loadend')); + }); + console.timeEnd(tag); + }); + }); + } + catch (error) { + this.status = 500; + this._headers = {}; + this.response = error; + this.responseText = error.toString(); + this.responseURL = this._url; + this.readyState = 4; + if (isProgressEventAvailable()) { + this.dispatchEvent(new ProgressEvent('progress', { + lengthComputable: false, + loaded: 0, + total: 0, + })); + } + setTimeout(() => { + this.dispatchEvent(new Event('error')); + this.dispatchEvent(new Event('loadend')); + }); + console.timeEnd(tag); + } + }; + // XHR patch getAllResponseHeaders + prototype.getAllResponseHeaders = function () { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.getAllResponseHeaders.call(this); + } + let returnString = ''; + for (const key in this._headers) { + if (key.toLowerCase() !== 'set-cookie') { + returnString += key + ': ' + this._headers[key] + '\r\n'; + } + } + return returnString; + }; + // XHR patch getResponseHeader + prototype.getResponseHeader = function (name) { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.getResponseHeader.call(this, name); + } + for (const key in this._headers) { + if (key.toLowerCase() === name.toLowerCase()) { + return this._headers[key]; + } + } + return null; + }; + Object.setPrototypeOf(xhr, prototype); + return xhr; + }; + Object.assign(window.XMLHttpRequest, win.CapacitorWebXMLHttpRequest.fullObject); + } + } + // patch window.console on iOS and store original console fns + const isIos = getPlatformId(win) === 'ios'; + if (win.console && isIos) { + Object.defineProperties(win.console, BRIDGED_CONSOLE_METHODS.reduce((props, method) => { + const consoleMethod = win.console[method].bind(win.console); + props[method] = { + value: (...args) => { + const msgs = [...args]; + cap.toNative('Console', 'log', { + level: method, + message: msgs.map(serializeConsoleMessage).join(' '), + }); + return consoleMethod(...args); + }, + }; + return props; + }, {})); + } + cap.logJs = (msg, level) => { + switch (level) { + case 'error': + win.console.error(msg); + break; + case 'warn': + win.console.warn(msg); + break; + case 'info': + win.console.info(msg); + break; + default: + win.console.log(msg); + } + }; + cap.logToNative = createLogToNative(win.console); + cap.logFromNative = createLogFromNative(win.console); + cap.handleError = err => win.console.error(err); + win.Capacitor = cap; + }; + function initNativeBridge(win) { + const cap = win.Capacitor || {}; + // keep a collection of callbacks for native response data + const callbacks = new Map(); + const webviewServerUrl = typeof win.WEBVIEW_SERVER_URL === 'string' ? win.WEBVIEW_SERVER_URL : ''; + cap.getServerUrl = () => webviewServerUrl; + cap.convertFileSrc = filePath => convertFileSrcServerUrl(webviewServerUrl, filePath); + // Counter of callback ids, randomized to avoid + // any issues during reloads if a call comes back with + // an existing callback id from an old session + let callbackIdCount = Math.floor(Math.random() * 134217728); + let postToNative = null; + const isNativePlatform = () => true; + const getPlatform = () => getPlatformId(win); + cap.getPlatform = getPlatform; + cap.isPluginAvailable = name => Object.prototype.hasOwnProperty.call(cap.Plugins, name); + cap.isNativePlatform = isNativePlatform; + // create the postToNative() fn if needed + if (getPlatformId(win) === 'android') { + // android platform + postToNative = data => { + var _a; + try { + win.androidBridge.postMessage(JSON.stringify(data)); + } + catch (e) { + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e); + } + }; + } + else if (getPlatformId(win) === 'ios') { + // ios platform + postToNative = data => { + var _a; + try { + data.type = data.type ? data.type : 'message'; + win.webkit.messageHandlers.bridge.postMessage(data); + } + catch (e) { + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e); + } + }; + } + cap.handleWindowError = (msg, url, lineNo, columnNo, err) => { + const str = msg.toLowerCase(); + if (str.indexOf('script error') > -1) ; + else { + const errObj = { + type: 'js.error', + error: { + message: msg, + url: url, + line: lineNo, + col: columnNo, + errorObject: JSON.stringify(err), + }, + }; + if (err !== null) { + cap.handleError(err); + } + postToNative(errObj); + } + return false; + }; + if (cap.DEBUG) { + window.onerror = cap.handleWindowError; + } + initLogger(win, cap); + /** + * Send a plugin method call to the native layer + */ + cap.toNative = (pluginName, methodName, options, storedCallback) => { + var _a, _b; + try { + if (typeof postToNative === 'function') { + let callbackId = '-1'; + if (storedCallback && + (typeof storedCallback.callback === 'function' || + typeof storedCallback.resolve === 'function')) { + // store the call for later lookup + callbackId = String(++callbackIdCount); + callbacks.set(callbackId, storedCallback); + } + const callData = { + callbackId: callbackId, + pluginId: pluginName, + methodName: methodName, + options: options || {}, + }; + if (cap.isLoggingEnabled && pluginName !== 'Console') { + cap.logToNative(callData); + } + // post the call data to native + postToNative(callData); + return callbackId; + } + else { + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(`implementation unavailable for: ${pluginName}`); + } + } + catch (e) { + (_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e); + } + return null; + }; + if (win === null || win === void 0 ? void 0 : win.androidBridge) { + win.androidBridge.onmessage = function (event) { + returnResult(JSON.parse(event.data)); + }; + } + /** + * Process a response from the native layer. + */ + cap.fromNative = result => { + returnResult(result); + }; + const returnResult = (result) => { + var _a, _b; + if (cap.isLoggingEnabled && result.pluginId !== 'Console') { + cap.logFromNative(result); + } + // get the stored call, if it exists + try { + const storedCall = callbacks.get(result.callbackId); + if (storedCall) { + // looks like we've got a stored call + if (result.error) { + // ensure stacktraces by copying error properties to an Error + result.error = Object.keys(result.error).reduce((err, key) => { + // use any type to avoid importing util and compiling most of .ts files + err[key] = result.error[key]; + return err; + }, new cap.Exception('')); + } + if (typeof storedCall.callback === 'function') { + // callback + if (result.success) { + storedCall.callback(result.data); + } + else { + storedCall.callback(null, result.error); + } + } + else if (typeof storedCall.resolve === 'function') { + // promise + if (result.success) { + storedCall.resolve(result.data); + } + else { + storedCall.reject(result.error); + } + // no need to keep this stored callback + // around for a one time resolve promise + callbacks.delete(result.callbackId); + } + } + else if (!result.success && result.error) { + // no stored callback, but if there was an error let's log it + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(result.error); + } + if (result.save === false) { + callbacks.delete(result.callbackId); + } + } + catch (e) { + (_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e); + } + // always delete to prevent memory leaks + // overkill but we're not sure what apps will do with this data + delete result.data; + delete result.error; + }; + cap.nativeCallback = (pluginName, methodName, options, callback) => { + if (typeof options === 'function') { + console.warn(`Using a callback as the 'options' parameter of 'nativeCallback()' is deprecated.`); + callback = options; + options = null; + } + return cap.toNative(pluginName, methodName, options, { callback }); + }; + cap.nativePromise = (pluginName, methodName, options) => { + return new Promise((resolve, reject) => { + cap.toNative(pluginName, methodName, options, { + resolve: resolve, + reject: reject, + }); + }); + }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + cap.withPlugin = (_pluginId, _fn) => dummy; + cap.Exception = CapacitorException; + initEvents(win, cap); + initLegacyHandlers(win, cap); + initVendor(win, cap); + win.Capacitor = cap; + } + initNativeBridge(w); + }; + initBridge(typeof globalThis !== 'undefined' + ? globalThis + : typeof self !== 'undefined' + ? self + : typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}); + + dummy = initBridge; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/AndroidProtocolHandler.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/AndroidProtocolHandler.java new file mode 100755 index 0000000..df893c7 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/AndroidProtocolHandler.java @@ -0,0 +1,94 @@ +// Copyright 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package com.getcapacitor; + +import android.content.Context; +import android.content.res.AssetManager; +import android.net.Uri; +import android.util.TypedValue; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +public class AndroidProtocolHandler { + + private Context context; + + public AndroidProtocolHandler(Context context) { + this.context = context; + } + + public InputStream openAsset(String path) throws IOException { + return context.getAssets().open(path, AssetManager.ACCESS_STREAMING); + } + + public InputStream openResource(Uri uri) { + assert uri.getPath() != null; + // The path must be of the form ".../asset_type/asset_name.ext". + List pathSegments = uri.getPathSegments(); + String assetType = pathSegments.get(pathSegments.size() - 2); + String assetName = pathSegments.get(pathSegments.size() - 1); + + // Drop the file extension. + assetName = assetName.split("\\.")[0]; + try { + // Use the application context for resolving the resource package name so that we do + // not use the browser's own resources. Note that if 'context' here belongs to the + // test suite, it does not have a separate application context. In that case we use + // the original context object directly. + if (context.getApplicationContext() != null) { + context = context.getApplicationContext(); + } + int fieldId = getFieldId(context, assetType, assetName); + int valueType = getValueType(context, fieldId); + if (valueType == TypedValue.TYPE_STRING) { + return context.getResources().openRawResource(fieldId); + } else { + Logger.error("Asset not of type string: " + uri); + } + } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) { + Logger.error("Unable to open resource URL: " + uri, e); + } + return null; + } + + private static int getFieldId(Context context, String assetType, String assetName) + throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { + Class d = context.getClassLoader().loadClass(context.getPackageName() + ".R$" + assetType); + java.lang.reflect.Field field = d.getField(assetName); + return field.getInt(null); + } + + public InputStream openFile(String filePath) throws IOException { + String realPath = filePath.replace(Bridge.CAPACITOR_FILE_START, ""); + File localFile = new File(realPath); + return new FileInputStream(localFile); + } + + public InputStream openContentUrl(Uri uri) throws IOException { + Integer port = uri.getPort(); + String baseUrl = uri.getScheme() + "://" + uri.getHost(); + if (port != -1) { + baseUrl += ":" + port; + } + String realPath = uri.toString().replace(baseUrl + Bridge.CAPACITOR_CONTENT_START, "content:/"); + + InputStream stream = null; + try { + stream = context.getContentResolver().openInputStream(Uri.parse(realPath)); + } catch (SecurityException e) { + Logger.error("Unable to open content URL: " + uri, e); + } + return stream; + } + + private static int getValueType(Context context, int fieldId) { + TypedValue value = new TypedValue(); + context.getResources().getValue(fieldId, value, true); + return value.type; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/App.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/App.java new file mode 100644 index 0000000..f46b633 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/App.java @@ -0,0 +1,61 @@ +package com.getcapacitor; + +import androidx.annotation.Nullable; + +public class App { + + /** + * Interface for callbacks when app status changes. + */ + public interface AppStatusChangeListener { + void onAppStatusChanged(Boolean isActive); + } + + /** + * Interface for callbacks when app is restored with pending plugin call. + */ + public interface AppRestoredListener { + void onAppRestored(PluginResult result); + } + + @Nullable + private AppStatusChangeListener statusChangeListener; + + @Nullable + private AppRestoredListener appRestoredListener; + + private boolean isActive = false; + + public boolean isActive() { + return isActive; + } + + /** + * Set the object to receive callbacks. + * @param listener + */ + public void setStatusChangeListener(@Nullable AppStatusChangeListener listener) { + this.statusChangeListener = listener; + } + + /** + * Set the object to receive callbacks. + * @param listener + */ + public void setAppRestoredListener(@Nullable AppRestoredListener listener) { + this.appRestoredListener = listener; + } + + protected void fireRestoredResult(PluginResult result) { + if (appRestoredListener != null) { + appRestoredListener.onAppRestored(result); + } + } + + public void fireStatusChange(boolean isActive) { + this.isActive = isActive; + if (statusChangeListener != null) { + statusChangeListener.onAppStatusChanged(isActive); + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/AppUUID.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/AppUUID.java new file mode 100644 index 0000000..3c1b1db --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/AppUUID.java @@ -0,0 +1,65 @@ +package com.getcapacitor; + +import android.content.Context; +import android.content.SharedPreferences; +import androidx.appcompat.app.AppCompatActivity; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Objects; +import java.util.UUID; + +public final class AppUUID { + + private static final String KEY = "CapacitorAppUUID"; + + public static String getAppUUID(AppCompatActivity activity) throws Exception { + assertAppUUID(activity); + return readUUID(activity); + } + + public static void regenerateAppUUID(AppCompatActivity activity) throws Exception { + try { + String uuid = generateUUID(); + writeUUID(activity, uuid); + } catch (NoSuchAlgorithmException ex) { + throw new Exception("Capacitor App UUID could not be generated."); + } + } + + private static void assertAppUUID(AppCompatActivity activity) throws Exception { + String uuid = readUUID(activity); + if (uuid.equals("")) { + regenerateAppUUID(activity); + } + } + + private static String generateUUID() throws NoSuchAlgorithmException { + MessageDigest salt = MessageDigest.getInstance("SHA-256"); + salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8)); + return bytesToHex(salt.digest()); + } + + private static String readUUID(AppCompatActivity activity) { + SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); + return sharedPref.getString(KEY, ""); + } + + private static void writeUUID(AppCompatActivity activity, String uuid) { + SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedPref.edit(); + editor.putString(KEY, uuid); + editor.apply(); + } + + private static String bytesToHex(byte[] bytes) { + byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII); + byte[] hexChars = new byte[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = HEX_ARRAY[v >>> 4]; + hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; + } + return new String(hexChars, StandardCharsets.UTF_8); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Bridge.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Bridge.java new file mode 100644 index 0000000..1313194 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Bridge.java @@ -0,0 +1,1573 @@ +package com.getcapacitor; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.res.Configuration; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.HandlerThread; +import android.webkit.ValueCallback; +import android.webkit.WebSettings; +import android.webkit.WebView; +import androidx.activity.result.ActivityResultCallback; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContract; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.core.content.pm.PackageInfoCompat; +import androidx.fragment.app.Fragment; +import com.getcapacitor.android.R; +import com.getcapacitor.annotation.CapacitorPlugin; +import com.getcapacitor.annotation.Permission; +import com.getcapacitor.cordova.MockCordovaInterfaceImpl; +import com.getcapacitor.cordova.MockCordovaWebViewImpl; +import com.getcapacitor.util.HostMask; +import com.getcapacitor.util.InternalUtils; +import com.getcapacitor.util.PermissionHelper; +import com.getcapacitor.util.WebColor; +import java.io.File; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.cordova.ConfigXmlParser; +import org.apache.cordova.CordovaPreferences; +import org.apache.cordova.CordovaWebView; +import org.apache.cordova.PluginEntry; +import org.apache.cordova.PluginManager; +import org.json.JSONException; + +/** + * The Bridge class is the main engine of Capacitor. It manages + * loading and communicating with all Plugins, + * proxying Native events to Plugins, executing Plugin methods, + * communicating with the WebView, and a whole lot more. + * + * Generally, you'll not use Bridge directly, instead, extend from BridgeActivity + * to get a WebView instance and proxy native events automatically. + * + * If you want to use this Bridge in an existing Android app, please + * see the source for BridgeActivity for the methods you'll need to + * pass through to Bridge: + * + * BridgeActivity.java + */ +public class Bridge { + + private static final String PREFS_NAME = "CapacitorSettings"; + private static final String PERMISSION_PREFS_NAME = "PluginPermStates"; + private static final String BUNDLE_LAST_PLUGIN_ID_KEY = "capacitorLastActivityPluginId"; + private static final String BUNDLE_LAST_PLUGIN_CALL_METHOD_NAME_KEY = "capacitorLastActivityPluginMethod"; + private static final String BUNDLE_PLUGIN_CALL_OPTIONS_SAVED_KEY = "capacitorLastPluginCallOptions"; + private static final String BUNDLE_PLUGIN_CALL_BUNDLE_KEY = "capacitorLastPluginCallBundle"; + private static final String LAST_BINARY_VERSION_CODE = "lastBinaryVersionCode"; + private static final String LAST_BINARY_VERSION_NAME = "lastBinaryVersionName"; + private static final String MINIMUM_ANDROID_WEBVIEW_ERROR = "System WebView is not supported"; + + // The name of the directory we use to look for index.html and the rest of our web assets + public static final String DEFAULT_WEB_ASSET_DIR = "public"; + public static final String CAPACITOR_HTTP_SCHEME = "http"; + public static final String CAPACITOR_HTTPS_SCHEME = "https"; + public static final String CAPACITOR_FILE_START = "/_capacitor_file_"; + public static final String CAPACITOR_CONTENT_START = "/_capacitor_content_"; + public static final String CAPACITOR_HTTP_INTERCEPTOR_START = "/_capacitor_http_interceptor_"; + + /** @deprecated CAPACITOR_HTTPS_INTERCEPTOR_START is no longer required. All proxied requests are handled via CAPACITOR_HTTP_INTERCEPTOR_START instead */ + @Deprecated + public static final String CAPACITOR_HTTPS_INTERCEPTOR_START = "/_capacitor_https_interceptor_"; + + public static final String CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM = "u"; + + public static final int DEFAULT_ANDROID_WEBVIEW_VERSION = 60; + public static final int MINIMUM_ANDROID_WEBVIEW_VERSION = 55; + public static final int DEFAULT_HUAWEI_WEBVIEW_VERSION = 10; + public static final int MINIMUM_HUAWEI_WEBVIEW_VERSION = 10; + + // Loaded Capacitor config + private CapConfig config; + + // A reference to the main activity for the app + private final AppCompatActivity context; + // A reference to the containing Fragment if used + private final Fragment fragment; + private WebViewLocalServer localServer; + private String localUrl; + private String appUrl; + private String appUrlConfig; + private HostMask appAllowNavigationMask; + private Set allowedOriginRules = new HashSet(); + private ArrayList authorities = new ArrayList<>(); + // A reference to the main WebView for the app + private final WebView webView; + public final MockCordovaInterfaceImpl cordovaInterface; + private CordovaWebView cordovaWebView; + private CordovaPreferences preferences; + private BridgeWebViewClient webViewClient; + private App app; + + // Our MessageHandler for sending and receiving data to the WebView + private final MessageHandler msgHandler; + + // The ThreadHandler for executing plugin calls + private final HandlerThread handlerThread = new HandlerThread("CapacitorPlugins"); + + // Our Handler for posting plugin calls. Created from the ThreadHandler + private Handler taskHandler = null; + + private final List> initialPlugins; + + private final List pluginInstances; + + // A map of Plugin Id's to PluginHandle's + private Map plugins = new HashMap<>(); + + // Stored plugin calls that we're keeping around to call again someday + private Map savedCalls = new HashMap<>(); + + // The call IDs of saved plugin calls with associated plugin id for handling permissions + private Map> savedPermissionCallIds = new HashMap<>(); + + // Store a plugin that started a new activity, in case we need to resume + // the app and return that data back + private PluginCall pluginCallForLastActivity; + + // Any URI that was passed to the app on start + private Uri intentUri; + + // A list of listeners that trigger when webView events occur + private List webViewListeners = new ArrayList<>(); + + // An interface to manipulate route resolving + private RouteProcessor routeProcessor; + + // A pre-determined path to load the bridge + private ServerPath serverPath; + + /** + * Create the Bridge with a reference to the main {@link Activity} for the + * app, and a reference to the {@link WebView} our app will use. + * @param context + * @param webView + * @deprecated Use {@link Bridge.Builder} to create Bridge instances + */ + @Deprecated + public Bridge( + AppCompatActivity context, + WebView webView, + List> initialPlugins, + MockCordovaInterfaceImpl cordovaInterface, + PluginManager pluginManager, + CordovaPreferences preferences, + CapConfig config + ) { + this(context, null, null, webView, initialPlugins, new ArrayList<>(), cordovaInterface, pluginManager, preferences, config); + } + + private Bridge( + AppCompatActivity context, + ServerPath serverPath, + Fragment fragment, + WebView webView, + List> initialPlugins, + List pluginInstances, + MockCordovaInterfaceImpl cordovaInterface, + PluginManager pluginManager, + CordovaPreferences preferences, + CapConfig config + ) { + this.app = new App(); + this.serverPath = serverPath; + this.context = context; + this.fragment = fragment; + this.webView = webView; + this.webViewClient = new BridgeWebViewClient(this); + this.initialPlugins = initialPlugins; + this.pluginInstances = pluginInstances; + this.cordovaInterface = cordovaInterface; + this.preferences = preferences; + + // Start our plugin execution threads and handlers + handlerThread.start(); + taskHandler = new Handler(handlerThread.getLooper()); + + this.config = config != null ? config : CapConfig.loadDefault(getActivity()); + Logger.init(this.config); + + // Initialize web view and message handler for it + this.initWebView(); + this.setAllowedOriginRules(); + this.msgHandler = new MessageHandler(this, webView, pluginManager); + + // Grab any intent info that our app was launched with + Intent intent = context.getIntent(); + this.intentUri = intent.getData(); + // Register our core plugins + this.registerAllPlugins(); + + this.loadWebView(); + } + + private void setAllowedOriginRules() { + String[] appAllowNavigationConfig = this.config.getAllowNavigation(); + String authority = this.getHost(); + String scheme = this.getScheme(); + allowedOriginRules.add(scheme + "://" + authority); + if (this.getServerUrl() != null) { + allowedOriginRules.add(this.getServerUrl()); + } + if (appAllowNavigationConfig != null) { + for (String allowNavigation : appAllowNavigationConfig) { + if (!allowNavigation.startsWith("http")) { + allowedOriginRules.add("https://" + allowNavigation); + } else { + allowedOriginRules.add(allowNavigation); + } + } + authorities.addAll(Arrays.asList(appAllowNavigationConfig)); + } + this.appAllowNavigationMask = HostMask.Parser.parse(appAllowNavigationConfig); + } + + public App getApp() { + return app; + } + + private void loadWebView() { + final boolean html5mode = this.config.isHTML5Mode(); + + // Start the local web server + localServer = new WebViewLocalServer(context, this, getJSInjector(), authorities, html5mode); + localServer.hostAssets(DEFAULT_WEB_ASSET_DIR); + + Logger.debug("Loading app at " + appUrl); + + webView.setWebChromeClient(new BridgeWebChromeClient(this)); + webView.setWebViewClient(this.webViewClient); + + if (!isDeployDisabled() && !isNewBinary()) { + SharedPreferences prefs = getContext() + .getSharedPreferences(com.getcapacitor.plugin.WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE); + String path = prefs.getString(com.getcapacitor.plugin.WebView.CAP_SERVER_PATH, null); + if (path != null && !path.isEmpty() && new File(path).exists()) { + setServerBasePath(path); + } + } + if (!this.isMinimumWebViewInstalled()) { + String errorUrl = this.getErrorUrl(); + if (errorUrl != null) { + webView.loadUrl(errorUrl); + return; + } else { + Logger.error(MINIMUM_ANDROID_WEBVIEW_ERROR); + } + } + + // If serverPath configured, start server based on provided path + if (serverPath != null) { + if (serverPath.getType() == ServerPath.PathType.ASSET_PATH) { + setServerAssetPath(serverPath.getPath()); + } else { + setServerBasePath(serverPath.getPath()); + } + } else { + // Get to work + webView.loadUrl(appUrl); + } + } + + @SuppressLint("WebViewApiAvailability") + public boolean isMinimumWebViewInstalled() { + PackageManager pm = getContext().getPackageManager(); + + // Check getCurrentWebViewPackage() directly if above Android 8 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + PackageInfo info = WebView.getCurrentWebViewPackage(); + Pattern pattern = Pattern.compile("(\\d+)"); + Matcher matcher = pattern.matcher(info.versionName); + if (matcher.find()) { + String majorVersionStr = matcher.group(0); + int majorVersion = Integer.parseInt(majorVersionStr); + if (info.packageName.equals("com.huawei.webview")) { + return majorVersion >= config.getMinHuaweiWebViewVersion(); + } + return majorVersion >= config.getMinWebViewVersion(); + } else { + return false; + } + } + + // Otherwise manually check WebView versions + try { + String webViewPackage = "com.google.android.webview"; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + webViewPackage = "com.android.chrome"; + } + PackageInfo info = InternalUtils.getPackageInfo(pm, webViewPackage); + String majorVersionStr = info.versionName.split("\\.")[0]; + int majorVersion = Integer.parseInt(majorVersionStr); + return majorVersion >= config.getMinWebViewVersion(); + } catch (Exception ex) { + Logger.warn("Unable to get package info for 'com.google.android.webview'" + ex.toString()); + } + + try { + PackageInfo info = InternalUtils.getPackageInfo(pm, "com.android.webview"); + String majorVersionStr = info.versionName.split("\\.")[0]; + int majorVersion = Integer.parseInt(majorVersionStr); + return majorVersion >= config.getMinWebViewVersion(); + } catch (Exception ex) { + Logger.warn("Unable to get package info for 'com.android.webview'" + ex.toString()); + } + + final int amazonFireMajorWebViewVersion = extractWebViewMajorVersion(pm, "com.amazon.webview.chromium"); + if (amazonFireMajorWebViewVersion >= config.getMinWebViewVersion()) { + return true; + } + + // Could not detect any webview, return false + return false; + } + + private int extractWebViewMajorVersion(final PackageManager pm, final String webViewPackageName) { + try { + final PackageInfo info = InternalUtils.getPackageInfo(pm, webViewPackageName); + final String majorVersionStr = info.versionName.split("\\.")[0]; + final int majorVersion = Integer.parseInt(majorVersionStr); + return majorVersion; + } catch (Exception ex) { + Logger.warn(String.format("Unable to get package info for '%s' with err '%s'", webViewPackageName, ex)); + } + return 0; + } + + public boolean launchIntent(Uri url) { + /* + * Give plugins the chance to handle the url + */ + for (Map.Entry entry : plugins.entrySet()) { + Plugin plugin = entry.getValue().getInstance(); + if (plugin != null) { + Boolean shouldOverrideLoad = plugin.shouldOverrideLoad(url); + if (shouldOverrideLoad != null) { + return shouldOverrideLoad; + } + } + } + + if (url.getScheme().equals("data") || url.getScheme().equals("blob")) { + return false; + } + + Uri appUri = Uri.parse(appUrl); + if ( + !(appUri.getHost().equals(url.getHost()) && url.getScheme().equals(appUri.getScheme())) && + !appAllowNavigationMask.matches(url.getHost()) + ) { + try { + Intent openIntent = new Intent(Intent.ACTION_VIEW, url); + getContext().startActivity(openIntent); + } catch (ActivityNotFoundException e) { + // TODO - trigger an event + } + return true; + } + return false; + } + + private boolean isNewBinary() { + String versionCode = ""; + String versionName = ""; + SharedPreferences prefs = getContext() + .getSharedPreferences(com.getcapacitor.plugin.WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE); + String lastVersionCode = prefs.getString(LAST_BINARY_VERSION_CODE, null); + String lastVersionName = prefs.getString(LAST_BINARY_VERSION_NAME, null); + + try { + PackageManager pm = getContext().getPackageManager(); + PackageInfo pInfo = InternalUtils.getPackageInfo(pm, getContext().getPackageName()); + versionCode = Integer.toString((int) PackageInfoCompat.getLongVersionCode(pInfo)); + versionName = pInfo.versionName; + } catch (Exception ex) { + Logger.error("Unable to get package info", ex); + } + + if (!versionCode.equals(lastVersionCode) || !versionName.equals(lastVersionName)) { + SharedPreferences.Editor editor = prefs.edit(); + editor.putString(LAST_BINARY_VERSION_CODE, versionCode); + editor.putString(LAST_BINARY_VERSION_NAME, versionName); + editor.putString(com.getcapacitor.plugin.WebView.CAP_SERVER_PATH, ""); + editor.apply(); + return true; + } + return false; + } + + public boolean isDeployDisabled() { + return preferences.getBoolean("DisableDeploy", false); + } + + public boolean shouldKeepRunning() { + return preferences.getBoolean("KeepRunning", true); + } + + public void handleAppUrlLoadError(Exception ex) { + if (ex instanceof SocketTimeoutException) { + Logger.error( + "Unable to load app. Ensure the server is running at " + + appUrl + + ", or modify the " + + "appUrl setting in capacitor.config.json (make sure to npx cap copy after to commit changes).", + ex + ); + } + } + + public boolean isDevMode() { + return (getActivity().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; + } + + protected void setCordovaWebView(CordovaWebView cordovaWebView) { + this.cordovaWebView = cordovaWebView; + } + + /** + * Get the Context for the App + * @return + */ + public Context getContext() { + return this.context; + } + + /** + * Get the activity for the app + * @return + */ + public AppCompatActivity getActivity() { + return this.context; + } + + /** + * Get the fragment for the app, if applicable. This will likely be null unless Capacitor + * is being used embedded in a Native Android app. + * + * @return The fragment containing the Capacitor WebView. + */ + public Fragment getFragment() { + return this.fragment; + } + + /** + * Get the core WebView under Capacitor's control + * @return + */ + public WebView getWebView() { + return this.webView; + } + + /** + * Get the URI that was used to launch the app (if any) + * @return + */ + public Uri getIntentUri() { + return intentUri; + } + + /** + * Get scheme that is used to serve content + * @return + */ + public String getScheme() { + return this.config.getAndroidScheme(); + } + + /** + * Get host name that is used to serve content + * @return + */ + public String getHost() { + return this.config.getHostname(); + } + + /** + * Get the server url that is used to serve content + * @return + */ + public String getServerUrl() { + return this.config.getServerUrl(); + } + + public String getErrorUrl() { + String errorPath = this.config.getErrorPath(); + + if (errorPath != null && !errorPath.trim().isEmpty()) { + String authority = this.getHost(); + String scheme = this.getScheme(); + + String localUrl = scheme + "://" + authority; + + return localUrl + "/" + errorPath; + } + + return null; + } + + public String getAppUrl() { + return appUrl; + } + + public CapConfig getConfig() { + return this.config; + } + + public void reset() { + savedCalls = new HashMap<>(); + } + + /** + * Initialize the WebView, setting required flags + */ + @SuppressLint("SetJavaScriptEnabled") + private void initWebView() { + WebSettings settings = webView.getSettings(); + settings.setJavaScriptEnabled(true); + settings.setDomStorageEnabled(true); + settings.setGeolocationEnabled(true); + settings.setDatabaseEnabled(true); + settings.setMediaPlaybackRequiresUserGesture(false); + settings.setJavaScriptCanOpenWindowsAutomatically(true); + if (this.config.isMixedContentAllowed()) { + settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); + } + + String appendUserAgent = this.config.getAppendedUserAgentString(); + if (appendUserAgent != null) { + String defaultUserAgent = settings.getUserAgentString(); + settings.setUserAgentString(defaultUserAgent + " " + appendUserAgent); + } + String overrideUserAgent = this.config.getOverriddenUserAgentString(); + if (overrideUserAgent != null) { + settings.setUserAgentString(overrideUserAgent); + } + + String backgroundColor = this.config.getBackgroundColor(); + try { + if (backgroundColor != null) { + webView.setBackgroundColor(WebColor.parseColor(backgroundColor)); + } + } catch (IllegalArgumentException ex) { + Logger.debug("WebView background color not applied"); + } + + if (config.isInitialFocus()) { + webView.requestFocusFromTouch(); + } + + WebView.setWebContentsDebuggingEnabled(this.config.isWebContentsDebuggingEnabled()); + + appUrlConfig = this.getServerUrl(); + String authority = this.getHost(); + authorities.add(authority); + String scheme = this.getScheme(); + + localUrl = scheme + "://" + authority; + + if (appUrlConfig != null) { + try { + URL appUrlObject = new URL(appUrlConfig); + authorities.add(appUrlObject.getAuthority()); + } catch (Exception ex) { + Logger.error("Provided server url is invalid: " + ex.getMessage()); + return; + } + localUrl = appUrlConfig; + appUrl = appUrlConfig; + } else { + appUrl = localUrl; + // custom URL schemes requires path ending with / + if (!scheme.equals(Bridge.CAPACITOR_HTTP_SCHEME) && !scheme.equals(CAPACITOR_HTTPS_SCHEME)) { + appUrl += "/"; + } + } + + String appUrlPath = this.config.getStartPath(); + if (appUrlPath != null && !appUrlPath.trim().isEmpty()) { + appUrl += appUrlPath; + } + } + + /** + * Register our core Plugin APIs + */ + private void registerAllPlugins() { + this.registerPlugin(com.getcapacitor.plugin.CapacitorCookies.class); + this.registerPlugin(com.getcapacitor.plugin.WebView.class); + this.registerPlugin(com.getcapacitor.plugin.CapacitorHttp.class); + + for (Class pluginClass : this.initialPlugins) { + this.registerPlugin(pluginClass); + } + + for (Plugin plugin : pluginInstances) { + registerPluginInstance(plugin); + } + } + + /** + * Register additional plugins + * @param pluginClasses the plugins to register + */ + public void registerPlugins(Class[] pluginClasses) { + for (Class plugin : pluginClasses) { + this.registerPlugin(plugin); + } + } + + public void registerPluginInstances(Plugin[] pluginInstances) { + for (Plugin plugin : pluginInstances) { + this.registerPluginInstance(plugin); + } + } + + @SuppressWarnings("deprecation") + private String getLegacyPluginName(Class pluginClass) { + NativePlugin legacyPluginAnnotation = pluginClass.getAnnotation(NativePlugin.class); + if (legacyPluginAnnotation == null) { + Logger.error("Plugin doesn't have the @CapacitorPlugin annotation. Please add it"); + return null; + } + + return legacyPluginAnnotation.name(); + } + + /** + * Register a plugin class + * @param pluginClass a class inheriting from Plugin + */ + public void registerPlugin(Class pluginClass) { + String pluginId = pluginId(pluginClass); + if (pluginId == null) return; + + try { + this.plugins.put(pluginId, new PluginHandle(this, pluginClass)); + } catch (InvalidPluginException ex) { + logInvalidPluginException(pluginClass); + } catch (PluginLoadException ex) { + logPluginLoadException(pluginClass, ex); + } + } + + public void registerPluginInstance(Plugin plugin) { + Class clazz = plugin.getClass(); + String pluginId = pluginId(clazz); + if (pluginId == null) return; + + try { + this.plugins.put(pluginId, new PluginHandle(this, plugin)); + } catch (InvalidPluginException ex) { + logInvalidPluginException(clazz); + } + } + + private String pluginId(Class clazz) { + String pluginName = pluginName(clazz); + String pluginId = clazz.getSimpleName(); + if (pluginName == null) return null; + + if (!pluginName.equals("")) { + pluginId = pluginName; + } + Logger.debug("Registering plugin instance: " + pluginId); + return pluginId; + } + + private String pluginName(Class clazz) { + String pluginName; + CapacitorPlugin pluginAnnotation = clazz.getAnnotation(CapacitorPlugin.class); + if (pluginAnnotation == null) { + pluginName = this.getLegacyPluginName(clazz); + } else { + pluginName = pluginAnnotation.name(); + } + + return pluginName; + } + + private void logInvalidPluginException(Class clazz) { + Logger.error( + "NativePlugin " + + clazz.getName() + + " is invalid. Ensure the @CapacitorPlugin annotation exists on the plugin class and" + + " the class extends Plugin" + ); + } + + private void logPluginLoadException(Class clazz, Exception ex) { + Logger.error("NativePlugin " + clazz.getName() + " failed to load", ex); + } + + public PluginHandle getPlugin(String pluginId) { + return this.plugins.get(pluginId); + } + + /** + * Find the plugin handle that responds to the given request code. This will + * fire after certain Android OS intent results/permission checks/etc. + * @param requestCode + * @return + */ + @Deprecated + @SuppressWarnings("deprecation") + public PluginHandle getPluginWithRequestCode(int requestCode) { + for (PluginHandle handle : this.plugins.values()) { + int[] requestCodes; + + CapacitorPlugin pluginAnnotation = handle.getPluginAnnotation(); + if (pluginAnnotation == null) { + // Check for legacy plugin annotation, @NativePlugin + NativePlugin legacyPluginAnnotation = handle.getLegacyPluginAnnotation(); + if (legacyPluginAnnotation == null) { + continue; + } + + if (legacyPluginAnnotation.permissionRequestCode() == requestCode) { + return handle; + } + + requestCodes = legacyPluginAnnotation.requestCodes(); + + for (int rc : requestCodes) { + if (rc == requestCode) { + return handle; + } + } + } else { + requestCodes = pluginAnnotation.requestCodes(); + + for (int rc : requestCodes) { + if (rc == requestCode) { + return handle; + } + } + } + } + return null; + } + + /** + * Call a method on a plugin. + * @param pluginId the plugin id to use to lookup the plugin handle + * @param methodName the name of the method to call + * @param call the call object to pass to the method + */ + public void callPluginMethod(String pluginId, final String methodName, final PluginCall call) { + try { + final PluginHandle plugin = this.getPlugin(pluginId); + + if (plugin == null) { + Logger.error("unable to find plugin : " + pluginId); + call.errorCallback("unable to find plugin : " + pluginId); + return; + } + + if (Logger.shouldLog()) { + Logger.verbose( + "callback: " + + call.getCallbackId() + + ", pluginId: " + + plugin.getId() + + ", methodName: " + + methodName + + ", methodData: " + + call.getData().toString() + ); + } + + Runnable currentThreadTask = () -> { + try { + plugin.invoke(methodName, call); + + if (call.isKeptAlive()) { + saveCall(call); + } + } catch (PluginLoadException | InvalidPluginMethodException ex) { + Logger.error("Unable to execute plugin method", ex); + } catch (Exception ex) { + Logger.error("Serious error executing plugin", ex); + throw new RuntimeException(ex); + } + }; + + taskHandler.post(currentThreadTask); + } catch (Exception ex) { + Logger.error(Logger.tags("callPluginMethod"), "error : " + ex, null); + call.errorCallback(ex.toString()); + } + } + + /** + * Evaluate JavaScript in the web view. This method + * executes on the main thread automatically. + * @param js the JS to execute + * @param callback an optional ValueCallback that will synchronously receive a value + * after calling the JS + */ + public void eval(final String js, final ValueCallback callback) { + Handler mainHandler = new Handler(context.getMainLooper()); + mainHandler.post(() -> webView.evaluateJavascript(js, callback)); + } + + public void logToJs(final String message, final String level) { + eval("window.Capacitor.logJs(\"" + message + "\", \"" + level + "\")", null); + } + + public void logToJs(final String message) { + logToJs(message, "log"); + } + + public void triggerJSEvent(final String eventName, final String target) { + eval("window.Capacitor.triggerEvent(\"" + eventName + "\", \"" + target + "\")", s -> {}); + } + + public void triggerJSEvent(final String eventName, final String target, final String data) { + eval("window.Capacitor.triggerEvent(\"" + eventName + "\", \"" + target + "\", " + data + ")", s -> {}); + } + + public void triggerWindowJSEvent(final String eventName) { + this.triggerJSEvent(eventName, "window"); + } + + public void triggerWindowJSEvent(final String eventName, final String data) { + this.triggerJSEvent(eventName, "window", data); + } + + public void triggerDocumentJSEvent(final String eventName) { + this.triggerJSEvent(eventName, "document"); + } + + public void triggerDocumentJSEvent(final String eventName, final String data) { + this.triggerJSEvent(eventName, "document", data); + } + + public void execute(Runnable runnable) { + taskHandler.post(runnable); + } + + public void executeOnMainThread(Runnable runnable) { + Handler mainHandler = new Handler(context.getMainLooper()); + + mainHandler.post(runnable); + } + + /** + * Retain a call between plugin invocations + * @param call + */ + public void saveCall(PluginCall call) { + this.savedCalls.put(call.getCallbackId(), call); + } + + /** + * Get a retained plugin call + * @param callbackId the callbackId to use to lookup the call with + * @return the stored call + */ + public PluginCall getSavedCall(String callbackId) { + if (callbackId == null) { + return null; + } + + return this.savedCalls.get(callbackId); + } + + PluginCall getPluginCallForLastActivity() { + PluginCall pluginCallForLastActivity = this.pluginCallForLastActivity; + this.pluginCallForLastActivity = null; + return pluginCallForLastActivity; + } + + void setPluginCallForLastActivity(PluginCall pluginCallForLastActivity) { + this.pluginCallForLastActivity = pluginCallForLastActivity; + } + + /** + * Release a retained call + * @param call a call to release + */ + public void releaseCall(PluginCall call) { + releaseCall(call.getCallbackId()); + } + + /** + * Release a retained call by its ID + * @param callbackId an ID of a callback to release + */ + public void releaseCall(String callbackId) { + this.savedCalls.remove(callbackId); + } + + /** + * Removes the earliest saved call prior to a permissions request for a given plugin and + * returns it. + * + * @return The saved plugin call + */ + protected PluginCall getPermissionCall(String pluginId) { + LinkedList permissionCallIds = this.savedPermissionCallIds.get(pluginId); + String savedCallId = null; + if (permissionCallIds != null) { + savedCallId = permissionCallIds.poll(); + } + + return getSavedCall(savedCallId); + } + + /** + * Save a call to be retrieved after requesting permissions. Calls are saved in order. + * + * @param call The plugin call to save. + */ + protected void savePermissionCall(PluginCall call) { + if (call != null) { + if (!savedPermissionCallIds.containsKey(call.getPluginId())) { + savedPermissionCallIds.put(call.getPluginId(), new LinkedList<>()); + } + + savedPermissionCallIds.get(call.getPluginId()).add(call.getCallbackId()); + saveCall(call); + } + } + + /** + * Register an Activity Result Launcher to the containing Fragment or Activity. + * + * @param contract A contract specifying that an activity can be called with an input of + * type I and produce an output of type O. + * @param callback The callback run on Activity Result. + * @return A registered Activity Result Launcher. + */ + public ActivityResultLauncher registerForActivityResult( + @NonNull final ActivityResultContract contract, + @NonNull final ActivityResultCallback callback + ) { + if (fragment != null) { + return fragment.registerForActivityResult(contract, callback); + } else { + return context.registerForActivityResult(contract, callback); + } + } + + /** + * Build the JSInjector that will be used to inject JS into files served to the app, + * to ensure that Capacitor's JS and the JS for all the plugins is loaded each time. + */ + private JSInjector getJSInjector() { + try { + String globalJS = JSExport.getGlobalJS(context, config.isLoggingEnabled(), isDevMode()); + String bridgeJS = JSExport.getBridgeJS(context); + String pluginJS = JSExport.getPluginJS(plugins.values()); + String cordovaJS = JSExport.getCordovaJS(context); + String cordovaPluginsJS = JSExport.getCordovaPluginJS(context); + String cordovaPluginsFileJS = JSExport.getCordovaPluginsFileJS(context); + String localUrlJS = "window.WEBVIEW_SERVER_URL = '" + localUrl + "';"; + + return new JSInjector(globalJS, bridgeJS, pluginJS, cordovaJS, cordovaPluginsJS, cordovaPluginsFileJS, localUrlJS); + } catch (Exception ex) { + Logger.error("Unable to export Capacitor JS. App will not function!", ex); + } + return null; + } + + /** + * Restore any saved bundle state data + * @param savedInstanceState + */ + public void restoreInstanceState(Bundle savedInstanceState) { + String lastPluginId = savedInstanceState.getString(BUNDLE_LAST_PLUGIN_ID_KEY); + String lastPluginCallMethod = savedInstanceState.getString(BUNDLE_LAST_PLUGIN_CALL_METHOD_NAME_KEY); + String lastOptionsJson = savedInstanceState.getString(BUNDLE_PLUGIN_CALL_OPTIONS_SAVED_KEY); + + if (lastPluginId != null) { + // If we have JSON blob saved, create a new plugin call with the original options + if (lastOptionsJson != null) { + try { + JSObject options = new JSObject(lastOptionsJson); + + pluginCallForLastActivity = + new PluginCall(msgHandler, lastPluginId, PluginCall.CALLBACK_ID_DANGLING, lastPluginCallMethod, options); + } catch (JSONException ex) { + Logger.error("Unable to restore plugin call, unable to parse persisted JSON object", ex); + } + } + + // Let the plugin restore any state it needs + Bundle bundleData = savedInstanceState.getBundle(BUNDLE_PLUGIN_CALL_BUNDLE_KEY); + PluginHandle lastPlugin = getPlugin(lastPluginId); + if (bundleData != null && lastPlugin != null) { + lastPlugin.getInstance().restoreState(bundleData); + } else { + Logger.error("Unable to restore last plugin call"); + } + } + } + + public void saveInstanceState(Bundle outState) { + Logger.debug("Saving instance state!"); + + // If there was a last PluginCall for a started activity, we need to + // persist it so we can load it again in case our app gets terminated + if (pluginCallForLastActivity != null) { + PluginCall call = pluginCallForLastActivity; + PluginHandle handle = getPlugin(call.getPluginId()); + + if (handle != null) { + Bundle bundle = handle.getInstance().saveInstanceState(); + if (bundle != null) { + outState.putString(BUNDLE_LAST_PLUGIN_ID_KEY, call.getPluginId()); + outState.putString(BUNDLE_LAST_PLUGIN_CALL_METHOD_NAME_KEY, call.getMethodName()); + outState.putString(BUNDLE_PLUGIN_CALL_OPTIONS_SAVED_KEY, call.getData().toString()); + outState.putBundle(BUNDLE_PLUGIN_CALL_BUNDLE_KEY, bundle); + } else { + Logger.error("Couldn't save last " + call.getPluginId() + "'s Plugin " + call.getMethodName() + " call"); + } + } + } + } + + @Deprecated + @SuppressWarnings("deprecation") + public void startActivityForPluginWithResult(PluginCall call, Intent intent, int requestCode) { + Logger.debug("Starting activity for result"); + + pluginCallForLastActivity = call; + + getActivity().startActivityForResult(intent, requestCode); + } + + /** + * Check for legacy Capacitor or Cordova plugins that may have registered to handle a permission + * request, and handle them if so. If not handled, false is returned. + * + * @param requestCode the code that was requested + * @param permissions the permissions requested + * @param grantResults the set of granted/denied permissions + * @return true if permission code was handled by a plugin explicitly, false if not + */ + @SuppressWarnings("deprecation") + boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + PluginHandle plugin = getPluginWithRequestCode(requestCode); + + if (plugin == null) { + boolean permissionHandled = false; + Logger.debug("Unable to find a Capacitor plugin to handle permission requestCode, trying Cordova plugins " + requestCode); + try { + permissionHandled = cordovaInterface.handlePermissionResult(requestCode, permissions, grantResults); + } catch (JSONException e) { + Logger.debug("Error on Cordova plugin permissions request " + e.getMessage()); + } + return permissionHandled; + } + + // Call deprecated method if using deprecated NativePlugin annotation + if (plugin.getPluginAnnotation() == null) { + plugin.getInstance().handleRequestPermissionsResult(requestCode, permissions, grantResults); + return true; + } + + return false; + } + + /** + * Saves permission states and rejects if permissions were not correctly defined in + * the AndroidManifest.xml file. + * + * @param plugin + * @param savedCall + * @param permissions + * @return true if permissions were saved and defined correctly, false if not + */ + protected boolean validatePermissions(Plugin plugin, PluginCall savedCall, Map permissions) { + SharedPreferences prefs = getContext().getSharedPreferences(PERMISSION_PREFS_NAME, Activity.MODE_PRIVATE); + + for (Map.Entry permission : permissions.entrySet()) { + String permString = permission.getKey(); + boolean isGranted = permission.getValue(); + + if (isGranted) { + // Permission granted. If previously denied, remove cached state + String state = prefs.getString(permString, null); + + if (state != null) { + SharedPreferences.Editor editor = prefs.edit(); + editor.remove(permString); + editor.apply(); + } + } else { + SharedPreferences.Editor editor = prefs.edit(); + + if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permString)) { + // Permission denied, can prompt again with rationale + editor.putString(permString, PermissionState.PROMPT_WITH_RATIONALE.toString()); + } else { + // Permission denied permanently, store this state for future reference + editor.putString(permString, PermissionState.DENIED.toString()); + } + + editor.apply(); + } + } + + String[] permStrings = permissions.keySet().toArray(new String[0]); + + if (!PermissionHelper.hasDefinedPermissions(getContext(), permStrings)) { + StringBuilder builder = new StringBuilder(); + builder.append("Missing the following permissions in AndroidManifest.xml:\n"); + String[] missing = PermissionHelper.getUndefinedPermissions(getContext(), permStrings); + for (String perm : missing) { + builder.append(perm + "\n"); + } + savedCall.reject(builder.toString()); + return false; + } + + return true; + } + + /** + * Helper to check all permissions and see the current states of each permission. + * + * @since 3.0.0 + * @return A mapping of permission aliases to the associated granted status. + */ + protected Map getPermissionStates(Plugin plugin) { + Map permissionsResults = new HashMap<>(); + CapacitorPlugin annotation = plugin.getPluginHandle().getPluginAnnotation(); + for (Permission perm : annotation.permissions()) { + // If a permission is defined with no permission constants, return GRANTED for it. + // Otherwise, get its true state. + if (perm.strings().length == 0 || (perm.strings().length == 1 && perm.strings()[0].isEmpty())) { + String key = perm.alias(); + if (!key.isEmpty()) { + PermissionState existingResult = permissionsResults.get(key); + + // auto set permission state to GRANTED if the alias is empty. + if (existingResult == null) { + permissionsResults.put(key, PermissionState.GRANTED); + } + } + } else { + for (String permString : perm.strings()) { + String key = perm.alias().isEmpty() ? permString : perm.alias(); + PermissionState permissionStatus; + if (ActivityCompat.checkSelfPermission(this.getContext(), permString) == PackageManager.PERMISSION_GRANTED) { + permissionStatus = PermissionState.GRANTED; + } else { + permissionStatus = PermissionState.PROMPT; + + // Check if there is a cached permission state for the "Never ask again" state + SharedPreferences prefs = getContext().getSharedPreferences(PERMISSION_PREFS_NAME, Activity.MODE_PRIVATE); + String state = prefs.getString(permString, null); + + if (state != null) { + permissionStatus = PermissionState.byState(state); + } + } + + PermissionState existingResult = permissionsResults.get(key); + + // multiple permissions with the same alias must all be true, otherwise all false. + if (existingResult == null || existingResult == PermissionState.GRANTED) { + permissionsResults.put(key, permissionStatus); + } + } + } + } + + return permissionsResults; + } + + /** + * Handle an activity result and pass it to a plugin that has indicated it wants to + * handle the result. + * @param requestCode + * @param resultCode + * @param data + */ + @SuppressWarnings("deprecation") + boolean onActivityResult(int requestCode, int resultCode, Intent data) { + PluginHandle plugin = getPluginWithRequestCode(requestCode); + + if (plugin == null || plugin.getInstance() == null) { + Logger.debug("Unable to find a Capacitor plugin to handle requestCode, trying Cordova plugins " + requestCode); + return cordovaInterface.onActivityResult(requestCode, resultCode, data); + } + + // deprecated, to be removed + PluginCall lastCall = plugin.getInstance().getSavedCall(); + + // If we don't have a saved last call (because our app was killed and restarted, for example), + // Then we should see if we have any saved plugin call information and generate a new, + // "dangling" plugin call (a plugin call that doesn't have a corresponding web callback) + // and then send that to the plugin + if (lastCall == null && pluginCallForLastActivity != null) { + plugin.getInstance().saveCall(pluginCallForLastActivity); + } + + plugin.getInstance().handleOnActivityResult(requestCode, resultCode, data); + + // Clear the plugin call we may have re-hydrated on app launch + pluginCallForLastActivity = null; + + return true; + } + + /** + * Handle an onNewIntent lifecycle event and notify the plugins + * @param intent + */ + public void onNewIntent(Intent intent) { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnNewIntent(intent); + } + + if (cordovaWebView != null) { + cordovaWebView.onNewIntent(intent); + } + } + + /** + * Handle an onConfigurationChanged event and notify the plugins + * @param newConfig + */ + public void onConfigurationChanged(Configuration newConfig) { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnConfigurationChanged(newConfig); + } + } + + /** + * Handle onRestart lifecycle event and notify the plugins + */ + public void onRestart() { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnRestart(); + } + } + + /** + * Handle onStart lifecycle event and notify the plugins + */ + public void onStart() { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnStart(); + } + + if (cordovaWebView != null) { + cordovaWebView.handleStart(); + } + } + + /** + * Handle onResume lifecycle event and notify the plugins + */ + public void onResume() { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnResume(); + } + + if (cordovaWebView != null) { + cordovaWebView.handleResume(this.shouldKeepRunning()); + } + } + + /** + * Handle onPause lifecycle event and notify the plugins + */ + public void onPause() { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnPause(); + } + + if (cordovaWebView != null) { + boolean keepRunning = this.shouldKeepRunning() || cordovaInterface.getActivityResultCallback() != null; + cordovaWebView.handlePause(keepRunning); + } + } + + /** + * Handle onStop lifecycle event and notify the plugins + */ + public void onStop() { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnStop(); + } + + if (cordovaWebView != null) { + cordovaWebView.handleStop(); + } + } + + /** + * Handle onDestroy lifecycle event and notify the plugins + */ + public void onDestroy() { + for (PluginHandle plugin : plugins.values()) { + plugin.getInstance().handleOnDestroy(); + } + + handlerThread.quitSafely(); + + if (cordovaWebView != null) { + cordovaWebView.handleDestroy(); + } + } + + /** + * Handle onDetachedFromWindow lifecycle event + */ + public void onDetachedFromWindow() { + webView.removeAllViews(); + webView.destroy(); + } + + public String getServerBasePath() { + return this.localServer.getBasePath(); + } + + /** + * Tell the local server to load files from the given + * file path instead of the assets path. + * @param path + */ + public void setServerBasePath(String path) { + localServer.hostFiles(path); + webView.post(() -> webView.loadUrl(appUrl)); + } + + /** + * Tell the local server to load files from the given + * asset path. + * @param path + */ + public void setServerAssetPath(String path) { + localServer.hostAssets(path); + webView.post(() -> webView.loadUrl(appUrl)); + } + + /** + * Reload the WebView + */ + public void reload() { + webView.post(() -> webView.loadUrl(appUrl)); + } + + public String getLocalUrl() { + return localUrl; + } + + public WebViewLocalServer getLocalServer() { + return localServer; + } + + public HostMask getAppAllowNavigationMask() { + return appAllowNavigationMask; + } + + public Set getAllowedOriginRules() { + return allowedOriginRules; + } + + public BridgeWebViewClient getWebViewClient() { + return this.webViewClient; + } + + public void setWebViewClient(BridgeWebViewClient client) { + this.webViewClient = client; + webView.setWebViewClient(client); + } + + List getWebViewListeners() { + return webViewListeners; + } + + void setWebViewListeners(List webViewListeners) { + this.webViewListeners = webViewListeners; + } + + RouteProcessor getRouteProcessor() { + return routeProcessor; + } + + void setRouteProcessor(RouteProcessor routeProcessor) { + this.routeProcessor = routeProcessor; + } + + ServerPath getServerPath() { + return serverPath; + } + + /** + * Add a listener that the WebViewClient can trigger on certain events. + * @param webViewListener A {@link WebViewListener} to add. + */ + public void addWebViewListener(WebViewListener webViewListener) { + webViewListeners.add(webViewListener); + } + + /** + * Remove a listener that the WebViewClient triggers on certain events. + * @param webViewListener A {@link WebViewListener} to remove. + */ + public void removeWebViewListener(WebViewListener webViewListener) { + webViewListeners.remove(webViewListener); + } + + public static class Builder { + + private Bundle instanceState = null; + private CapConfig config = null; + private List> plugins = new ArrayList<>(); + private List pluginInstances = new ArrayList<>(); + private AppCompatActivity activity; + private Fragment fragment; + private RouteProcessor routeProcessor; + private final List webViewListeners = new ArrayList<>(); + private ServerPath serverPath; + + public Builder(AppCompatActivity activity) { + this.activity = activity; + } + + public Builder(Fragment fragment) { + this.activity = (AppCompatActivity) fragment.getActivity(); + this.fragment = fragment; + } + + public Builder setInstanceState(Bundle instanceState) { + this.instanceState = instanceState; + return this; + } + + public Builder setConfig(CapConfig config) { + this.config = config; + return this; + } + + public Builder setPlugins(List> plugins) { + this.plugins = plugins; + return this; + } + + public Builder addPlugin(Class plugin) { + this.plugins.add(plugin); + return this; + } + + public Builder addPlugins(List> plugins) { + for (Class cls : plugins) { + this.addPlugin(cls); + } + + return this; + } + + public Builder addPluginInstance(Plugin plugin) { + this.pluginInstances.add(plugin); + return this; + } + + public Builder addPluginInstances(List plugins) { + this.pluginInstances.addAll(plugins); + return this; + } + + public Builder addWebViewListener(WebViewListener webViewListener) { + webViewListeners.add(webViewListener); + return this; + } + + public Builder addWebViewListeners(List webViewListeners) { + for (WebViewListener listener : webViewListeners) { + this.addWebViewListener(listener); + } + + return this; + } + + public Builder setRouteProcessor(RouteProcessor routeProcessor) { + this.routeProcessor = routeProcessor; + return this; + } + + public Builder setServerPath(ServerPath serverPath) { + this.serverPath = serverPath; + return this; + } + + public Bridge create() { + // Cordova initialization + ConfigXmlParser parser = new ConfigXmlParser(); + parser.parse(activity.getApplicationContext()); + CordovaPreferences preferences = parser.getPreferences(); + preferences.setPreferencesBundle(activity.getIntent().getExtras()); + List pluginEntries = parser.getPluginEntries(); + + MockCordovaInterfaceImpl cordovaInterface = new MockCordovaInterfaceImpl(activity); + if (instanceState != null) { + cordovaInterface.restoreInstanceState(instanceState); + } + + WebView webView = this.fragment != null ? fragment.getView().findViewById(R.id.webview) : activity.findViewById(R.id.webview); + MockCordovaWebViewImpl mockWebView = new MockCordovaWebViewImpl(activity.getApplicationContext()); + mockWebView.init(cordovaInterface, pluginEntries, preferences, webView); + PluginManager pluginManager = mockWebView.getPluginManager(); + cordovaInterface.onCordovaInit(pluginManager); + + // Bridge initialization + Bridge bridge = new Bridge( + activity, + serverPath, + fragment, + webView, + plugins, + pluginInstances, + cordovaInterface, + pluginManager, + preferences, + config + ); + + if (webView instanceof CapacitorWebView) { + CapacitorWebView capacitorWebView = (CapacitorWebView) webView; + capacitorWebView.setBridge(bridge); + } + + bridge.setCordovaWebView(mockWebView); + bridge.setWebViewListeners(webViewListeners); + bridge.setRouteProcessor(routeProcessor); + + if (instanceState != null) { + bridge.restoreInstanceState(instanceState); + } + + return bridge; + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeActivity.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeActivity.java new file mode 100644 index 0000000..c366026 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeActivity.java @@ -0,0 +1,197 @@ +package com.getcapacitor; + +import android.content.Intent; +import android.content.res.Configuration; +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; +import com.getcapacitor.android.R; +import java.util.ArrayList; +import java.util.List; + +public class BridgeActivity extends AppCompatActivity { + + protected Bridge bridge; + protected boolean keepRunning = true; + protected CapConfig config; + + protected int activityDepth = 0; + protected List> initialPlugins = new ArrayList<>(); + protected final Bridge.Builder bridgeBuilder = new Bridge.Builder(this); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + bridgeBuilder.setInstanceState(savedInstanceState); + getApplication().setTheme(R.style.AppTheme_NoActionBar); + setTheme(R.style.AppTheme_NoActionBar); + setContentView(R.layout.bridge_layout_main); + PluginManager loader = new PluginManager(getAssets()); + + try { + bridgeBuilder.addPlugins(loader.loadPluginClasses()); + } catch (PluginLoadException ex) { + Logger.error("Error loading plugins.", ex); + } + + this.load(); + } + + protected void load() { + Logger.debug("Starting BridgeActivity"); + + bridge = bridgeBuilder.addPlugins(initialPlugins).setConfig(config).create(); + + this.keepRunning = bridge.shouldKeepRunning(); + this.onNewIntent(getIntent()); + } + + public void registerPlugin(Class plugin) { + bridgeBuilder.addPlugin(plugin); + } + + public void registerPlugins(List> plugins) { + bridgeBuilder.addPlugins(plugins); + } + + public Bridge getBridge() { + return this.bridge; + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + bridge.saveInstanceState(outState); + } + + @Override + public void onStart() { + super.onStart(); + activityDepth++; + this.bridge.onStart(); + Logger.debug("App started"); + } + + @Override + public void onRestart() { + super.onRestart(); + this.bridge.onRestart(); + Logger.debug("App restarted"); + } + + @Override + public void onResume() { + super.onResume(); + bridge.getApp().fireStatusChange(true); + this.bridge.onResume(); + Logger.debug("App resumed"); + } + + @Override + public void onPause() { + super.onPause(); + this.bridge.onPause(); + Logger.debug("App paused"); + } + + @Override + public void onStop() { + super.onStop(); + + activityDepth = Math.max(0, activityDepth - 1); + if (activityDepth == 0) { + bridge.getApp().fireStatusChange(false); + } + + this.bridge.onStop(); + Logger.debug("App stopped"); + } + + @Override + public void onDestroy() { + super.onDestroy(); + this.bridge.onDestroy(); + Logger.debug("App destroyed"); + } + + @Override + public void onDetachedFromWindow() { + super.onDetachedFromWindow(); + this.bridge.onDetachedFromWindow(); + } + + /** + * Handles permission request results. + * + * Capacitor is backwards compatible such that plugins using legacy permission request codes + * may coexist with plugins using the AndroidX Activity v1.2 permission callback flow introduced + * in Capacitor 3.0. + * + * In this method, plugins are checked first for ownership of the legacy permission request code. + * If the {@link Bridge#onRequestPermissionsResult(int, String[], int[])} method indicates it has + * handled the permission, then the permission callback will be considered complete. Otherwise, + * the permission will be handled using the AndroidX Activity flow. + * + * @param requestCode the request code associated with the permission request + * @param permissions the Android permission strings requested + * @param grantResults the status result of the permission request + */ + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + if (this.bridge == null) { + return; + } + + if (!bridge.onRequestPermissionsResult(requestCode, permissions, grantResults)) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + } + } + + /** + * Handles activity results. + * + * Capacitor is backwards compatible such that plugins using legacy activity result codes + * may coexist with plugins using the AndroidX Activity v1.2 activity callback flow introduced + * in Capacitor 3.0. + * + * In this method, plugins are checked first for ownership of the legacy request code. If the + * {@link Bridge#onActivityResult(int, int, Intent)} method indicates it has handled the activity + * result, then the callback will be considered complete. Otherwise, the result will be handled + * using the AndroidX Activiy flow. + * + * @param requestCode the request code associated with the activity result + * @param resultCode the result code + * @param data any data included with the activity result + */ + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (this.bridge == null) { + return; + } + + if (!bridge.onActivityResult(requestCode, resultCode, data)) { + super.onActivityResult(requestCode, resultCode, data); + } + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + + if (this.bridge == null || intent == null) { + return; + } + + this.bridge.onNewIntent(intent); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + + if (this.bridge == null) { + return; + } + + this.bridge.onConfigurationChanged(newConfig); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeFragment.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeFragment.java new file mode 100644 index 0000000..f269bd5 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeFragment.java @@ -0,0 +1,134 @@ +package com.getcapacitor; + +import android.content.Context; +import android.content.res.TypedArray; +import android.os.Bundle; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import androidx.fragment.app.Fragment; +import com.getcapacitor.android.R; +import java.util.ArrayList; +import java.util.List; + +/** + * A simple {@link Fragment} subclass. + * Use the {@link BridgeFragment#newInstance} factory method to + * create an instance of this fragment. + */ +public class BridgeFragment extends Fragment { + + private static final String ARG_START_DIR = "startDir"; + + protected Bridge bridge; + protected boolean keepRunning = true; + + private final List> initialPlugins = new ArrayList<>(); + private CapConfig config = null; + + private final List webViewListeners = new ArrayList<>(); + + public BridgeFragment() { + // Required empty public constructor + } + + /** + * Use this factory method to create a new instance of + * this fragment using the provided parameters. + * + * @param startDir the directory to serve content from + * @return A new instance of fragment BridgeFragment. + */ + public static BridgeFragment newInstance(String startDir) { + BridgeFragment fragment = new BridgeFragment(); + Bundle args = new Bundle(); + args.putString(ARG_START_DIR, startDir); + fragment.setArguments(args); + return fragment; + } + + public void addPlugin(Class plugin) { + this.initialPlugins.add(plugin); + } + + public void setConfig(CapConfig config) { + this.config = config; + } + + public Bridge getBridge() { + return bridge; + } + + public void addWebViewListener(WebViewListener webViewListener) { + webViewListeners.add(webViewListener); + } + + /** + * Load the WebView and create the Bridge + */ + protected void load(Bundle savedInstanceState) { + Logger.debug("Loading Bridge with BridgeFragment"); + + Bundle args = getArguments(); + String startDir = null; + + if (args != null) { + startDir = getArguments().getString(ARG_START_DIR); + } + + bridge = + new Bridge.Builder(this) + .setInstanceState(savedInstanceState) + .setPlugins(initialPlugins) + .setConfig(config) + .addWebViewListeners(webViewListeners) + .create(); + + if (startDir != null) { + bridge.setServerAssetPath(startDir); + } + + this.keepRunning = bridge.shouldKeepRunning(); + } + + @Override + public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) { + super.onInflate(context, attrs, savedInstanceState); + + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.bridge_fragment); + CharSequence c = a.getString(R.styleable.bridge_fragment_start_dir); + + if (c != null) { + String startDir = c.toString(); + Bundle args = new Bundle(); + args.putString(ARG_START_DIR, startDir); + setArguments(args); + } + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + // Inflate the layout for this fragment + return inflater.inflate(R.layout.fragment_bridge, container, false); + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + this.load(savedInstanceState); + } + + @Override + public void onDestroy() { + super.onDestroy(); + if (this.bridge != null) { + this.bridge.onDestroy(); + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java new file mode 100644 index 0000000..400b65a --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java @@ -0,0 +1,510 @@ +package com.getcapacitor; + +import android.Manifest; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ActivityNotFoundException; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.MediaStore; +import android.view.View; +import android.webkit.ConsoleMessage; +import android.webkit.GeolocationPermissions; +import android.webkit.JsPromptResult; +import android.webkit.JsResult; +import android.webkit.MimeTypeMap; +import android.webkit.PermissionRequest; +import android.webkit.ValueCallback; +import android.webkit.WebChromeClient; +import android.webkit.WebView; +import android.widget.EditText; +import androidx.activity.result.ActivityResult; +import androidx.activity.result.ActivityResultCallback; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.core.content.FileProvider; +import com.getcapacitor.util.PermissionHelper; +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * Custom WebChromeClient handler, required for showing dialogs, confirms, etc. in our + * WebView instance. + */ +public class BridgeWebChromeClient extends WebChromeClient { + + private interface PermissionListener { + void onPermissionSelect(Boolean isGranted); + } + + private interface ActivityResultListener { + void onActivityResult(ActivityResult result); + } + + private ActivityResultLauncher permissionLauncher; + private ActivityResultLauncher activityLauncher; + private PermissionListener permissionListener; + private ActivityResultListener activityListener; + + private Bridge bridge; + + public BridgeWebChromeClient(Bridge bridge) { + this.bridge = bridge; + + ActivityResultCallback> permissionCallback = (Map isGranted) -> { + if (permissionListener != null) { + boolean granted = true; + for (Map.Entry permission : isGranted.entrySet()) { + if (!permission.getValue()) granted = false; + } + permissionListener.onPermissionSelect(granted); + } + }; + + permissionLauncher = bridge.registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissionCallback); + activityLauncher = + bridge.registerForActivityResult( + new ActivityResultContracts.StartActivityForResult(), + result -> { + if (activityListener != null) { + activityListener.onActivityResult(result); + } + } + ); + } + + /** + * Render web content in `view`. + * + * Both this method and {@link #onHideCustomView()} are required for + * rendering web content in full screen. + * + * @see onShowCustomView() docs + */ + @Override + public void onShowCustomView(View view, CustomViewCallback callback) { + callback.onCustomViewHidden(); + super.onShowCustomView(view, callback); + } + + /** + * Render web content in the original Web View again. + * + * Do not remove this method--@see #onShowCustomView(View, CustomViewCallback). + */ + @Override + public void onHideCustomView() { + super.onHideCustomView(); + } + + @Override + public void onPermissionRequest(final PermissionRequest request) { + boolean isRequestPermissionRequired = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M; + + List permissionList = new ArrayList<>(); + if (Arrays.asList(request.getResources()).contains("android.webkit.resource.VIDEO_CAPTURE")) { + permissionList.add(Manifest.permission.CAMERA); + } + if (Arrays.asList(request.getResources()).contains("android.webkit.resource.AUDIO_CAPTURE")) { + permissionList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS); + permissionList.add(Manifest.permission.RECORD_AUDIO); + } + if (!permissionList.isEmpty() && isRequestPermissionRequired) { + String[] permissions = permissionList.toArray(new String[0]); + permissionListener = + isGranted -> { + if (isGranted) { + request.grant(request.getResources()); + } else { + request.deny(); + } + }; + permissionLauncher.launch(permissions); + } else { + request.grant(request.getResources()); + } + } + + /** + * Show the browser alert modal + * @param view + * @param url + * @param message + * @param result + * @return + */ + @Override + public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { + if (bridge.getActivity().isFinishing()) { + return true; + } + + AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); + builder + .setMessage(message) + .setPositiveButton( + "OK", + (dialog, buttonIndex) -> { + dialog.dismiss(); + result.confirm(); + } + ) + .setOnCancelListener( + dialog -> { + dialog.dismiss(); + result.cancel(); + } + ); + + AlertDialog dialog = builder.create(); + + dialog.show(); + + return true; + } + + /** + * Show the browser confirm modal + * @param view + * @param url + * @param message + * @param result + * @return + */ + @Override + public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { + if (bridge.getActivity().isFinishing()) { + return true; + } + + final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); + + builder + .setMessage(message) + .setPositiveButton( + "OK", + (dialog, buttonIndex) -> { + dialog.dismiss(); + result.confirm(); + } + ) + .setNegativeButton( + "Cancel", + (dialog, buttonIndex) -> { + dialog.dismiss(); + result.cancel(); + } + ) + .setOnCancelListener( + dialog -> { + dialog.dismiss(); + result.cancel(); + } + ); + + AlertDialog dialog = builder.create(); + + dialog.show(); + + return true; + } + + /** + * Show the browser prompt modal + * @param view + * @param url + * @param message + * @param defaultValue + * @param result + * @return + */ + @Override + public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) { + if (bridge.getActivity().isFinishing()) { + return true; + } + + final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); + final EditText input = new EditText(view.getContext()); + + builder + .setMessage(message) + .setView(input) + .setPositiveButton( + "OK", + (dialog, buttonIndex) -> { + dialog.dismiss(); + + String inputText1 = input.getText().toString().trim(); + result.confirm(inputText1); + } + ) + .setNegativeButton( + "Cancel", + (dialog, buttonIndex) -> { + dialog.dismiss(); + result.cancel(); + } + ) + .setOnCancelListener( + dialog -> { + dialog.dismiss(); + result.cancel(); + } + ); + + AlertDialog dialog = builder.create(); + + dialog.show(); + + return true; + } + + /** + * Handle the browser geolocation permission prompt + * @param origin + * @param callback + */ + @Override + public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { + super.onGeolocationPermissionsShowPrompt(origin, callback); + Logger.debug("onGeolocationPermissionsShowPrompt: DOING IT HERE FOR ORIGIN: " + origin); + final String[] geoPermissions = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }; + + if (!PermissionHelper.hasPermissions(bridge.getContext(), geoPermissions)) { + permissionListener = + isGranted -> { + if (isGranted) { + callback.invoke(origin, true, false); + } else { + final String[] coarsePermission = { Manifest.permission.ACCESS_COARSE_LOCATION }; + if ( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && + PermissionHelper.hasPermissions(bridge.getContext(), coarsePermission) + ) { + callback.invoke(origin, true, false); + } else { + callback.invoke(origin, false, false); + } + } + }; + permissionLauncher.launch(geoPermissions); + } else { + // permission is already granted + callback.invoke(origin, true, false); + Logger.debug("onGeolocationPermissionsShowPrompt: has required permission"); + } + } + + @Override + public boolean onShowFileChooser( + WebView webView, + final ValueCallback filePathCallback, + final FileChooserParams fileChooserParams + ) { + List acceptTypes = Arrays.asList(fileChooserParams.getAcceptTypes()); + boolean captureEnabled = fileChooserParams.isCaptureEnabled(); + boolean capturePhoto = captureEnabled && acceptTypes.contains("image/*"); + final boolean captureVideo = captureEnabled && acceptTypes.contains("video/*"); + if ((capturePhoto || captureVideo)) { + if (isMediaCaptureSupported()) { + showMediaCaptureOrFilePicker(filePathCallback, fileChooserParams, captureVideo); + } else { + permissionListener = + isGranted -> { + if (isGranted) { + showMediaCaptureOrFilePicker(filePathCallback, fileChooserParams, captureVideo); + } else { + Logger.warn(Logger.tags("FileChooser"), "Camera permission not granted"); + filePathCallback.onReceiveValue(null); + } + }; + final String[] camPermission = { Manifest.permission.CAMERA }; + permissionLauncher.launch(camPermission); + } + } else { + showFilePicker(filePathCallback, fileChooserParams); + } + + return true; + } + + private boolean isMediaCaptureSupported() { + String[] permissions = { Manifest.permission.CAMERA }; + return ( + PermissionHelper.hasPermissions(bridge.getContext(), permissions) || + !PermissionHelper.hasDefinedPermission(bridge.getContext(), Manifest.permission.CAMERA) + ); + } + + private void showMediaCaptureOrFilePicker(ValueCallback filePathCallback, FileChooserParams fileChooserParams, boolean isVideo) { + // TODO: add support for video capture on Android M and older + // On Android M and lower the VIDEO_CAPTURE_INTENT (e.g.: intent.getData()) + // returns a file:// URI instead of the expected content:// URI. + // So we disable it for now because it requires a bit more work + boolean isVideoCaptureSupported = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N; + boolean shown = false; + if (isVideo && isVideoCaptureSupported) { + shown = showVideoCapturePicker(filePathCallback); + } else { + shown = showImageCapturePicker(filePathCallback); + } + if (!shown) { + Logger.warn(Logger.tags("FileChooser"), "Media capture intent could not be launched. Falling back to default file picker."); + showFilePicker(filePathCallback, fileChooserParams); + } + } + + @SuppressLint("QueryPermissionsNeeded") + private boolean showImageCapturePicker(final ValueCallback filePathCallback) { + Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); + if (takePictureIntent.resolveActivity(bridge.getActivity().getPackageManager()) == null) { + return false; + } + + final Uri imageFileUri; + try { + imageFileUri = createImageFileUri(); + } catch (Exception ex) { + Logger.error("Unable to create temporary media capture file: " + ex.getMessage()); + return false; + } + takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri); + activityListener = + activityResult -> { + Uri[] result = null; + if (activityResult.getResultCode() == Activity.RESULT_OK) { + result = new Uri[] { imageFileUri }; + } + filePathCallback.onReceiveValue(result); + }; + activityLauncher.launch(takePictureIntent); + + return true; + } + + @SuppressLint("QueryPermissionsNeeded") + private boolean showVideoCapturePicker(final ValueCallback filePathCallback) { + Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); + if (takeVideoIntent.resolveActivity(bridge.getActivity().getPackageManager()) == null) { + return false; + } + + activityListener = + activityResult -> { + Uri[] result = null; + if (activityResult.getResultCode() == Activity.RESULT_OK) { + result = new Uri[] { activityResult.getData().getData() }; + } + filePathCallback.onReceiveValue(result); + }; + activityLauncher.launch(takeVideoIntent); + + return true; + } + + private void showFilePicker(final ValueCallback filePathCallback, FileChooserParams fileChooserParams) { + Intent intent = fileChooserParams.createIntent(); + if (fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE) { + intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); + } + if (fileChooserParams.getAcceptTypes().length > 1 || intent.getType().startsWith(".")) { + String[] validTypes = getValidTypes(fileChooserParams.getAcceptTypes()); + intent.putExtra(Intent.EXTRA_MIME_TYPES, validTypes); + if (intent.getType().startsWith(".")) { + intent.setType(validTypes[0]); + } + } + try { + activityListener = + activityResult -> { + Uri[] result; + Intent resultIntent = activityResult.getData(); + if (activityResult.getResultCode() == Activity.RESULT_OK && resultIntent.getClipData() != null) { + final int numFiles = resultIntent.getClipData().getItemCount(); + result = new Uri[numFiles]; + for (int i = 0; i < numFiles; i++) { + result[i] = resultIntent.getClipData().getItemAt(i).getUri(); + } + } else { + result = WebChromeClient.FileChooserParams.parseResult(activityResult.getResultCode(), resultIntent); + } + filePathCallback.onReceiveValue(result); + }; + activityLauncher.launch(intent); + } catch (ActivityNotFoundException e) { + filePathCallback.onReceiveValue(null); + } + } + + private String[] getValidTypes(String[] currentTypes) { + List validTypes = new ArrayList<>(); + MimeTypeMap mtm = MimeTypeMap.getSingleton(); + for (String mime : currentTypes) { + if (mime.startsWith(".")) { + String extension = mime.substring(1); + String extensionMime = mtm.getMimeTypeFromExtension(extension); + if (extensionMime != null && !validTypes.contains(extensionMime)) { + validTypes.add(extensionMime); + } + } else if (!validTypes.contains(mime)) { + validTypes.add(mime); + } + } + Object[] validObj = validTypes.toArray(); + return Arrays.copyOf(validObj, validObj.length, String[].class); + } + + @Override + public boolean onConsoleMessage(ConsoleMessage consoleMessage) { + String tag = Logger.tags("Console"); + if (consoleMessage.message() != null && isValidMsg(consoleMessage.message())) { + String msg = String.format( + "File: %s - Line %d - Msg: %s", + consoleMessage.sourceId(), + consoleMessage.lineNumber(), + consoleMessage.message() + ); + String level = consoleMessage.messageLevel().name(); + if ("ERROR".equalsIgnoreCase(level)) { + Logger.error(tag, msg, null); + } else if ("WARNING".equalsIgnoreCase(level)) { + Logger.warn(tag, msg); + } else if ("TIP".equalsIgnoreCase(level)) { + Logger.debug(tag, msg); + } else { + Logger.info(tag, msg); + } + } + return true; + } + + public boolean isValidMsg(String msg) { + return !( + msg.contains("%cresult %c") || + (msg.contains("%cnative %c")) || + msg.equalsIgnoreCase("[object Object]") || + msg.equalsIgnoreCase("console.groupEnd") + ); + } + + private Uri createImageFileUri() throws IOException { + Activity activity = bridge.getActivity(); + File photoFile = createImageFile(activity); + return FileProvider.getUriForFile(activity, bridge.getContext().getPackageName() + ".fileprovider", photoFile); + } + + private File createImageFile(Activity activity) throws IOException { + // Create an image file name + String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + String imageFileName = "JPEG_" + timeStamp + "_"; + File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES); + + return File.createTempFile(imageFileName, ".jpg", storageDir); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeWebViewClient.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeWebViewClient.java new file mode 100644 index 0000000..c434247 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/BridgeWebViewClient.java @@ -0,0 +1,111 @@ +package com.getcapacitor; + +import android.graphics.Bitmap; +import android.net.Uri; +import android.webkit.RenderProcessGoneDetail; +import android.webkit.WebResourceError; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import java.util.List; + +public class BridgeWebViewClient extends WebViewClient { + + private Bridge bridge; + + public BridgeWebViewClient(Bridge bridge) { + this.bridge = bridge; + } + + @Override + public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { + return bridge.getLocalServer().shouldInterceptRequest(request); + } + + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { + Uri url = request.getUrl(); + return bridge.launchIntent(url); + } + + @Deprecated + @Override + public boolean shouldOverrideUrlLoading(WebView view, String url) { + return bridge.launchIntent(Uri.parse(url)); + } + + @Override + public void onPageFinished(WebView view, String url) { + super.onPageFinished(view, url); + List webViewListeners = bridge.getWebViewListeners(); + + if (webViewListeners != null && view.getProgress() == 100) { + for (WebViewListener listener : bridge.getWebViewListeners()) { + listener.onPageLoaded(view); + } + } + } + + @Override + public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { + super.onReceivedError(view, request, error); + + List webViewListeners = bridge.getWebViewListeners(); + if (webViewListeners != null) { + for (WebViewListener listener : bridge.getWebViewListeners()) { + listener.onReceivedError(view); + } + } + + String errorPath = bridge.getErrorUrl(); + if (errorPath != null && request.isForMainFrame()) { + view.loadUrl(errorPath); + } + } + + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + super.onPageStarted(view, url, favicon); + bridge.reset(); + List webViewListeners = bridge.getWebViewListeners(); + + if (webViewListeners != null) { + for (WebViewListener listener : bridge.getWebViewListeners()) { + listener.onPageStarted(view); + } + } + } + + @Override + public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { + super.onReceivedHttpError(view, request, errorResponse); + + List webViewListeners = bridge.getWebViewListeners(); + if (webViewListeners != null) { + for (WebViewListener listener : bridge.getWebViewListeners()) { + listener.onReceivedHttpError(view); + } + } + + String errorPath = bridge.getErrorUrl(); + if (errorPath != null && request.isForMainFrame()) { + view.loadUrl(errorPath); + } + } + + @Override + public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) { + super.onRenderProcessGone(view, detail); + boolean result = false; + + List webViewListeners = bridge.getWebViewListeners(); + if (webViewListeners != null) { + for (WebViewListener listener : bridge.getWebViewListeners()) { + result = listener.onRenderProcessGone(view, detail) || result; + } + } + + return result; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java new file mode 100644 index 0000000..63db2a4 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/CapConfig.java @@ -0,0 +1,670 @@ +package com.getcapacitor; + +import static com.getcapacitor.Bridge.CAPACITOR_HTTP_SCHEME; +import static com.getcapacitor.Bridge.DEFAULT_ANDROID_WEBVIEW_VERSION; +import static com.getcapacitor.Bridge.DEFAULT_HUAWEI_WEBVIEW_VERSION; +import static com.getcapacitor.Bridge.MINIMUM_ANDROID_WEBVIEW_VERSION; +import static com.getcapacitor.Bridge.MINIMUM_HUAWEI_WEBVIEW_VERSION; +import static com.getcapacitor.FileUtils.readFileFromAssets; + +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.res.AssetManager; +import androidx.annotation.Nullable; +import com.getcapacitor.util.JSONUtils; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Represents the configuration options for Capacitor + */ +public class CapConfig { + + private static final String LOG_BEHAVIOR_NONE = "none"; + private static final String LOG_BEHAVIOR_DEBUG = "debug"; + private static final String LOG_BEHAVIOR_PRODUCTION = "production"; + + // Server Config + private boolean html5mode = true; + private String serverUrl; + private String hostname = "localhost"; + private String androidScheme = CAPACITOR_HTTP_SCHEME; + private String[] allowNavigation; + + // Android Config + private String overriddenUserAgentString; + private String appendedUserAgentString; + private String backgroundColor; + private boolean allowMixedContent = false; + private boolean captureInput = false; + private boolean webContentsDebuggingEnabled = false; + private boolean loggingEnabled = true; + private boolean initialFocus = true; + private boolean useLegacyBridge = false; + private int minWebViewVersion = DEFAULT_ANDROID_WEBVIEW_VERSION; + private int minHuaweiWebViewVersion = DEFAULT_HUAWEI_WEBVIEW_VERSION; + private String errorPath; + + // Embedded + private String startPath; + + // Plugins + private Map pluginsConfiguration = null; + + // Config Object JSON (legacy) + private JSONObject configJSON = new JSONObject(); + + /** + * Constructs an empty config file. + */ + private CapConfig() {} + + /** + * Get an instance of the Config file object. + * @deprecated use {@link #loadDefault(Context)} to load an instance of the Config object + * from the capacitor.config.json file, or use the {@link CapConfig.Builder} to construct + * a CapConfig for embedded use. + * + * @param assetManager The AssetManager used to load the config file + * @param config JSON describing a configuration to use + */ + @Deprecated + public CapConfig(AssetManager assetManager, JSONObject config) { + if (config != null) { + this.configJSON = config; + } else { + // Load the capacitor.config.json + loadConfigFromAssets(assetManager, null); + } + + deserializeConfig(null); + } + + /** + * Constructs a Capacitor Configuration from config.json file. + * + * @param context The context. + * @return A loaded config file, if successful. + */ + public static CapConfig loadDefault(Context context) { + CapConfig config = new CapConfig(); + + if (context == null) { + Logger.error("Capacitor Config could not be created from file. Context must not be null."); + return config; + } + + config.loadConfigFromAssets(context.getAssets(), null); + config.deserializeConfig(context); + return config; + } + + /** + * Constructs a Capacitor Configuration from config.json file within the app assets. + * + * @param context The context. + * @param path A path relative to the root assets directory. + * @return A loaded config file, if successful. + */ + public static CapConfig loadFromAssets(Context context, String path) { + CapConfig config = new CapConfig(); + + if (context == null) { + Logger.error("Capacitor Config could not be created from file. Context must not be null."); + return config; + } + + config.loadConfigFromAssets(context.getAssets(), path); + config.deserializeConfig(context); + return config; + } + + /** + * Constructs a Capacitor Configuration from config.json file within the app file-space. + * + * @param context The context. + * @param path A path relative to the root of the app file-space. + * @return A loaded config file, if successful. + */ + public static CapConfig loadFromFile(Context context, String path) { + CapConfig config = new CapConfig(); + + if (context == null) { + Logger.error("Capacitor Config could not be created from file. Context must not be null."); + return config; + } + + config.loadConfigFromFile(path); + config.deserializeConfig(context); + return config; + } + + /** + * Constructs a Capacitor Configuration using ConfigBuilder. + * + * @param builder A config builder initialized with values + */ + private CapConfig(Builder builder) { + // Server Config + this.html5mode = builder.html5mode; + this.serverUrl = builder.serverUrl; + this.hostname = builder.hostname; + + if (this.validateScheme(builder.androidScheme)) { + this.androidScheme = builder.androidScheme; + } + + this.allowNavigation = builder.allowNavigation; + + // Android Config + this.overriddenUserAgentString = builder.overriddenUserAgentString; + this.appendedUserAgentString = builder.appendedUserAgentString; + this.backgroundColor = builder.backgroundColor; + this.allowMixedContent = builder.allowMixedContent; + this.captureInput = builder.captureInput; + this.webContentsDebuggingEnabled = builder.webContentsDebuggingEnabled; + this.loggingEnabled = builder.loggingEnabled; + this.initialFocus = builder.initialFocus; + this.useLegacyBridge = builder.useLegacyBridge; + this.minWebViewVersion = builder.minWebViewVersion; + this.minHuaweiWebViewVersion = builder.minHuaweiWebViewVersion; + this.errorPath = builder.errorPath; + + // Embedded + this.startPath = builder.startPath; + + // Plugins Config + this.pluginsConfiguration = builder.pluginsConfiguration; + } + + /** + * Loads a Capacitor Configuration JSON file into a Capacitor Configuration object. + * An optional path string can be provided to look for the config in a subdirectory path. + */ + private void loadConfigFromAssets(AssetManager assetManager, String path) { + if (path == null) { + path = ""; + } else { + // Add slash at the end to form a proper file path if going deeper in assets dir + if (path.charAt(path.length() - 1) != '/') { + path = path + "/"; + } + } + + try { + String jsonString = readFileFromAssets(assetManager, path + "capacitor.config.json"); + configJSON = new JSONObject(jsonString); + } catch (IOException ex) { + Logger.error("Unable to load capacitor.config.json. Run npx cap copy first", ex); + } catch (JSONException ex) { + Logger.error("Unable to parse capacitor.config.json. Make sure it's valid json", ex); + } + } + + /** + * Loads a Capacitor Configuration JSON file into a Capacitor Configuration object. + * An optional path string can be provided to look for the config in a subdirectory path. + */ + private void loadConfigFromFile(String path) { + if (path == null) { + path = ""; + } else { + // Add slash at the end to form a proper file path if going deeper in assets dir + if (path.charAt(path.length() - 1) != '/') { + path = path + "/"; + } + } + + try { + File configFile = new File(path + "capacitor.config.json"); + String jsonString = FileUtils.readFileFromDisk(configFile); + configJSON = new JSONObject(jsonString); + } catch (JSONException ex) { + Logger.error("Unable to parse capacitor.config.json. Make sure it's valid json", ex); + } catch (IOException ex) { + Logger.error("Unable to load capacitor.config.json.", ex); + } + } + + /** + * Deserializes the config from JSON into a Capacitor Configuration object. + */ + private void deserializeConfig(@Nullable Context context) { + boolean isDebug = context != null && (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; + + // Server + html5mode = JSONUtils.getBoolean(configJSON, "server.html5mode", html5mode); + serverUrl = JSONUtils.getString(configJSON, "server.url", null); + hostname = JSONUtils.getString(configJSON, "server.hostname", hostname); + errorPath = JSONUtils.getString(configJSON, "server.errorPath", null); + + String configSchema = JSONUtils.getString(configJSON, "server.androidScheme", androidScheme); + if (this.validateScheme(configSchema)) { + androidScheme = configSchema; + } + + allowNavigation = JSONUtils.getArray(configJSON, "server.allowNavigation", null); + + // Android + overriddenUserAgentString = + JSONUtils.getString(configJSON, "android.overrideUserAgent", JSONUtils.getString(configJSON, "overrideUserAgent", null)); + appendedUserAgentString = + JSONUtils.getString(configJSON, "android.appendUserAgent", JSONUtils.getString(configJSON, "appendUserAgent", null)); + backgroundColor = + JSONUtils.getString(configJSON, "android.backgroundColor", JSONUtils.getString(configJSON, "backgroundColor", null)); + allowMixedContent = + JSONUtils.getBoolean( + configJSON, + "android.allowMixedContent", + JSONUtils.getBoolean(configJSON, "allowMixedContent", allowMixedContent) + ); + minWebViewVersion = JSONUtils.getInt(configJSON, "android.minWebViewVersion", DEFAULT_ANDROID_WEBVIEW_VERSION); + minHuaweiWebViewVersion = JSONUtils.getInt(configJSON, "android.minHuaweiWebViewVersion", DEFAULT_HUAWEI_WEBVIEW_VERSION); + captureInput = JSONUtils.getBoolean(configJSON, "android.captureInput", captureInput); + useLegacyBridge = JSONUtils.getBoolean(configJSON, "android.useLegacyBridge", useLegacyBridge); + webContentsDebuggingEnabled = JSONUtils.getBoolean(configJSON, "android.webContentsDebuggingEnabled", isDebug); + + String logBehavior = JSONUtils.getString( + configJSON, + "android.loggingBehavior", + JSONUtils.getString(configJSON, "loggingBehavior", LOG_BEHAVIOR_DEBUG) + ); + switch (logBehavior.toLowerCase(Locale.ROOT)) { + case LOG_BEHAVIOR_PRODUCTION: + loggingEnabled = true; + break; + case LOG_BEHAVIOR_NONE: + loggingEnabled = false; + break; + default: // LOG_BEHAVIOR_DEBUG + loggingEnabled = isDebug; + } + + initialFocus = JSONUtils.getBoolean(configJSON, "android.initialFocus", initialFocus); + + // Plugins + pluginsConfiguration = deserializePluginsConfig(JSONUtils.getObject(configJSON, "plugins")); + } + + private boolean validateScheme(String scheme) { + List invalidSchemes = Arrays.asList("file", "ftp", "ftps", "ws", "wss", "about", "blob", "data"); + if (invalidSchemes.contains(scheme)) { + Logger.warn(scheme + " is not an allowed scheme. Defaulting to http."); + return false; + } + + // Non-http(s) schemes are not allowed to modify the URL path as of Android Webview 117 + if (!scheme.equals("http") && !scheme.equals("https")) { + Logger.warn( + "Using a non-standard scheme: " + scheme + " for Android. This is known to cause issues as of Android Webview 117." + ); + } + + return true; + } + + public boolean isHTML5Mode() { + return html5mode; + } + + public String getServerUrl() { + return serverUrl; + } + + public String getErrorPath() { + return errorPath; + } + + public String getHostname() { + return hostname; + } + + public String getStartPath() { + return startPath; + } + + public String getAndroidScheme() { + return androidScheme; + } + + public String[] getAllowNavigation() { + return allowNavigation; + } + + public String getOverriddenUserAgentString() { + return overriddenUserAgentString; + } + + public String getAppendedUserAgentString() { + return appendedUserAgentString; + } + + public String getBackgroundColor() { + return backgroundColor; + } + + public boolean isMixedContentAllowed() { + return allowMixedContent; + } + + public boolean isInputCaptured() { + return captureInput; + } + + public boolean isWebContentsDebuggingEnabled() { + return webContentsDebuggingEnabled; + } + + public boolean isLoggingEnabled() { + return loggingEnabled; + } + + public boolean isInitialFocus() { + return initialFocus; + } + + public boolean isUsingLegacyBridge() { + return useLegacyBridge; + } + + public int getMinWebViewVersion() { + if (minWebViewVersion < MINIMUM_ANDROID_WEBVIEW_VERSION) { + Logger.warn("Specified minimum webview version is too low, defaulting to " + MINIMUM_ANDROID_WEBVIEW_VERSION); + return MINIMUM_ANDROID_WEBVIEW_VERSION; + } + + return minWebViewVersion; + } + + public int getMinHuaweiWebViewVersion() { + if (minHuaweiWebViewVersion < MINIMUM_HUAWEI_WEBVIEW_VERSION) { + Logger.warn("Specified minimum Huawei webview version is too low, defaulting to " + MINIMUM_HUAWEI_WEBVIEW_VERSION); + return MINIMUM_HUAWEI_WEBVIEW_VERSION; + } + + return minHuaweiWebViewVersion; + } + + public PluginConfig getPluginConfiguration(String pluginId) { + PluginConfig pluginConfig = pluginsConfiguration.get(pluginId); + if (pluginConfig == null) { + pluginConfig = new PluginConfig(new JSONObject()); + } + + return pluginConfig; + } + + /** + * Get a JSON object value from the Capacitor config. + * @deprecated use {@link PluginConfig#getObject(String)} to access plugin config values. + * For main Capacitor config values, use the appropriate getter. + * + * @param key A key to fetch from the config + * @return The value from the config, if exists. Null if not + */ + @Deprecated + public JSONObject getObject(String key) { + try { + return configJSON.getJSONObject(key); + } catch (Exception ex) {} + return null; + } + + /** + * Get a string value from the Capacitor config. + * @deprecated use {@link PluginConfig#getString(String, String)} to access plugin config + * values. For main Capacitor config values, use the appropriate getter. + * + * @param key A key to fetch from the config + * @return The value from the config, if exists. Null if not + */ + @Deprecated + public String getString(String key) { + return JSONUtils.getString(configJSON, key, null); + } + + /** + * Get a string value from the Capacitor config. + * @deprecated use {@link PluginConfig#getString(String, String)} to access plugin config + * values. For main Capacitor config values, use the appropriate getter. + * + * @param key A key to fetch from the config + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + @Deprecated + public String getString(String key, String defaultValue) { + return JSONUtils.getString(configJSON, key, defaultValue); + } + + /** + * Get a boolean value from the Capacitor config. + * @deprecated use {@link PluginConfig#getBoolean(String, boolean)} to access plugin config + * values. For main Capacitor config values, use the appropriate getter. + * + * @param key A key to fetch from the config + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + @Deprecated + public boolean getBoolean(String key, boolean defaultValue) { + return JSONUtils.getBoolean(configJSON, key, defaultValue); + } + + /** + * Get an integer value from the Capacitor config. + * @deprecated use {@link PluginConfig#getInt(String, int)} to access the plugin config + * values. For main Capacitor config values, use the appropriate getter. + * + * @param key A key to fetch from the config + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + @Deprecated + public int getInt(String key, int defaultValue) { + return JSONUtils.getInt(configJSON, key, defaultValue); + } + + /** + * Get a string array value from the Capacitor config. + * @deprecated use {@link PluginConfig#getArray(String)} to access the plugin config + * values. For main Capacitor config values, use the appropriate getter. + * + * @param key A key to fetch from the config + * @return The value from the config, if exists. Null if not + */ + @Deprecated + public String[] getArray(String key) { + return JSONUtils.getArray(configJSON, key, null); + } + + /** + * Get a string array value from the Capacitor config. + * @deprecated use {@link PluginConfig#getArray(String, String[])} to access the plugin + * config values. For main Capacitor config values, use the appropriate getter. + * + * @param key A key to fetch from the config + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + @Deprecated + public String[] getArray(String key, String[] defaultValue) { + return JSONUtils.getArray(configJSON, key, defaultValue); + } + + private static Map deserializePluginsConfig(JSONObject pluginsConfig) { + Map pluginsMap = new HashMap<>(); + + // return an empty map if there is no pluginsConfig json + if (pluginsConfig == null) { + return pluginsMap; + } + + Iterator pluginIds = pluginsConfig.keys(); + + while (pluginIds.hasNext()) { + String pluginId = pluginIds.next(); + JSONObject value = null; + + try { + value = pluginsConfig.getJSONObject(pluginId); + PluginConfig pluginConfig = new PluginConfig(value); + pluginsMap.put(pluginId, pluginConfig); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + return pluginsMap; + } + + /** + * Builds a Capacitor Configuration in code + */ + public static class Builder { + + private Context context; + + // Server Config Values + private boolean html5mode = true; + private String serverUrl; + private String errorPath; + private String hostname = "localhost"; + private String androidScheme = CAPACITOR_HTTP_SCHEME; + private String[] allowNavigation; + + // Android Config Values + private String overriddenUserAgentString; + private String appendedUserAgentString; + private String backgroundColor; + private boolean allowMixedContent = false; + private boolean captureInput = false; + private Boolean webContentsDebuggingEnabled = null; + private boolean loggingEnabled = true; + private boolean initialFocus = false; + private boolean useLegacyBridge = false; + private int minWebViewVersion = DEFAULT_ANDROID_WEBVIEW_VERSION; + private int minHuaweiWebViewVersion = DEFAULT_HUAWEI_WEBVIEW_VERSION; + + // Embedded + private String startPath = null; + + // Plugins Config Object + private Map pluginsConfiguration = new HashMap<>(); + + /** + * Constructs a new CapConfig Builder. + * + * @param context The context + */ + public Builder(Context context) { + this.context = context; + } + + /** + * Builds a Capacitor Config from the builder. + * + * @return A new Capacitor Config + */ + public CapConfig create() { + if (webContentsDebuggingEnabled == null) { + webContentsDebuggingEnabled = (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; + } + + return new CapConfig(this); + } + + public Builder setPluginsConfiguration(JSONObject pluginsConfiguration) { + this.pluginsConfiguration = deserializePluginsConfig(pluginsConfiguration); + return this; + } + + public Builder setHTML5mode(boolean html5mode) { + this.html5mode = html5mode; + return this; + } + + public Builder setServerUrl(String serverUrl) { + this.serverUrl = serverUrl; + return this; + } + + public Builder setErrorPath(String errorPath) { + this.errorPath = errorPath; + return this; + } + + public Builder setHostname(String hostname) { + this.hostname = hostname; + return this; + } + + public Builder setStartPath(String path) { + this.startPath = path; + return this; + } + + public Builder setAndroidScheme(String androidScheme) { + this.androidScheme = androidScheme; + return this; + } + + public Builder setAllowNavigation(String[] allowNavigation) { + this.allowNavigation = allowNavigation; + return this; + } + + public Builder setOverriddenUserAgentString(String overriddenUserAgentString) { + this.overriddenUserAgentString = overriddenUserAgentString; + return this; + } + + public Builder setAppendedUserAgentString(String appendedUserAgentString) { + this.appendedUserAgentString = appendedUserAgentString; + return this; + } + + public Builder setBackgroundColor(String backgroundColor) { + this.backgroundColor = backgroundColor; + return this; + } + + public Builder setAllowMixedContent(boolean allowMixedContent) { + this.allowMixedContent = allowMixedContent; + return this; + } + + public Builder setCaptureInput(boolean captureInput) { + this.captureInput = captureInput; + return this; + } + + public Builder setUseLegacyBridge(boolean useLegacyBridge) { + this.useLegacyBridge = useLegacyBridge; + return this; + } + + public Builder setWebContentsDebuggingEnabled(boolean webContentsDebuggingEnabled) { + this.webContentsDebuggingEnabled = webContentsDebuggingEnabled; + return this; + } + + public Builder setLoggingEnabled(boolean enabled) { + this.loggingEnabled = enabled; + return this; + } + + public Builder setInitialFocus(boolean focus) { + this.initialFocus = focus; + return this; + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/CapacitorWebView.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/CapacitorWebView.java new file mode 100644 index 0000000..e46b904 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/CapacitorWebView.java @@ -0,0 +1,52 @@ +package com.getcapacitor; + +import android.content.Context; +import android.util.AttributeSet; +import android.view.KeyEvent; +import android.view.inputmethod.BaseInputConnection; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.webkit.WebView; + +public class CapacitorWebView extends WebView { + + private BaseInputConnection capInputConnection; + private Bridge bridge; + + public CapacitorWebView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public void setBridge(Bridge bridge) { + this.bridge = bridge; + } + + @Override + public InputConnection onCreateInputConnection(EditorInfo outAttrs) { + CapConfig config; + if (bridge != null) { + config = bridge.getConfig(); + } else { + config = CapConfig.loadDefault(getContext()); + } + + boolean captureInput = config.isInputCaptured(); + if (captureInput) { + if (capInputConnection == null) { + capInputConnection = new BaseInputConnection(this, false); + } + return capInputConnection; + } + return super.onCreateInputConnection(outAttrs); + } + + @Override + @SuppressWarnings("deprecation") + public boolean dispatchKeyEvent(KeyEvent event) { + if (event.getAction() == KeyEvent.ACTION_MULTIPLE) { + evaluateJavascript("document.activeElement.value = document.activeElement.value + '" + event.getCharacters() + "';", null); + return false; + } + return super.dispatchKeyEvent(event); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/FileUtils.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/FileUtils.java new file mode 100644 index 0000000..47add8c --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/FileUtils.java @@ -0,0 +1,292 @@ +/** + * Portions adopted from react-native-image-crop-picker + * + * MIT License + + * Copyright (c) 2017 Ivan Pusic + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall 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. + */ +package com.getcapacitor; + +import android.content.ContentUris; +import android.content.Context; +import android.content.res.AssetManager; +import android.database.Cursor; +import android.net.Uri; +import android.os.Environment; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.provider.OpenableColumns; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +/** + * Common File utilities, such as resolve content URIs and + * creating portable web paths from low-level files + */ +public class FileUtils { + + private static String CapacitorFileScheme = Bridge.CAPACITOR_FILE_START; + + public enum Type { + IMAGE("image"); + + private String type; + + Type(String type) { + this.type = type; + } + } + + public static String getPortablePath(Context c, String host, Uri u) { + String path = getFileUrlForUri(c, u); + if (path.startsWith("file://")) { + path = path.replace("file://", ""); + } + return host + Bridge.CAPACITOR_FILE_START + path; + } + + public static String getFileUrlForUri(final Context context, final Uri uri) { + // DocumentProvider + if (DocumentsContract.isDocumentUri(context, uri)) { + // ExternalStorageProvider + if (isExternalStorageDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + if ("primary".equalsIgnoreCase(type)) { + return legacyPrimaryPath(split[1]); + } else { + final int splitIndex = docId.indexOf(':', 1); + final String tag = docId.substring(0, splitIndex); + final String path = docId.substring(splitIndex + 1); + + String nonPrimaryVolume = getPathToNonPrimaryVolume(context, tag); + if (nonPrimaryVolume != null) { + String result = nonPrimaryVolume + "/" + path; + File file = new File(result); + if (file.exists() && file.canRead()) { + return result; + } + return null; + } + } + } + // DownloadsProvider + else if (isDownloadsDocument(uri)) { + final String id = DocumentsContract.getDocumentId(uri); + final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); + + return getDataColumn(context, contentUri, null, null); + } + // MediaProvider + else if (isMediaDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + Uri contentUri = null; + if ("image".equals(type)) { + contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; + } else if ("video".equals(type)) { + contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; + } else if ("audio".equals(type)) { + contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; + } + + final String selection = "_id=?"; + final String[] selectionArgs = new String[] { split[1] }; + + return getDataColumn(context, contentUri, selection, selectionArgs); + } + } + // MediaStore (and general) + else if ("content".equalsIgnoreCase(uri.getScheme())) { + // Return the remote address + if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); + return getDataColumn(context, uri, null, null); + } + // File + else if ("file".equalsIgnoreCase(uri.getScheme())) { + return uri.getPath(); + } + + return null; + } + + @SuppressWarnings("deprecation") + private static String legacyPrimaryPath(String pathPart) { + return Environment.getExternalStorageDirectory() + "/" + pathPart; + } + + /** + * Read a plaintext file from the assets directory. + * + * @param assetManager Used to open the file. + * @param fileName The path of the file to read. + * @return The contents of the file path. + * @throws IOException Thrown if any issues reading the provided file path. + */ + static String readFileFromAssets(AssetManager assetManager, String fileName) throws IOException { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(assetManager.open(fileName)))) { + StringBuilder buffer = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + buffer.append(line).append("\n"); + } + + return buffer.toString(); + } + } + + /** + * Read a plaintext file from within the app disk space. + * + * @param file The file to read. + * @return The contents of the file path. + * @throws IOException Thrown if any issues reading the provided file path. + */ + static String readFileFromDisk(File file) throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + StringBuilder buffer = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + buffer.append(line).append("\n"); + } + + return buffer.toString(); + } + } + + /** + * Get the value of the data column for this Uri. This is useful for + * MediaStore Uris, and other file-based ContentProviders. + * + * @param context The context. + * @param uri The Uri to query. + * @param selection (Optional) Filter used in the query. + * @param selectionArgs (Optional) Selection arguments used in the query. + * @return The value of the _data column, which is typically a file path. + */ + private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { + String path = null; + Cursor cursor = null; + final String column = "_data"; + final String[] projection = { column }; + + try { + cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); + if (cursor != null && cursor.moveToFirst()) { + final int index = cursor.getColumnIndexOrThrow(column); + path = cursor.getString(index); + } + } catch (IllegalArgumentException ex) { + return getCopyFilePath(uri, context); + } finally { + if (cursor != null) cursor.close(); + } + if (path == null) { + return getCopyFilePath(uri, context); + } + return path; + } + + private static String getCopyFilePath(Uri uri, Context context) { + Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); + int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); + cursor.moveToFirst(); + String name = (cursor.getString(nameIndex)); + File file = new File(context.getFilesDir(), name); + try { + InputStream inputStream = context.getContentResolver().openInputStream(uri); + FileOutputStream outputStream = new FileOutputStream(file); + int read = 0; + int maxBufferSize = 1024 * 1024; + int bufferSize = Math.min(inputStream.available(), maxBufferSize); + final byte[] buffers = new byte[bufferSize]; + while ((read = inputStream.read(buffers)) != -1) { + outputStream.write(buffers, 0, read); + } + inputStream.close(); + outputStream.close(); + } catch (Exception e) { + return null; + } finally { + if (cursor != null) cursor.close(); + } + return file.getPath(); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is ExternalStorageProvider. + */ + private static boolean isExternalStorageDocument(Uri uri) { + return "com.android.externalstorage.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is DownloadsProvider. + */ + private static boolean isDownloadsDocument(Uri uri) { + return "com.android.providers.downloads.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is MediaProvider. + */ + private static boolean isMediaDocument(Uri uri) { + return "com.android.providers.media.documents".equals(uri.getAuthority()); + } + + /** + * @param uri The Uri to check. + * @return Whether the Uri authority is Google Photos. + */ + private static boolean isGooglePhotosUri(Uri uri) { + return "com.google.android.apps.photos.content".equals(uri.getAuthority()); + } + + private static String getPathToNonPrimaryVolume(Context context, String tag) { + File[] volumes = context.getExternalCacheDirs(); + if (volumes != null) { + for (File volume : volumes) { + if (volume != null) { + String path = volume.getAbsolutePath(); + if (path != null) { + int index = path.indexOf(tag); + if (index != -1) { + return path.substring(0, index) + tag; + } + } + } + } + } + return null; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/InvalidPluginException.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/InvalidPluginException.java new file mode 100644 index 0000000..1757e32 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/InvalidPluginException.java @@ -0,0 +1,8 @@ +package com.getcapacitor; + +class InvalidPluginException extends Exception { + + public InvalidPluginException(String s) { + super(s); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/InvalidPluginMethodException.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/InvalidPluginMethodException.java new file mode 100644 index 0000000..94be491 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/InvalidPluginMethodException.java @@ -0,0 +1,16 @@ +package com.getcapacitor; + +class InvalidPluginMethodException extends Exception { + + public InvalidPluginMethodException(String s) { + super(s); + } + + public InvalidPluginMethodException(Throwable t) { + super(t); + } + + public InvalidPluginMethodException(String s, Throwable t) { + super(s, t); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSArray.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSArray.java new file mode 100644 index 0000000..06b7f4d --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSArray.java @@ -0,0 +1,51 @@ +package com.getcapacitor; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; + +public class JSArray extends JSONArray { + + public JSArray() { + super(); + } + + public JSArray(String json) throws JSONException { + super(json); + } + + public JSArray(Collection copyFrom) { + super(copyFrom); + } + + public JSArray(Object array) throws JSONException { + super(array); + } + + @SuppressWarnings("unchecked") + public List toList() throws JSONException { + List items = new ArrayList<>(); + Object o = null; + for (int i = 0; i < this.length(); i++) { + o = this.get(i); + try { + items.add((E) this.get(i)); + } catch (Exception ex) { + throw new JSONException("Not all items are instances of the given type"); + } + } + return items; + } + + /** + * Create a new JSArray without throwing a error + */ + public static JSArray from(Object array) { + try { + return new JSArray(array); + } catch (JSONException ex) {} + return null; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSExport.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSExport.java new file mode 100644 index 0000000..382f4b5 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSExport.java @@ -0,0 +1,193 @@ +package com.getcapacitor; + +import static com.getcapacitor.FileUtils.readFileFromAssets; + +import android.content.Context; +import android.text.TextUtils; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class JSExport { + + private static String CATCHALL_OPTIONS_PARAM = "_options"; + private static String CALLBACK_PARAM = "_callback"; + + public static String getGlobalJS(Context context, boolean loggingEnabled, boolean isDebug) { + return "window.Capacitor = { DEBUG: " + isDebug + ", isLoggingEnabled: " + loggingEnabled + ", Plugins: {} };"; + } + + public static String getCordovaJS(Context context) { + String fileContent = ""; + try { + fileContent = readFileFromAssets(context.getAssets(), "public/cordova.js"); + } catch (IOException ex) { + Logger.error("Unable to read public/cordova.js file, Cordova plugins will not work"); + } + return fileContent; + } + + public static String getCordovaPluginsFileJS(Context context) { + String fileContent = ""; + try { + fileContent = readFileFromAssets(context.getAssets(), "public/cordova_plugins.js"); + } catch (IOException ex) { + Logger.error("Unable to read public/cordova_plugins.js file, Cordova plugins will not work"); + } + return fileContent; + } + + public static String getPluginJS(Collection plugins) { + List lines = new ArrayList<>(); + JSONArray pluginArray = new JSONArray(); + + lines.add("// Begin: Capacitor Plugin JS"); + for (PluginHandle plugin : plugins) { + lines.add( + "(function(w) {\n" + + "var a = (w.Capacitor = w.Capacitor || {});\n" + + "var p = (a.Plugins = a.Plugins || {});\n" + + "var t = (p['" + + plugin.getId() + + "'] = {});\n" + + "t.addListener = function(eventName, callback) {\n" + + " return w.Capacitor.addListener('" + + plugin.getId() + + "', eventName, callback);\n" + + "}" + ); + Collection methods = plugin.getMethods(); + for (PluginMethodHandle method : methods) { + if (method.getName().equals("addListener") || method.getName().equals("removeListener")) { + // Don't export add/remove listener, we do that automatically above as they are "special snowflakes" + continue; + } + lines.add(generateMethodJS(plugin, method)); + } + + lines.add("})(window);\n"); + pluginArray.put(createPluginHeader(plugin)); + } + + return TextUtils.join("\n", lines) + "\nwindow.Capacitor.PluginHeaders = " + pluginArray.toString() + ";"; + } + + public static String getCordovaPluginJS(Context context) { + return getFilesContent(context, "public/plugins"); + } + + public static String getFilesContent(Context context, String path) { + StringBuilder builder = new StringBuilder(); + try { + String[] content = context.getAssets().list(path); + if (content.length > 0) { + for (String file : content) { + if (!file.endsWith(".map")) { + builder.append(getFilesContent(context, path + "/" + file)); + } + } + } else { + return readFileFromAssets(context.getAssets(), path); + } + } catch (IOException ex) { + Logger.warn("Unable to read file at path " + path); + } + return builder.toString(); + } + + private static JSONObject createPluginHeader(PluginHandle plugin) { + JSONObject pluginObj = new JSONObject(); + Collection methods = plugin.getMethods(); + try { + String id = plugin.getId(); + JSONArray methodArray = new JSONArray(); + pluginObj.put("name", id); + + for (PluginMethodHandle method : methods) { + methodArray.put(createPluginMethodHeader(method)); + } + + pluginObj.put("methods", methodArray); + } catch (JSONException e) { + // ignore + } + return pluginObj; + } + + private static JSONObject createPluginMethodHeader(PluginMethodHandle method) { + JSONObject methodObj = new JSONObject(); + + try { + methodObj.put("name", method.getName()); + if (!method.getReturnType().equals(PluginMethod.RETURN_NONE)) { + methodObj.put("rtype", method.getReturnType()); + } + } catch (JSONException e) { + // ignore + } + + return methodObj; + } + + public static String getBridgeJS(Context context) throws JSExportException { + return getFilesContent(context, "native-bridge.js"); + } + + private static String generateMethodJS(PluginHandle plugin, PluginMethodHandle method) { + List lines = new ArrayList<>(); + + List args = new ArrayList<>(); + // Add the catch all param that will take a full javascript object to pass to the plugin + args.add(CATCHALL_OPTIONS_PARAM); + + String returnType = method.getReturnType(); + if (returnType.equals(PluginMethod.RETURN_CALLBACK)) { + args.add(CALLBACK_PARAM); + } + + // Create the method function declaration + lines.add("t['" + method.getName() + "'] = function(" + TextUtils.join(", ", args) + ") {"); + + switch (returnType) { + case PluginMethod.RETURN_NONE: + lines.add( + "return w.Capacitor.nativeCallback('" + + plugin.getId() + + "', '" + + method.getName() + + "', " + + CATCHALL_OPTIONS_PARAM + + ")" + ); + break; + case PluginMethod.RETURN_PROMISE: + lines.add( + "return w.Capacitor.nativePromise('" + plugin.getId() + "', '" + method.getName() + "', " + CATCHALL_OPTIONS_PARAM + ")" + ); + break; + case PluginMethod.RETURN_CALLBACK: + lines.add( + "return w.Capacitor.nativeCallback('" + + plugin.getId() + + "', '" + + method.getName() + + "', " + + CATCHALL_OPTIONS_PARAM + + ", " + + CALLBACK_PARAM + + ")" + ); + break; + default: + // TODO: Do something here? + } + + lines.add("}"); + + return TextUtils.join("\n", lines); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSExportException.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSExportException.java new file mode 100644 index 0000000..14b6043 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSExportException.java @@ -0,0 +1,16 @@ +package com.getcapacitor; + +public class JSExportException extends Exception { + + public JSExportException(String s) { + super(s); + } + + public JSExportException(Throwable t) { + super(t); + } + + public JSExportException(String s, Throwable t) { + super(s, t); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSInjector.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSInjector.java new file mode 100644 index 0000000..a3871f7 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSInjector.java @@ -0,0 +1,107 @@ +package com.getcapacitor; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; + +/** + * JSInject is responsible for returning Capacitor's core + * runtime JS and any plugin JS back into HTML page responses + * to the client. + */ +class JSInjector { + + private String globalJS; + private String bridgeJS; + private String pluginJS; + private String cordovaJS; + private String cordovaPluginsJS; + private String cordovaPluginsFileJS; + private String localUrlJS; + + public JSInjector( + String globalJS, + String bridgeJS, + String pluginJS, + String cordovaJS, + String cordovaPluginsJS, + String cordovaPluginsFileJS, + String localUrlJS + ) { + this.globalJS = globalJS; + this.bridgeJS = bridgeJS; + this.pluginJS = pluginJS; + this.cordovaJS = cordovaJS; + this.cordovaPluginsJS = cordovaPluginsJS; + this.cordovaPluginsFileJS = cordovaPluginsFileJS; + this.localUrlJS = localUrlJS; + } + + /** + * Generates injectable JS content. + * This may be used in other forms of injecting that aren't using an InputStream. + * @return + */ + public String getScriptString() { + return ( + globalJS + + "\n\n" + + localUrlJS + + "\n\n" + + bridgeJS + + "\n\n" + + pluginJS + + "\n\n" + + cordovaJS + + "\n\n" + + cordovaPluginsFileJS + + "\n\n" + + cordovaPluginsJS + ); + } + + /** + * Given an InputStream from the web server, prepend it with + * our JS stream + * @param responseStream + * @return + */ + public InputStream getInjectedStream(InputStream responseStream) { + String js = ""; + String html = this.readAssetStream(responseStream); + + // Insert the js string at the position after or before using StringBuilder + StringBuilder modifiedHtml = new StringBuilder(html); + if (html.contains("")) { + modifiedHtml.insert(html.indexOf("") + "".length(), "\n" + js + "\n"); + html = modifiedHtml.toString(); + } else if (html.contains("")) { + modifiedHtml.insert(html.indexOf(""), "\n" + js + "\n"); + html = modifiedHtml.toString(); + } else { + Logger.error("Unable to inject Capacitor, Plugins won't work"); + } + return new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)); + } + + private String readAssetStream(InputStream stream) { + try { + final int bufferSize = 1024; + final char[] buffer = new char[bufferSize]; + final StringBuilder out = new StringBuilder(); + Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8); + for (;;) { + int rsz = in.read(buffer, 0, buffer.length); + if (rsz < 0) break; + out.append(buffer, 0, rsz); + } + return out.toString(); + } catch (Exception e) { + Logger.error("Unable to process HTML asset file. This is a fatal error", e); + } + + return ""; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSObject.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSObject.java new file mode 100644 index 0000000..0e98707 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSObject.java @@ -0,0 +1,164 @@ +package com.getcapacitor; + +import androidx.annotation.Nullable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * A wrapper around JSONObject that isn't afraid to do simple + * JSON put operations without having to throw an exception + * for every little thing jeez + */ +public class JSObject extends JSONObject { + + public JSObject() { + super(); + } + + public JSObject(String json) throws JSONException { + super(json); + } + + public JSObject(JSONObject obj, String[] names) throws JSONException { + super(obj, names); + } + + /** + * Convert a pathetic JSONObject into a JSObject + * @param obj + */ + public static JSObject fromJSONObject(JSONObject obj) throws JSONException { + Iterator keysIter = obj.keys(); + List keys = new ArrayList<>(); + while (keysIter.hasNext()) { + keys.add(keysIter.next()); + } + + return new JSObject(obj, keys.toArray(new String[keys.size()])); + } + + @Override + @Nullable + public String getString(String key) { + return getString(key, null); + } + + @Nullable + public String getString(String key, @Nullable String defaultValue) { + try { + String value = super.getString(key); + if (!super.isNull(key)) { + return value; + } + } catch (JSONException ex) {} + return defaultValue; + } + + @Nullable + public Integer getInteger(String key) { + return getInteger(key, null); + } + + @Nullable + public Integer getInteger(String key, @Nullable Integer defaultValue) { + try { + return super.getInt(key); + } catch (JSONException e) {} + return defaultValue; + } + + @Nullable + public Boolean getBoolean(String key, @Nullable Boolean defaultValue) { + try { + return super.getBoolean(key); + } catch (JSONException e) {} + return defaultValue; + } + + /** + * Fetch boolean from jsonObject + */ + @Nullable + public Boolean getBool(String key) { + return getBoolean(key, null); + } + + @Nullable + public JSObject getJSObject(String name) { + try { + return getJSObject(name, null); + } catch (JSONException e) {} + return null; + } + + @Nullable + public JSObject getJSObject(String name, @Nullable JSObject defaultValue) throws JSONException { + try { + Object obj = get(name); + if (obj instanceof JSONObject) { + Iterator keysIter = ((JSONObject) obj).keys(); + List keys = new ArrayList<>(); + while (keysIter.hasNext()) { + keys.add(keysIter.next()); + } + + return new JSObject((JSONObject) obj, keys.toArray(new String[keys.size()])); + } + } catch (JSONException ex) {} + return defaultValue; + } + + @Override + public JSObject put(String key, boolean value) { + try { + super.put(key, value); + } catch (JSONException ex) {} + return this; + } + + @Override + public JSObject put(String key, int value) { + try { + super.put(key, value); + } catch (JSONException ex) {} + return this; + } + + @Override + public JSObject put(String key, long value) { + try { + super.put(key, value); + } catch (JSONException ex) {} + return this; + } + + @Override + public JSObject put(String key, double value) { + try { + super.put(key, value); + } catch (JSONException ex) {} + return this; + } + + @Override + public JSObject put(String key, Object value) { + try { + super.put(key, value); + } catch (JSONException ex) {} + return this; + } + + public JSObject put(String key, String value) { + try { + super.put(key, value); + } catch (JSONException ex) {} + return this; + } + + public JSObject putSafe(String key, Object value) throws JSONException { + return (JSObject) super.put(key, value); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSValue.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSValue.java new file mode 100644 index 0000000..d97ba91 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/JSValue.java @@ -0,0 +1,65 @@ +package com.getcapacitor; + +import org.json.JSONException; + +/** + * Represents a single user-data value of any type on the capacitor PluginCall object. + */ +public class JSValue { + + private final Object value; + + /** + * @param call The capacitor plugin call, used for accessing the value safely. + * @param name The name of the property to access. + */ + public JSValue(PluginCall call, String name) { + this.value = this.toValue(call, name); + } + + /** + * Returns the coerced but uncasted underlying value. + */ + public Object getValue() { + return this.value; + } + + @Override + public String toString() { + return this.getValue().toString(); + } + + /** + * Returns the underlying value as a JSObject, or throwing if it cannot. + * + * @throws JSONException If the underlying value is not a JSObject. + */ + public JSObject toJSObject() throws JSONException { + if (this.value instanceof JSObject) return (JSObject) this.value; + throw new JSONException("JSValue could not be coerced to JSObject."); + } + + /** + * Returns the underlying value as a JSArray, or throwing if it cannot. + * + * @throws JSONException If the underlying value is not a JSArray. + */ + public JSArray toJSArray() throws JSONException { + if (this.value instanceof JSArray) return (JSArray) this.value; + throw new JSONException("JSValue could not be coerced to JSArray."); + } + + /** + * Returns the underlying value this object represents, coercing it into a capacitor-friendly object if supported. + */ + private Object toValue(PluginCall call, String name) { + Object value = null; + value = call.getArray(name, null); + if (value != null) return value; + value = call.getObject(name, null); + if (value != null) return value; + value = call.getString(name, null); + if (value != null) return value; + return call.getData().opt(name); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Logger.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Logger.java new file mode 100644 index 0000000..9d24fed --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Logger.java @@ -0,0 +1,103 @@ +package com.getcapacitor; + +import android.text.TextUtils; +import android.util.Log; + +public class Logger { + + public static final String LOG_TAG_CORE = "Capacitor"; + public static CapConfig config; + + private static Logger instance; + + private static Logger getInstance() { + if (instance == null) { + instance = new Logger(); + } + return instance; + } + + public static void init(CapConfig config) { + Logger.getInstance().loadConfig(config); + } + + private void loadConfig(CapConfig config) { + Logger.config = config; + } + + public static String tags(String... subtags) { + if (subtags != null && subtags.length > 0) { + return LOG_TAG_CORE + "/" + TextUtils.join("/", subtags); + } + + return LOG_TAG_CORE; + } + + public static void verbose(String message) { + verbose(LOG_TAG_CORE, message); + } + + public static void verbose(String tag, String message) { + if (!shouldLog()) { + return; + } + + Log.v(tag, message); + } + + public static void debug(String message) { + debug(LOG_TAG_CORE, message); + } + + public static void debug(String tag, String message) { + if (!shouldLog()) { + return; + } + + Log.d(tag, message); + } + + public static void info(String message) { + info(LOG_TAG_CORE, message); + } + + public static void info(String tag, String message) { + if (!shouldLog()) { + return; + } + + Log.i(tag, message); + } + + public static void warn(String message) { + warn(LOG_TAG_CORE, message); + } + + public static void warn(String tag, String message) { + if (!shouldLog()) { + return; + } + + Log.w(tag, message); + } + + public static void error(String message) { + error(LOG_TAG_CORE, message, null); + } + + public static void error(String message, Throwable e) { + error(LOG_TAG_CORE, message, e); + } + + public static void error(String tag, String message, Throwable e) { + if (!shouldLog()) { + return; + } + + Log.e(tag, message, e); + } + + public static boolean shouldLog() { + return config == null || config.isLoggingEnabled(); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/MessageHandler.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/MessageHandler.java new file mode 100644 index 0000000..b71124e --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/MessageHandler.java @@ -0,0 +1,159 @@ +package com.getcapacitor; + +import android.webkit.JavascriptInterface; +import android.webkit.WebView; +import androidx.webkit.JavaScriptReplyProxy; +import androidx.webkit.WebViewCompat; +import androidx.webkit.WebViewFeature; +import org.apache.cordova.PluginManager; + +/** + * MessageHandler handles messages from the WebView, dispatching them + * to plugins. + */ +public class MessageHandler { + + private Bridge bridge; + private WebView webView; + private PluginManager cordovaPluginManager; + private JavaScriptReplyProxy javaScriptReplyProxy; + + public MessageHandler(Bridge bridge, WebView webView, PluginManager cordovaPluginManager) { + this.bridge = bridge; + this.webView = webView; + this.cordovaPluginManager = cordovaPluginManager; + + if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) && !bridge.getConfig().isUsingLegacyBridge()) { + WebViewCompat.WebMessageListener capListener = (view, message, sourceOrigin, isMainFrame, replyProxy) -> { + if (isMainFrame) { + postMessage(message.getData()); + javaScriptReplyProxy = replyProxy; + } else { + Logger.warn("Plugin execution is allowed in Main Frame only"); + } + }; + try { + WebViewCompat.addWebMessageListener(webView, "androidBridge", bridge.getAllowedOriginRules(), capListener); + } catch (Exception ex) { + webView.addJavascriptInterface(this, "androidBridge"); + } + } else { + webView.addJavascriptInterface(this, "androidBridge"); + } + } + + /** + * The main message handler that will be called from JavaScript + * to send a message to the native bridge. + * @param jsonStr + */ + @JavascriptInterface + @SuppressWarnings("unused") + public void postMessage(String jsonStr) { + try { + JSObject postData = new JSObject(jsonStr); + + String type = postData.getString("type"); + + boolean typeIsNotNull = type != null; + boolean isCordovaPlugin = typeIsNotNull && type.equals("cordova"); + boolean isJavaScriptError = typeIsNotNull && type.equals("js.error"); + + String callbackId = postData.getString("callbackId"); + + if (isCordovaPlugin) { + String service = postData.getString("service"); + String action = postData.getString("action"); + String actionArgs = postData.getString("actionArgs"); + + Logger.verbose( + Logger.tags("Plugin"), + "To native (Cordova plugin): callbackId: " + + callbackId + + ", service: " + + service + + ", action: " + + action + + ", actionArgs: " + + actionArgs + ); + + this.callCordovaPluginMethod(callbackId, service, action, actionArgs); + } else if (isJavaScriptError) { + Logger.error("JavaScript Error: " + jsonStr); + } else { + String pluginId = postData.getString("pluginId"); + String methodName = postData.getString("methodName"); + JSObject methodData = postData.getJSObject("options", new JSObject()); + + Logger.verbose( + Logger.tags("Plugin"), + "To native (Capacitor plugin): callbackId: " + callbackId + ", pluginId: " + pluginId + ", methodName: " + methodName + ); + + this.callPluginMethod(callbackId, pluginId, methodName, methodData); + } + } catch (Exception ex) { + Logger.error("Post message error:", ex); + } + } + + public void sendResponseMessage(PluginCall call, PluginResult successResult, PluginResult errorResult) { + try { + PluginResult data = new PluginResult(); + data.put("save", call.isKeptAlive()); + data.put("callbackId", call.getCallbackId()); + data.put("pluginId", call.getPluginId()); + data.put("methodName", call.getMethodName()); + + boolean pluginResultInError = errorResult != null; + if (pluginResultInError) { + data.put("success", false); + data.put("error", errorResult); + Logger.debug("Sending plugin error: " + data.toString()); + } else { + data.put("success", true); + if (successResult != null) { + data.put("data", successResult); + } + } + + boolean isValidCallbackId = !call.getCallbackId().equals(PluginCall.CALLBACK_ID_DANGLING); + if (isValidCallbackId) { + if (bridge.getConfig().isUsingLegacyBridge()) { + legacySendResponseMessage(data); + } else if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) && javaScriptReplyProxy != null) { + javaScriptReplyProxy.postMessage(data.toString()); + } else { + legacySendResponseMessage(data); + } + } else { + bridge.getApp().fireRestoredResult(data); + } + } catch (Exception ex) { + Logger.error("sendResponseMessage: error: " + ex); + } + if (!call.isKeptAlive()) { + call.release(bridge); + } + } + + private void legacySendResponseMessage(PluginResult data) { + final String runScript = "window.Capacitor.fromNative(" + data.toString() + ")"; + final WebView webView = this.webView; + webView.post(() -> webView.evaluateJavascript(runScript, null)); + } + + private void callPluginMethod(String callbackId, String pluginId, String methodName, JSObject methodData) { + PluginCall call = new PluginCall(this, pluginId, callbackId, methodName, methodData); + bridge.callPluginMethod(pluginId, methodName, call); + } + + private void callCordovaPluginMethod(String callbackId, String service, String action, String actionArgs) { + bridge.execute( + () -> { + cordovaPluginManager.exec(service, action, callbackId, actionArgs); + } + ); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/NativePlugin.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/NativePlugin.java new file mode 100644 index 0000000..c430762 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/NativePlugin.java @@ -0,0 +1,37 @@ +package com.getcapacitor; + +import com.getcapacitor.annotation.CapacitorPlugin; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Base annotation for all Plugins + * @deprecated + *

Use {@link CapacitorPlugin} instead + */ +@Retention(RetentionPolicy.RUNTIME) +@Deprecated +public @interface NativePlugin { + /** + * Request codes this plugin uses and responds to, in order to tie + * Android events back the plugin to handle + */ + int[] requestCodes() default {}; + + /** + * Permissions this plugin needs, in order to make permission requests + * easy if the plugin only needs basic permission prompting + */ + String[] permissions() default {}; + + /** + * The request code to use when automatically requesting permissions + */ + int permissionRequestCode() default 9000; + + /** + * A custom name for the plugin, otherwise uses the + * simple class name. + */ + String name() default ""; +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PermissionState.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PermissionState.java new file mode 100644 index 0000000..382cff7 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PermissionState.java @@ -0,0 +1,31 @@ +package com.getcapacitor; + +import java.util.Locale; + +/** + * Represents the state of a permission + * + * @since 3.0.0 + */ +public enum PermissionState { + GRANTED("granted"), + DENIED("denied"), + PROMPT("prompt"), + PROMPT_WITH_RATIONALE("prompt-with-rationale"); + + private String state; + + PermissionState(String state) { + this.state = state; + } + + @Override + public String toString() { + return state; + } + + public static PermissionState byState(String state) { + state = state.toUpperCase(Locale.ROOT).replace('-', '_'); + return valueOf(state); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Plugin.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Plugin.java new file mode 100644 index 0000000..d8a3e82 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/Plugin.java @@ -0,0 +1,1046 @@ +package com.getcapacitor; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.res.Configuration; +import android.net.Uri; +import android.os.Bundle; +import androidx.activity.result.ActivityResult; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import com.getcapacitor.annotation.ActivityCallback; +import com.getcapacitor.annotation.CapacitorPlugin; +import com.getcapacitor.annotation.Permission; +import com.getcapacitor.annotation.PermissionCallback; +import com.getcapacitor.util.PermissionHelper; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import org.json.JSONException; + +/** + * Plugin is the base class for all plugins, containing a number of + * convenient features for interacting with the {@link Bridge}, managing + * plugin permissions, tracking lifecycle events, and more. + * + * You should inherit from this class when creating new plugins, along with + * adding the {@link CapacitorPlugin} annotation to add additional required + * metadata about the Plugin + */ +public class Plugin { + + // The key we will use inside of a persisted Bundle for the JSON blob + // for a plugin call options. + private static final String BUNDLE_PERSISTED_OPTIONS_JSON_KEY = "_json"; + + // Reference to the Bridge + protected Bridge bridge; + + // Reference to the PluginHandle wrapper for this Plugin + protected PluginHandle handle; + + /** + * A way for plugins to quickly save a call that they will need to reference + * between activity/permissions starts/requests + * + * @deprecated store calls on the bridge using the methods + * {@link com.getcapacitor.Bridge#saveCall(PluginCall)}, + * {@link com.getcapacitor.Bridge#getSavedCall(String)} and + * {@link com.getcapacitor.Bridge#releaseCall(PluginCall)} + */ + @Deprecated + protected PluginCall savedLastCall; + + // Stored event listeners + private final Map> eventListeners; + + /** + * Launchers used by the plugin to handle activity results + */ + private final Map> activityLaunchers = new HashMap<>(); + + /** + * Launchers used by the plugin to handle permission results + */ + private final Map> permissionLaunchers = new HashMap<>(); + + private String lastPluginCallId; + + // Stored results of an event if an event was fired and + // no listeners were attached yet. Only stores the last value. + private final Map> retainedEventArguments; + + public Plugin() { + eventListeners = new HashMap<>(); + retainedEventArguments = new HashMap<>(); + } + + /** + * Called when the plugin has been connected to the bridge + * and is ready to start initializing. + */ + public void load() {} + + /** + * Registers activity result launchers defined on plugins, used for permission requests and + * activities started for result. + */ + void initializeActivityLaunchers() { + List pluginClassMethods = new ArrayList<>(); + for ( + Class pluginCursor = getClass(); + !pluginCursor.getName().equals(Object.class.getName()); + pluginCursor = pluginCursor.getSuperclass() + ) { + pluginClassMethods.addAll(Arrays.asList(pluginCursor.getDeclaredMethods())); + } + + for (final Method method : pluginClassMethods) { + if (method.isAnnotationPresent(ActivityCallback.class)) { + // register callbacks annotated with ActivityCallback for activity results + ActivityResultLauncher launcher = bridge.registerForActivityResult( + new ActivityResultContracts.StartActivityForResult(), + result -> triggerActivityCallback(method, result) + ); + + activityLaunchers.put(method.getName(), launcher); + } else if (method.isAnnotationPresent(PermissionCallback.class)) { + // register callbacks annotated with PermissionCallback for permission results + ActivityResultLauncher launcher = bridge.registerForActivityResult( + new ActivityResultContracts.RequestMultiplePermissions(), + permissions -> triggerPermissionCallback(method, permissions) + ); + + permissionLaunchers.put(method.getName(), launcher); + } + } + } + + private void triggerPermissionCallback(Method method, Map permissionResultMap) { + PluginCall savedCall = bridge.getPermissionCall(handle.getId()); + + // validate permissions and invoke the permission result callback + if (bridge.validatePermissions(this, savedCall, permissionResultMap)) { + try { + method.setAccessible(true); + method.invoke(this, savedCall); + } catch (IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } + + private void triggerActivityCallback(Method method, ActivityResult result) { + PluginCall savedCall = bridge.getSavedCall(lastPluginCallId); + if (savedCall == null) { + savedCall = bridge.getPluginCallForLastActivity(); + } + // invoke the activity result callback + try { + method.setAccessible(true); + method.invoke(this, savedCall, result); + } catch (IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } + } + + /** + * Start activity for result with the provided Intent and resolve with the provided callback method name. + *

+ * If there is no registered activity callback for the method name passed in, the call will + * be rejected. Make sure a valid activity result callback method is registered using the + * {@link ActivityCallback} annotation. + * + * @param call the plugin call + * @param intent the intent used to start an activity + * @param callbackName the name of the callback to run when the launched activity is finished + * @since 3.0.0 + */ + public void startActivityForResult(PluginCall call, Intent intent, String callbackName) { + ActivityResultLauncher activityResultLauncher = getActivityLauncherOrReject(call, callbackName); + if (activityResultLauncher == null) { + // return when null since call was rejected in getLauncherOrReject + return; + } + bridge.setPluginCallForLastActivity(call); + lastPluginCallId = call.getCallbackId(); + bridge.saveCall(call); + activityResultLauncher.launch(intent); + } + + private void permissionActivityResult(PluginCall call, String[] permissionStrings, String callbackName) { + ActivityResultLauncher permissionResultLauncher = getPermissionLauncherOrReject(call, callbackName); + if (permissionResultLauncher == null) { + // return when null since call was rejected in getLauncherOrReject + return; + } + + bridge.savePermissionCall(call); + permissionResultLauncher.launch(permissionStrings); + } + + /** + * Get the main {@link Context} for the current Activity (your app) + * @return the Context for the current activity + */ + public Context getContext() { + return this.bridge.getContext(); + } + + /** + * Get the main {@link Activity} for the app + * @return the Activity for the current app + */ + public AppCompatActivity getActivity() { + return this.bridge.getActivity(); + } + + /** + * Set the Bridge instance for this plugin + * @param bridge + */ + public void setBridge(Bridge bridge) { + this.bridge = bridge; + } + + /** + * Get the Bridge instance for this plugin + */ + public Bridge getBridge() { + return this.bridge; + } + + /** + * Set the wrapper {@link PluginHandle} instance for this plugin that + * contains additional metadata about the Plugin instance (such + * as indexed methods for reflection, and {@link CapacitorPlugin} annotation data). + * @param pluginHandle + */ + public void setPluginHandle(PluginHandle pluginHandle) { + this.handle = pluginHandle; + } + + /** + * Return the wrapper {@link PluginHandle} for this plugin. + * + * This wrapper contains additional metadata about the plugin instance, + * such as indexed methods for reflection, and {@link CapacitorPlugin} annotation data). + * @return + */ + public PluginHandle getPluginHandle() { + return this.handle; + } + + /** + * Get the root App ID + * @return + */ + public String getAppId() { + return getContext().getPackageName(); + } + + /** + * Called to save a {@link PluginCall} in order to reference it + * later, such as in an activity or permissions result handler + * @deprecated use {@link Bridge#saveCall(PluginCall)} + * + * @param lastCall + */ + @Deprecated + public void saveCall(PluginCall lastCall) { + this.savedLastCall = lastCall; + } + + /** + * Set the last saved call to null to free memory + * @deprecated use {@link PluginCall#release(Bridge)} + */ + @Deprecated + public void freeSavedCall() { + this.savedLastCall.release(bridge); + this.savedLastCall = null; + } + + /** + * Get the last saved call, if any + * @deprecated use {@link Bridge#getSavedCall(String)} + * + * @return + */ + @Deprecated + public PluginCall getSavedCall() { + return this.savedLastCall; + } + + /** + * Get the config options for this plugin. + * + * @return a config object representing the plugin config options, or an empty config + * if none exists + */ + public PluginConfig getConfig() { + return bridge.getConfig().getPluginConfiguration(handle.getId()); + } + + /** + * Get the value for a key on the config for this plugin. + * @deprecated use {@link #getConfig()} and access config values using the methods available + * depending on the type. + * + * @param key the key for the config value + * @return some object containing the value from the config + */ + @Deprecated + public Object getConfigValue(String key) { + try { + PluginConfig pluginConfig = getConfig(); + return pluginConfig.getConfigJSON().get(key); + } catch (JSONException ex) { + return null; + } + } + + /** + * Check whether any of the given permissions has been defined in the AndroidManifest.xml + * @deprecated use {@link #isPermissionDeclared(String)} + * + * @param permissions + * @return + */ + @Deprecated + public boolean hasDefinedPermissions(String[] permissions) { + for (String permission : permissions) { + if (!PermissionHelper.hasDefinedPermission(getContext(), permission)) { + return false; + } + } + return true; + } + + /** + * Check if all annotated permissions have been defined in the AndroidManifest.xml + * @deprecated use {@link #isPermissionDeclared(String)} + * + * @return true if permissions are all defined in the Manifest + */ + @Deprecated + public boolean hasDefinedRequiredPermissions() { + CapacitorPlugin annotation = handle.getPluginAnnotation(); + if (annotation == null) { + // Check for legacy plugin annotation, @NativePlugin + NativePlugin legacyAnnotation = handle.getLegacyPluginAnnotation(); + return hasDefinedPermissions(legacyAnnotation.permissions()); + } else { + for (Permission perm : annotation.permissions()) { + for (String permString : perm.strings()) { + if (!PermissionHelper.hasDefinedPermission(getContext(), permString)) { + return false; + } + } + } + } + + return true; + } + + /** + * Checks if the given permission alias is correctly declared in AndroidManifest.xml + * @param alias a permission alias defined on the plugin + * @return true only if all permissions associated with the given alias are declared in the manifest + */ + public boolean isPermissionDeclared(String alias) { + CapacitorPlugin annotation = handle.getPluginAnnotation(); + if (annotation != null) { + for (Permission perm : annotation.permissions()) { + if (alias.equalsIgnoreCase(perm.alias())) { + boolean result = true; + for (String permString : perm.strings()) { + result = result && PermissionHelper.hasDefinedPermission(getContext(), permString); + } + + return result; + } + } + } + + Logger.error(String.format("isPermissionDeclared: No alias defined for %s " + "or missing @CapacitorPlugin annotation.", alias)); + return false; + } + + /** + * Check whether the given permission has been granted by the user + * @deprecated use {@link #getPermissionState(String)} and {@link #getPermissionStates()} to get + * the states of permissions defined on the Plugin in conjunction with the @CapacitorPlugin + * annotation. Use the Android API {@link ActivityCompat#checkSelfPermission(Context, String)} + * methods to check permissions with Android permission strings + * + * @param permission + * @return + */ + @Deprecated + public boolean hasPermission(String permission) { + return ActivityCompat.checkSelfPermission(this.getContext(), permission) == PackageManager.PERMISSION_GRANTED; + } + + /** + * If the plugin annotation specified a set of permissions, this method checks if each is + * granted + * @deprecated use {@link #getPermissionState(String)} or {@link #getPermissionStates()} to + * check whether permissions are granted or not + * + * @return + */ + @Deprecated + public boolean hasRequiredPermissions() { + CapacitorPlugin annotation = handle.getPluginAnnotation(); + if (annotation == null) { + // Check for legacy plugin annotation, @NativePlugin + NativePlugin legacyAnnotation = handle.getLegacyPluginAnnotation(); + for (String perm : legacyAnnotation.permissions()) { + if (ActivityCompat.checkSelfPermission(this.getContext(), perm) != PackageManager.PERMISSION_GRANTED) { + return false; + } + } + + return true; + } + + for (Permission perm : annotation.permissions()) { + for (String permString : perm.strings()) { + if (ActivityCompat.checkSelfPermission(this.getContext(), permString) != PackageManager.PERMISSION_GRANTED) { + return false; + } + } + } + + return true; + } + + /** + * Request all of the specified permissions in the CapacitorPlugin annotation (if any) + * + * If there is no registered permission callback for the PluginCall passed in, the call will + * be rejected. Make sure a valid permission callback method is registered using the + * {@link PermissionCallback} annotation. + * + * @since 3.0.0 + * @param call the plugin call + * @param callbackName the name of the callback to run when the permission request is complete + */ + protected void requestAllPermissions(@NonNull PluginCall call, @NonNull String callbackName) { + CapacitorPlugin annotation = handle.getPluginAnnotation(); + if (annotation != null) { + HashSet perms = new HashSet<>(); + for (Permission perm : annotation.permissions()) { + perms.addAll(Arrays.asList(perm.strings())); + } + + permissionActivityResult(call, perms.toArray(new String[0]), callbackName); + } + } + + /** + * Request permissions using an alias defined on the plugin. + * + * If there is no registered permission callback for the PluginCall passed in, the call will + * be rejected. Make sure a valid permission callback method is registered using the + * {@link PermissionCallback} annotation. + * + * @param alias an alias defined on the plugin + * @param call the plugin call involved in originating the request + * @param callbackName the name of the callback to run when the permission request is complete + */ + protected void requestPermissionForAlias(@NonNull String alias, @NonNull PluginCall call, @NonNull String callbackName) { + requestPermissionForAliases(new String[] { alias }, call, callbackName); + } + + /** + * Request permissions using aliases defined on the plugin. + * + * If there is no registered permission callback for the PluginCall passed in, the call will + * be rejected. Make sure a valid permission callback method is registered using the + * {@link PermissionCallback} annotation. + * + * @param aliases a set of aliases defined on the plugin + * @param call the plugin call involved in originating the request + * @param callbackName the name of the callback to run when the permission request is complete + */ + protected void requestPermissionForAliases(@NonNull String[] aliases, @NonNull PluginCall call, @NonNull String callbackName) { + if (aliases.length == 0) { + Logger.error("No permission alias was provided"); + return; + } + + String[] permissions = getPermissionStringsForAliases(aliases); + + if (permissions.length > 0) { + permissionActivityResult(call, permissions, callbackName); + } + } + + /** + * Gets the Android permission strings defined on the {@link CapacitorPlugin} annotation with + * the provided aliases. + * + * @param aliases aliases for permissions defined on the plugin + * @return Android permission strings associated with the provided aliases, if exists + */ + private String[] getPermissionStringsForAliases(@NonNull String[] aliases) { + CapacitorPlugin annotation = handle.getPluginAnnotation(); + HashSet perms = new HashSet<>(); + for (Permission perm : annotation.permissions()) { + if (Arrays.asList(aliases).contains(perm.alias())) { + perms.addAll(Arrays.asList(perm.strings())); + } + } + + return perms.toArray(new String[0]); + } + + /** + * Gets the activity launcher associated with the calling methodName, or rejects the call if + * no registered launcher exists + * + * @param call the plugin call + * @param methodName the name of the activity callback method + * @return a launcher, or null if none found + */ + private @Nullable ActivityResultLauncher getActivityLauncherOrReject(PluginCall call, String methodName) { + ActivityResultLauncher activityLauncher = activityLaunchers.get(methodName); + + // if there is no registered launcher, reject the call with an error and return null + if (activityLauncher == null) { + String registerError = + "There is no ActivityCallback method registered for the name: %s. " + + "Please define a callback method annotated with @ActivityCallback " + + "that receives arguments: (PluginCall, ActivityResult)"; + registerError = String.format(Locale.US, registerError, methodName); + Logger.error(registerError); + call.reject(registerError); + return null; + } + + return activityLauncher; + } + + /** + * Gets the permission launcher associated with the calling methodName, or rejects the call if + * no registered launcher exists + * + * @param call the plugin call + * @param methodName the name of the permission callback method + * @return a launcher, or null if none found + */ + private @Nullable ActivityResultLauncher getPermissionLauncherOrReject(PluginCall call, String methodName) { + ActivityResultLauncher permissionLauncher = permissionLaunchers.get(methodName); + + // if there is no registered launcher, reject the call with an error and return null + if (permissionLauncher == null) { + String registerError = + "There is no PermissionCallback method registered for the name: %s. " + + "Please define a callback method annotated with @PermissionCallback " + + "that receives arguments: (PluginCall)"; + registerError = String.format(Locale.US, registerError, methodName); + Logger.error(registerError); + call.reject(registerError); + return null; + } + + return permissionLauncher; + } + + /** + * Request all of the specified permissions in the CapacitorPlugin annotation (if any) + * + * @deprecated use {@link #requestAllPermissions(PluginCall, String)} in conjunction with @CapacitorPlugin + */ + @Deprecated + public void pluginRequestAllPermissions() { + NativePlugin legacyAnnotation = handle.getLegacyPluginAnnotation(); + ActivityCompat.requestPermissions(getActivity(), legacyAnnotation.permissions(), legacyAnnotation.permissionRequestCode()); + } + + /** + * Helper for requesting a specific permission + * + * @param permission the permission to request + * @param requestCode the requestCode to use to associate the result with the plugin + * @deprecated use {@link #requestPermissionForAlias(String, PluginCall, String)} in conjunction with @CapacitorPlugin + */ + @Deprecated + public void pluginRequestPermission(String permission, int requestCode) { + ActivityCompat.requestPermissions(getActivity(), new String[] { permission }, requestCode); + } + + /** + * Helper for requesting specific permissions + * @deprecated use {@link #requestPermissionForAliases(String[], PluginCall, String)} in conjunction + * with @CapacitorPlugin + * + * @param permissions the set of permissions to request + * @param requestCode the requestCode to use to associate the result with the plugin + */ + @Deprecated + public void pluginRequestPermissions(String[] permissions, int requestCode) { + ActivityCompat.requestPermissions(getActivity(), permissions, requestCode); + } + + /** + * Get the permission state for the provided permission alias. + * + * @param alias the permission alias to get + * @return the state of the provided permission alias or null + */ + public PermissionState getPermissionState(String alias) { + return getPermissionStates().get(alias); + } + + /** + * Helper to check all permissions defined on a plugin and see the state of each. + * + * @since 3.0.0 + * @return A mapping of permission aliases to the associated granted status. + */ + public Map getPermissionStates() { + return bridge.getPermissionStates(this); + } + + /** + * Add a listener for the given event + * @param eventName + * @param call + */ + private void addEventListener(String eventName, PluginCall call) { + List listeners = eventListeners.get(eventName); + if (listeners == null || listeners.isEmpty()) { + listeners = new ArrayList<>(); + eventListeners.put(eventName, listeners); + + // Must add the call before sending retained arguments + listeners.add(call); + + sendRetainedArgumentsForEvent(eventName); + } else { + listeners.add(call); + } + } + + /** + * Remove a listener from the given event + * @param eventName + * @param call + */ + private void removeEventListener(String eventName, PluginCall call) { + List listeners = eventListeners.get(eventName); + if (listeners == null) { + return; + } + + listeners.remove(call); + } + + /** + * Notify all listeners that an event occurred + * @param eventName + * @param data + */ + protected void notifyListeners(String eventName, JSObject data, boolean retainUntilConsumed) { + Logger.verbose(getLogTag(), "Notifying listeners for event " + eventName); + List listeners = eventListeners.get(eventName); + if (listeners == null || listeners.isEmpty()) { + Logger.debug(getLogTag(), "No listeners found for event " + eventName); + if (retainUntilConsumed) { + List argList = retainedEventArguments.get(eventName); + + if (argList == null) { + argList = new ArrayList(); + } + + argList.add(data); + retainedEventArguments.put(eventName, argList); + } + return; + } + + CopyOnWriteArrayList listenersCopy = new CopyOnWriteArrayList(listeners); + for (PluginCall call : listenersCopy) { + call.resolve(data); + } + } + + /** + * Notify all listeners that an event occurred + * This calls {@link Plugin#notifyListeners(String, JSObject, boolean)} + * with retainUntilConsumed set to false + * @param eventName + * @param data + */ + protected void notifyListeners(String eventName, JSObject data) { + notifyListeners(eventName, data, false); + } + + /** + * Check if there are any listeners for the given event + */ + protected boolean hasListeners(String eventName) { + List listeners = eventListeners.get(eventName); + if (listeners == null) { + return false; + } + return !listeners.isEmpty(); + } + + /** + * Send retained arguments (if any) for this event. This + * is called only when the first listener for an event is added + * @param eventName + */ + private void sendRetainedArgumentsForEvent(String eventName) { + // copy retained args and null source to prevent potential race conditions + List retainedArgs = retainedEventArguments.get(eventName); + if (retainedArgs == null) { + return; + } + + retainedEventArguments.remove(eventName); + + for (JSObject retained : retainedArgs) { + notifyListeners(eventName, retained); + } + } + + /** + * Exported plugin call for adding a listener to this plugin + * @param call + */ + @SuppressWarnings("unused") + @PluginMethod(returnType = PluginMethod.RETURN_NONE) + public void addListener(PluginCall call) { + String eventName = call.getString("eventName"); + call.setKeepAlive(true); + addEventListener(eventName, call); + } + + /** + * Exported plugin call to remove a listener from this plugin + * @param call + */ + @SuppressWarnings("unused") + @PluginMethod(returnType = PluginMethod.RETURN_NONE) + public void removeListener(PluginCall call) { + String eventName = call.getString("eventName"); + String callbackId = call.getString("callbackId"); + PluginCall savedCall = bridge.getSavedCall(callbackId); + if (savedCall != null) { + removeEventListener(eventName, savedCall); + bridge.releaseCall(savedCall); + } + } + + /** + * Exported plugin call to remove all listeners from this plugin + * @param call + */ + @SuppressWarnings("unused") + @PluginMethod(returnType = PluginMethod.RETURN_PROMISE) + public void removeAllListeners(PluginCall call) { + eventListeners.clear(); + call.resolve(); + } + + /** + * Exported plugin call for checking the granted status for each permission + * declared on the plugin. This plugin call responds with a mapping of permissions to + * the associated granted status. + * + * @since 3.0.0 + */ + @PluginMethod + @PermissionCallback + public void checkPermissions(PluginCall pluginCall) { + Map permissionsResult = getPermissionStates(); + + if (permissionsResult.size() == 0) { + // if no permissions are defined on the plugin, resolve undefined + pluginCall.resolve(); + } else { + JSObject permissionsResultJSON = new JSObject(); + for (Map.Entry entry : permissionsResult.entrySet()) { + permissionsResultJSON.put(entry.getKey(), entry.getValue()); + } + + pluginCall.resolve(permissionsResultJSON); + } + } + + /** + * Exported plugin call to request all permissions for this plugin. + * To manually request permissions within a plugin use: + * {@link #requestAllPermissions(PluginCall, String)}, or + * {@link #requestPermissionForAlias(String, PluginCall, String)}, or + * {@link #requestPermissionForAliases(String[], PluginCall, String)} + * + * @param call the plugin call + */ + @PluginMethod + public void requestPermissions(PluginCall call) { + CapacitorPlugin annotation = handle.getPluginAnnotation(); + if (annotation == null) { + handleLegacyPermission(call); + } else { + // handle permission requests for plugins defined with @CapacitorPlugin (since 3.0.0) + String[] permAliases = null; + Set autoGrantPerms = new HashSet<>(); + + // If call was made with a list of specific permission aliases to request, save them + // to be requested + JSArray providedPerms = call.getArray("permissions"); + List providedPermsList = null; + + if (providedPerms != null) { + try { + providedPermsList = providedPerms.toList(); + } catch (JSONException ignore) { + // do nothing + } + } + + // If call was made without any custom permissions, request all from plugin annotation + Set aliasSet = new HashSet<>(); + if (providedPermsList == null || providedPermsList.isEmpty()) { + for (Permission perm : annotation.permissions()) { + // If a permission is defined with no permission strings, separate it for auto-granting. + // Otherwise, the alias is added to the list to be requested. + if (perm.strings().length == 0 || (perm.strings().length == 1 && perm.strings()[0].isEmpty())) { + if (!perm.alias().isEmpty()) { + autoGrantPerms.add(perm.alias()); + } + } else { + aliasSet.add(perm.alias()); + } + } + + permAliases = aliasSet.toArray(new String[0]); + } else { + for (Permission perm : annotation.permissions()) { + if (providedPermsList.contains(perm.alias())) { + aliasSet.add(perm.alias()); + } + } + + if (aliasSet.isEmpty()) { + call.reject("No valid permission alias was requested of this plugin."); + } else { + permAliases = aliasSet.toArray(new String[0]); + } + } + + if (permAliases != null && permAliases.length > 0) { + // request permissions using provided aliases or all defined on the plugin + requestPermissionForAliases(permAliases, call, "checkPermissions"); + } else if (!autoGrantPerms.isEmpty()) { + // if the plugin only has auto-grant permissions, return all as GRANTED + JSObject permissionsResults = new JSObject(); + + for (String perm : autoGrantPerms) { + permissionsResults.put(perm, PermissionState.GRANTED.toString()); + } + + call.resolve(permissionsResults); + } else { + // no permissions are defined on the plugin, resolve undefined + call.resolve(); + } + } + } + + @SuppressWarnings("deprecation") + private void handleLegacyPermission(PluginCall call) { + // handle permission requests for plugins defined with @NativePlugin (prior to 3.0.0) + NativePlugin legacyAnnotation = this.handle.getLegacyPluginAnnotation(); + String[] perms = legacyAnnotation.permissions(); + if (perms.length > 0) { + saveCall(call); + pluginRequestPermissions(perms, legacyAnnotation.permissionRequestCode()); + } else { + call.resolve(); + } + } + + /** + * Handle request permissions result. A plugin using the deprecated {@link NativePlugin} + * should override this to handle the result, or this method will handle the result + * for our convenient requestPermissions call. + * @deprecated in favor of using callbacks in conjunction with {@link CapacitorPlugin} + * + * @param requestCode + * @param permissions + * @param grantResults + */ + @Deprecated + protected void handleRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + if (!hasDefinedPermissions(permissions)) { + StringBuilder builder = new StringBuilder(); + builder.append("Missing the following permissions in AndroidManifest.xml:\n"); + String[] missing = PermissionHelper.getUndefinedPermissions(getContext(), permissions); + for (String perm : missing) { + builder.append(perm + "\n"); + } + savedLastCall.reject(builder.toString()); + savedLastCall = null; + } + } + + /** + * Called before the app is destroyed to give a plugin the chance to + * save the last call options for a saved plugin. By default, this + * method saves the full JSON blob of the options call. Since Bundle sizes + * may be limited, plugins that expect to be called with large data + * objects (such as a file), should override this method and selectively + * store option values in a {@link Bundle} to avoid exceeding limits. + * @return a new {@link Bundle} with fields set from the options of the last saved {@link PluginCall} + */ + protected Bundle saveInstanceState() { + PluginCall savedCall = bridge.getSavedCall(lastPluginCallId); + + if (savedCall == null) { + return null; + } + + Bundle ret = new Bundle(); + JSObject callData = savedCall.getData(); + + if (callData != null) { + ret.putString(BUNDLE_PERSISTED_OPTIONS_JSON_KEY, callData.toString()); + } + + return ret; + } + + /** + * Called when the app is opened with a previously un-handled + * activity response. If the plugin that started the activity + * stored data in {@link Plugin#saveInstanceState()} then this + * method will be called to allow the plugin to restore from that. + * @param state + */ + protected void restoreState(Bundle state) {} + + /** + * Handle activity result, should be overridden by each plugin + * + * @deprecated provide a callback method using the {@link ActivityCallback} annotation and use + * the {@link #startActivityForResult(PluginCall, Intent, String)} method + * + * @param requestCode + * @param resultCode + * @param data + */ + @Deprecated + protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {} + + /** + * Handle onNewIntent + * @param intent + */ + protected void handleOnNewIntent(Intent intent) {} + + /** + * Handle onConfigurationChanged + * @param newConfig + */ + protected void handleOnConfigurationChanged(Configuration newConfig) {} + + /** + * Handle onStart + */ + protected void handleOnStart() {} + + /** + * Handle onRestart + */ + protected void handleOnRestart() {} + + /** + * Handle onResume + */ + protected void handleOnResume() {} + + /** + * Handle onPause + */ + protected void handleOnPause() {} + + /** + * Handle onStop + */ + protected void handleOnStop() {} + + /** + * Handle onDestroy + */ + protected void handleOnDestroy() {} + + /** + * Give the plugins a chance to take control when a URL is about to be loaded in the WebView. + * Returning true causes the WebView to abort loading the URL. + * Returning false causes the WebView to continue loading the URL. + * Returning null will defer to the default Capacitor policy + */ + @SuppressWarnings("unused") + public Boolean shouldOverrideLoad(Uri url) { + return null; + } + + /** + * Start a new Activity. + * + * Note: This method must be used by all plugins instead of calling + * {@link Activity#startActivityForResult} as it associates the plugin with + * any resulting data from the new Activity even if this app + * is destroyed by the OS (to free up memory, for example). + * @param intent + * @param resultCode + */ + @Deprecated + protected void startActivityForResult(PluginCall call, Intent intent, int resultCode) { + bridge.startActivityForPluginWithResult(call, intent, resultCode); + } + + /** + * Execute the given runnable on the Bridge's task handler + * @param runnable + */ + public void execute(Runnable runnable) { + bridge.execute(runnable); + } + + /** + * Shortcut for getting the plugin log tag + * @param subTags + */ + protected String getLogTag(String... subTags) { + return Logger.tags(subTags); + } + + /** + * Gets a plugin log tag with the child's class name as subTag. + */ + protected String getLogTag() { + return Logger.tags(this.getClass().getSimpleName()); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginCall.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginCall.java new file mode 100644 index 0000000..18661d7 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginCall.java @@ -0,0 +1,440 @@ +package com.getcapacitor; + +import androidx.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Wraps a call from the web layer to native + */ +public class PluginCall { + + /** + * A special callback id that indicates there is no matching callback + * on the client to associate any PluginCall results back to. This is used + * in the case of an app resuming with saved instance data, for example. + */ + public static final String CALLBACK_ID_DANGLING = "-1"; + + private final MessageHandler msgHandler; + private final String pluginId; + private final String callbackId; + private final String methodName; + private final JSObject data; + + private boolean keepAlive = false; + + /** + * Indicates that this PluginCall was released, and should no longer be used + */ + @Deprecated + private boolean isReleased = false; + + public PluginCall(MessageHandler msgHandler, String pluginId, String callbackId, String methodName, JSObject data) { + this.msgHandler = msgHandler; + this.pluginId = pluginId; + this.callbackId = callbackId; + this.methodName = methodName; + this.data = data; + } + + public void successCallback(PluginResult successResult) { + if (CALLBACK_ID_DANGLING.equals(this.callbackId)) { + // don't send back response if the callbackId was "-1" + return; + } + + this.msgHandler.sendResponseMessage(this, successResult, null); + } + + /** + * @deprecated + * Use {@link #resolve(JSObject data)} + */ + @Deprecated + public void success(JSObject data) { + PluginResult result = new PluginResult(data); + this.msgHandler.sendResponseMessage(this, result, null); + } + + /** + * @deprecated + * Use {@link #resolve()} + */ + @Deprecated + public void success() { + this.resolve(new JSObject()); + } + + public void resolve(JSObject data) { + PluginResult result = new PluginResult(data); + this.msgHandler.sendResponseMessage(this, result, null); + } + + public void resolve() { + this.msgHandler.sendResponseMessage(this, null, null); + } + + public void errorCallback(String msg) { + PluginResult errorResult = new PluginResult(); + + try { + errorResult.put("message", msg); + } catch (Exception jsonEx) { + Logger.error(Logger.tags("Plugin"), jsonEx.toString(), null); + } + + this.msgHandler.sendResponseMessage(this, null, errorResult); + } + + /** + * @deprecated + * Use {@link #reject(String msg, Exception ex)} + */ + @Deprecated + public void error(String msg, Exception ex) { + reject(msg, ex); + } + + /** + * @deprecated + * Use {@link #reject(String msg, String code, Exception ex)} + */ + @Deprecated + public void error(String msg, String code, Exception ex) { + reject(msg, code, ex); + } + + /** + * @deprecated + * Use {@link #reject(String msg)} + */ + @Deprecated + public void error(String msg) { + reject(msg); + } + + public void reject(String msg, String code, Exception ex, JSObject data) { + PluginResult errorResult = new PluginResult(); + + if (ex != null) { + Logger.error(Logger.tags("Plugin"), msg, ex); + } + + try { + errorResult.put("message", msg); + errorResult.put("code", code); + if (null != data) { + errorResult.put("data", data); + } + } catch (Exception jsonEx) { + Logger.error(Logger.tags("Plugin"), jsonEx.getMessage(), jsonEx); + } + + this.msgHandler.sendResponseMessage(this, null, errorResult); + } + + public void reject(String msg, Exception ex, JSObject data) { + reject(msg, null, ex, data); + } + + public void reject(String msg, String code, JSObject data) { + reject(msg, code, null, data); + } + + public void reject(String msg, String code, Exception ex) { + reject(msg, code, ex, null); + } + + public void reject(String msg, JSObject data) { + reject(msg, null, null, data); + } + + public void reject(String msg, Exception ex) { + reject(msg, null, ex, null); + } + + public void reject(String msg, String code) { + reject(msg, code, null, null); + } + + public void reject(String msg) { + reject(msg, null, null, null); + } + + public void unimplemented() { + unimplemented("not implemented"); + } + + public void unimplemented(String msg) { + reject(msg, "UNIMPLEMENTED", null, null); + } + + public void unavailable() { + unavailable("not available"); + } + + public void unavailable(String msg) { + reject(msg, "UNAVAILABLE", null, null); + } + + public String getPluginId() { + return this.pluginId; + } + + public String getCallbackId() { + return this.callbackId; + } + + public String getMethodName() { + return this.methodName; + } + + public JSObject getData() { + return this.data; + } + + @Nullable + public String getString(String name) { + return this.getString(name, null); + } + + @Nullable + public String getString(String name, @Nullable String defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof String) { + return (String) value; + } + return defaultValue; + } + + @Nullable + public Integer getInt(String name) { + return this.getInt(name, null); + } + + @Nullable + public Integer getInt(String name, @Nullable Integer defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof Integer) { + return (Integer) value; + } + return defaultValue; + } + + @Nullable + public Long getLong(String name) { + return this.getLong(name, null); + } + + @Nullable + public Long getLong(String name, @Nullable Long defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof Long) { + return (Long) value; + } + return defaultValue; + } + + @Nullable + public Float getFloat(String name) { + return this.getFloat(name, null); + } + + @Nullable + public Float getFloat(String name, @Nullable Float defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof Float) { + return (Float) value; + } + if (value instanceof Double) { + return ((Double) value).floatValue(); + } + if (value instanceof Integer) { + return ((Integer) value).floatValue(); + } + return defaultValue; + } + + @Nullable + public Double getDouble(String name) { + return this.getDouble(name, null); + } + + @Nullable + public Double getDouble(String name, @Nullable Double defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof Double) { + return (Double) value; + } + if (value instanceof Float) { + return ((Float) value).doubleValue(); + } + if (value instanceof Integer) { + return ((Integer) value).doubleValue(); + } + return defaultValue; + } + + @Nullable + public Boolean getBoolean(String name) { + return this.getBoolean(name, null); + } + + @Nullable + public Boolean getBoolean(String name, @Nullable Boolean defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof Boolean) { + return (Boolean) value; + } + return defaultValue; + } + + public JSObject getObject(String name) { + return this.getObject(name, null); + } + + @Nullable + public JSObject getObject(String name, JSObject defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof JSONObject) { + try { + return JSObject.fromJSONObject((JSONObject) value); + } catch (JSONException ex) { + return defaultValue; + } + } + return defaultValue; + } + + public JSArray getArray(String name) { + return this.getArray(name, null); + } + + /** + * Get a JSONArray and turn it into a JSArray + * @param name + * @param defaultValue + * @return + */ + @Nullable + public JSArray getArray(String name, JSArray defaultValue) { + Object value = this.data.opt(name); + if (value == null) { + return defaultValue; + } + + if (value instanceof JSONArray) { + try { + JSONArray valueArray = (JSONArray) value; + List items = new ArrayList<>(); + for (int i = 0; i < valueArray.length(); i++) { + items.add(valueArray.get(i)); + } + return new JSArray(items.toArray()); + } catch (JSONException ex) { + return defaultValue; + } + } + return defaultValue; + } + + /** + * @param name of the option to check + * @return boolean indicating if the plugin call has an option for the provided name. + * @deprecated Presence of a key should not be considered significant. + * Use typed accessors to check the value instead. + */ + @Deprecated + public boolean hasOption(String name) { + return this.data.has(name); + } + + /** + * Indicate that the Bridge should cache this call in order to call + * it again later. For example, the addListener system uses this to + * continuously call the call's callback (😆). + * @deprecated use {@link #setKeepAlive(Boolean)} instead + */ + @Deprecated + public void save() { + setKeepAlive(true); + } + + /** + * Indicate that the Bridge should cache this call in order to call + * it again later. For example, the addListener system uses this to + * continuously call the call's callback. + * + * @param keepAlive whether to keep the callback saved + */ + public void setKeepAlive(Boolean keepAlive) { + this.keepAlive = keepAlive; + } + + public void release(Bridge bridge) { + this.keepAlive = false; + bridge.releaseCall(this); + this.isReleased = true; + } + + /** + * @deprecated use {@link #isKeptAlive()} + * @return true if the plugin call is kept alive + */ + @Deprecated + public boolean isSaved() { + return isKeptAlive(); + } + + /** + * Gets the keepAlive value of the plugin call + * @return true if the plugin call is kept alive + */ + public boolean isKeptAlive() { + return keepAlive; + } + + @Deprecated + public boolean isReleased() { + return isReleased; + } + + class PluginCallDataTypeException extends Exception { + + PluginCallDataTypeException(String m) { + super(m); + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginConfig.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginConfig.java new file mode 100644 index 0000000..0f00fc5 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginConfig.java @@ -0,0 +1,116 @@ +package com.getcapacitor; + +import com.getcapacitor.util.JSONUtils; +import org.json.JSONObject; + +/** + * Represents the configuration options for plugins used by Capacitor + */ +public class PluginConfig { + + /** + * The object containing plugin config values. + */ + private final JSONObject config; + + /** + * Constructs a PluginsConfig with the provided JSONObject value. + * + * @param config A plugin configuration expressed as a JSON Object + */ + PluginConfig(JSONObject config) { + this.config = config; + } + + /** + * Get a string value for a plugin in the Capacitor config. + * + * @param configKey The key of the value to retrieve + * @return The value from the config, if exists. Null if not + */ + public String getString(String configKey) { + return getString(configKey, null); + } + + /** + * Get a string value for a plugin in the Capacitor config. + * + * @param configKey The key of the value to retrieve + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + public String getString(String configKey, String defaultValue) { + return JSONUtils.getString(config, configKey, defaultValue); + } + + /** + * Get a boolean value for a plugin in the Capacitor config. + * + * @param configKey The key of the value to retrieve + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + public boolean getBoolean(String configKey, boolean defaultValue) { + return JSONUtils.getBoolean(config, configKey, defaultValue); + } + + /** + * Get an integer value for a plugin in the Capacitor config. + * + * @param configKey The key of the value to retrieve + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + public int getInt(String configKey, int defaultValue) { + return JSONUtils.getInt(config, configKey, defaultValue); + } + + /** + * Get a string array value for a plugin in the Capacitor config. + * + * @param configKey The key of the value to retrieve + * @return The value from the config, if exists. Null if not + */ + public String[] getArray(String configKey) { + return getArray(configKey, null); + } + + /** + * Get a string array value for a plugin in the Capacitor config. + * + * @param configKey The key of the value to retrieve + * @param defaultValue A default value to return if the key does not exist in the config + * @return The value from the config, if key exists. Default value returned if not + */ + public String[] getArray(String configKey, String[] defaultValue) { + return JSONUtils.getArray(config, configKey, defaultValue); + } + + /** + * Get a JSON object value for a plugin in the Capacitor config. + * + * @param configKey The key of the value to retrieve + * @return The value from the config, if exists. Null if not + */ + public JSONObject getObject(String configKey) { + return JSONUtils.getObject(config, configKey); + } + + /** + * Check if the PluginConfig is empty. + * + * @return true if the plugin config has no entries + */ + public boolean isEmpty() { + return config.length() == 0; + } + + /** + * Gets the JSON Object containing the config of the the provided plugin ID. + * + * @return The config for that plugin + */ + public JSONObject getConfigJSON() { + return config; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginHandle.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginHandle.java new file mode 100644 index 0000000..2e520b3 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginHandle.java @@ -0,0 +1,160 @@ +package com.getcapacitor; + +import com.getcapacitor.annotation.CapacitorPlugin; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +/** + * PluginHandle is an instance of a plugin that has been registered + * and indexed. Think of it as a Plugin instance with extra metadata goodies + */ +public class PluginHandle { + + private final Bridge bridge; + private final Class pluginClass; + + private final Map pluginMethods = new HashMap<>(); + + private final String pluginId; + + @SuppressWarnings("deprecation") + private NativePlugin legacyPluginAnnotation; + + private CapacitorPlugin pluginAnnotation; + + private Plugin instance; + + @SuppressWarnings("deprecation") + private PluginHandle(Class clazz, Bridge bridge) throws InvalidPluginException { + this.bridge = bridge; + this.pluginClass = clazz; + + CapacitorPlugin pluginAnnotation = pluginClass.getAnnotation(CapacitorPlugin.class); + if (pluginAnnotation == null) { + // Check for legacy plugin annotation, @NativePlugin + NativePlugin legacyPluginAnnotation = pluginClass.getAnnotation(NativePlugin.class); + if (legacyPluginAnnotation == null) { + throw new InvalidPluginException("No @CapacitorPlugin annotation found for plugin " + pluginClass.getName()); + } + + if (!legacyPluginAnnotation.name().equals("")) { + this.pluginId = legacyPluginAnnotation.name(); + } else { + this.pluginId = pluginClass.getSimpleName(); + } + + this.legacyPluginAnnotation = legacyPluginAnnotation; + } else { + if (!pluginAnnotation.name().equals("")) { + this.pluginId = pluginAnnotation.name(); + } else { + this.pluginId = pluginClass.getSimpleName(); + } + + this.pluginAnnotation = pluginAnnotation; + } + + this.indexMethods(clazz); + } + + public PluginHandle(Bridge bridge, Class pluginClass) throws InvalidPluginException, PluginLoadException { + this(pluginClass, bridge); + this.load(); + } + + public PluginHandle(Bridge bridge, Plugin plugin) throws InvalidPluginException { + this(plugin.getClass(), bridge); + this.loadInstance(plugin); + } + + public Class getPluginClass() { + return pluginClass; + } + + public String getId() { + return this.pluginId; + } + + @SuppressWarnings("deprecation") + public NativePlugin getLegacyPluginAnnotation() { + return this.legacyPluginAnnotation; + } + + public CapacitorPlugin getPluginAnnotation() { + return this.pluginAnnotation; + } + + public Plugin getInstance() { + return this.instance; + } + + public Collection getMethods() { + return this.pluginMethods.values(); + } + + public Plugin load() throws PluginLoadException { + if (this.instance != null) { + return this.instance; + } + + try { + this.instance = this.pluginClass.newInstance(); + return this.loadInstance(instance); + } catch (InstantiationException | IllegalAccessException ex) { + throw new PluginLoadException("Unable to load plugin instance. Ensure plugin is publicly accessible"); + } + } + + public Plugin loadInstance(Plugin plugin) { + this.instance = plugin; + this.instance.setPluginHandle(this); + this.instance.setBridge(this.bridge); + this.instance.load(); + this.instance.initializeActivityLaunchers(); + return this.instance; + } + + /** + * Call a method on a plugin. + * @param methodName the name of the method to call + * @param call the constructed PluginCall with parameters from the caller + * @throws InvalidPluginMethodException if no method was found on that plugin + */ + public void invoke(String methodName, PluginCall call) + throws PluginLoadException, InvalidPluginMethodException, InvocationTargetException, IllegalAccessException { + if (this.instance == null) { + // Can throw PluginLoadException + this.load(); + } + + PluginMethodHandle methodMeta = pluginMethods.get(methodName); + if (methodMeta == null) { + throw new InvalidPluginMethodException("No method " + methodName + " found for plugin " + pluginClass.getName()); + } + + methodMeta.getMethod().invoke(this.instance, call); + } + + /** + * Index all the known callable methods for a plugin for faster + * invocation later + */ + private void indexMethods(Class plugin) { + //Method[] methods = pluginClass.getDeclaredMethods(); + Method[] methods = pluginClass.getMethods(); + + for (Method methodReflect : methods) { + PluginMethod method = methodReflect.getAnnotation(PluginMethod.class); + + if (method == null) { + continue; + } + + PluginMethodHandle methodMeta = new PluginMethodHandle(methodReflect, method); + pluginMethods.put(methodReflect.getName(), methodMeta); + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginInvocationException.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginInvocationException.java new file mode 100644 index 0000000..ae6b0eb --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginInvocationException.java @@ -0,0 +1,16 @@ +package com.getcapacitor; + +class PluginInvocationException extends Exception { + + public PluginInvocationException(String s) { + super(s); + } + + public PluginInvocationException(Throwable t) { + super(t); + } + + public PluginInvocationException(String s, Throwable t) { + super(s, t); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginLoadException.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginLoadException.java new file mode 100644 index 0000000..8d81a38 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginLoadException.java @@ -0,0 +1,19 @@ +package com.getcapacitor; + +/** + * Thrown when a plugin fails to instantiate + */ +public class PluginLoadException extends Exception { + + public PluginLoadException(String s) { + super(s); + } + + public PluginLoadException(Throwable t) { + super(t); + } + + public PluginLoadException(String s, Throwable t) { + super(s, t); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginManager.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginManager.java new file mode 100644 index 0000000..540bc91 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginManager.java @@ -0,0 +1,56 @@ +package com.getcapacitor; + +import android.content.res.AssetManager; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class PluginManager { + + private final AssetManager assetManager; + + public PluginManager(AssetManager assetManager) { + this.assetManager = assetManager; + } + + public List> loadPluginClasses() throws PluginLoadException { + JSONArray pluginsJSON = parsePluginsJSON(); + ArrayList> pluginList = new ArrayList<>(); + + try { + for (int i = 0, size = pluginsJSON.length(); i < size; i++) { + JSONObject pluginJSON = pluginsJSON.getJSONObject(i); + String classPath = pluginJSON.getString("classpath"); + Class c = Class.forName(classPath); + pluginList.add(c.asSubclass(Plugin.class)); + } + } catch (JSONException e) { + throw new PluginLoadException("Could not parse capacitor.plugins.json as JSON"); + } catch (ClassNotFoundException e) { + throw new PluginLoadException("Could not find class by class path: " + e.getMessage()); + } + + return pluginList; + } + + private JSONArray parsePluginsJSON() throws PluginLoadException { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(assetManager.open("capacitor.plugins.json")))) { + StringBuilder builder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + builder.append(line); + } + String jsonString = builder.toString(); + return new JSONArray(jsonString); + } catch (IOException e) { + throw new PluginLoadException("Could not load capacitor.plugins.json"); + } catch (JSONException e) { + throw new PluginLoadException("Could not parse capacitor.plugins.json as JSON"); + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginMethod.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginMethod.java new file mode 100644 index 0000000..8566304 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginMethod.java @@ -0,0 +1,15 @@ +package com.getcapacitor; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface PluginMethod { + String RETURN_PROMISE = "promise"; + + String RETURN_CALLBACK = "callback"; + + String RETURN_NONE = "none"; + + String returnType() default RETURN_PROMISE; +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginMethodHandle.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginMethodHandle.java new file mode 100644 index 0000000..a728c1f --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginMethodHandle.java @@ -0,0 +1,33 @@ +package com.getcapacitor; + +import java.lang.reflect.Method; + +public class PluginMethodHandle { + + // The reflect method reference + private final Method method; + // The name of the method + private final String name; + // The return type of the method (see PluginMethod for constants) + private final String returnType; + + public PluginMethodHandle(Method method, PluginMethod methodDecorator) { + this.method = method; + + this.name = method.getName(); + + this.returnType = methodDecorator.returnType(); + } + + public String getReturnType() { + return returnType; + } + + public String getName() { + return name; + } + + public Method getMethod() { + return method; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginResult.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginResult.java new file mode 100644 index 0000000..cdc169e --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/PluginResult.java @@ -0,0 +1,84 @@ +package com.getcapacitor; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +/** + * Wraps a result for web from calling a native plugin. + */ +public class PluginResult { + + private final JSObject json; + + public PluginResult() { + this(new JSObject()); + } + + public PluginResult(JSObject json) { + this.json = json; + } + + public PluginResult put(String name, boolean value) { + return this.jsonPut(name, value); + } + + public PluginResult put(String name, double value) { + return this.jsonPut(name, value); + } + + public PluginResult put(String name, int value) { + return this.jsonPut(name, value); + } + + public PluginResult put(String name, long value) { + return this.jsonPut(name, value); + } + + /** + * Format a date as an ISO string + */ + public PluginResult put(String name, Date value) { + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); + df.setTimeZone(tz); + return this.jsonPut(name, df.format(value)); + } + + public PluginResult put(String name, Object value) { + return this.jsonPut(name, value); + } + + public PluginResult put(String name, PluginResult value) { + return this.jsonPut(name, value.json); + } + + PluginResult jsonPut(String name, Object value) { + try { + this.json.put(name, value); + } catch (Exception ex) { + Logger.error(Logger.tags("Plugin"), "", ex); + } + return this; + } + + public String toString() { + return this.json.toString(); + } + + /** + * Return plugin metadata and information about the result, if it succeeded the data, or error information if it didn't. + * This is used for appRestoredResult, as it's technically a raw data response from a plugin. + * @return the raw data response from the plugin. + */ + public JSObject getWrappedResult() { + JSObject ret = new JSObject(); + ret.put("pluginId", this.json.getString("pluginId")); + ret.put("methodName", this.json.getString("methodName")); + ret.put("success", this.json.getBoolean("success", false)); + ret.put("data", this.json.getJSObject("data")); + ret.put("error", this.json.getJSObject("error")); + return ret; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/ProcessedRoute.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/ProcessedRoute.java new file mode 100644 index 0000000..eb3d7b0 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/ProcessedRoute.java @@ -0,0 +1,37 @@ +package com.getcapacitor; + +/** + * An data class used in conjunction with RouteProcessor. + * + * @see com.getcapacitor.RouteProcessor + */ +public class ProcessedRoute { + + private String path; + private boolean isAsset; + private boolean ignoreAssetPath; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public boolean isAsset() { + return isAsset; + } + + public void setAsset(boolean asset) { + isAsset = asset; + } + + public boolean isIgnoreAssetPath() { + return ignoreAssetPath; + } + + public void setIgnoreAssetPath(boolean ignoreAssetPath) { + this.ignoreAssetPath = ignoreAssetPath; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/RouteProcessor.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/RouteProcessor.java new file mode 100644 index 0000000..670c8bc --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/RouteProcessor.java @@ -0,0 +1,8 @@ +package com.getcapacitor; + +/** + * An interface used in the processing of routes + */ +public interface RouteProcessor { + ProcessedRoute process(String basePath, String path); +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/ServerPath.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/ServerPath.java new file mode 100644 index 0000000..5b34b46 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/ServerPath.java @@ -0,0 +1,25 @@ +package com.getcapacitor; + +public class ServerPath { + + public enum PathType { + BASE_PATH, + ASSET_PATH + } + + private final PathType type; + private final String path; + + public ServerPath(PathType type, String path) { + this.type = type; + this.path = path; + } + + public PathType getType() { + return type; + } + + public String getPath() { + return path; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/UriMatcher.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/UriMatcher.java new file mode 100755 index 0000000..715a0a0 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/UriMatcher.java @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed 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 com.google.webviewlocalserver.third_party.android; +package com.getcapacitor; + +import android.net.Uri; +import com.getcapacitor.util.HostMask; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +public class UriMatcher { + + /** + * Creates the root node of the URI tree. + * + * @param code the code to match for the root URI + */ + public UriMatcher(Object code) { + mCode = code; + mWhich = -1; + mChildren = new ArrayList<>(); + mText = null; + } + + private UriMatcher() { + mCode = null; + mWhich = -1; + mChildren = new ArrayList<>(); + mText = null; + } + + /** + * Add a URI to match, and the code to return when this URI is + * matched. URI nodes may be exact match string, the token "*" + * that matches any text, or the token "#" that matches only + * numbers. + *

+ * Starting from API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, + * this method will accept a leading slash in the path. + * + * @param authority the authority to match + * @param path the path to match. * may be used as a wild card for + * any text, and # may be used as a wild card for numbers. + * @param code the code that is returned when a URI is matched + * against the given components. Must be positive. + */ + public void addURI(String scheme, String authority, String path, Object code) { + if (code == null) { + throw new IllegalArgumentException("Code can't be null"); + } + + String[] tokens = null; + if (path != null) { + String newPath = path; + // Strip leading slash if present. + if (!path.isEmpty() && path.charAt(0) == '/') { + newPath = path.substring(1); + } + tokens = PATH_SPLIT_PATTERN.split(newPath); + } + + int numTokens = tokens != null ? tokens.length : 0; + UriMatcher node = this; + for (int i = -2; i < numTokens; i++) { + String token; + if (i == -2) token = scheme; else if (i == -1) token = authority; else token = tokens[i]; + ArrayList children = node.mChildren; + int numChildren = children.size(); + UriMatcher child; + int j; + for (j = 0; j < numChildren; j++) { + child = children.get(j); + if (token.equals(child.mText)) { + node = child; + break; + } + } + if (j == numChildren) { + // Child not found, create it + child = new UriMatcher(); + if (i == -1 && token.contains("*")) { + child.mWhich = MASK; + } else if (token.equals("**")) { + child.mWhich = REST; + } else if (token.equals("*")) { + child.mWhich = TEXT; + } else { + child.mWhich = EXACT; + } + child.mText = token; + node.mChildren.add(child); + node = child; + } + } + node.mCode = code; + } + + static final Pattern PATH_SPLIT_PATTERN = Pattern.compile("/"); + + /** + * Try to match against the path in a url. + * + * @param uri The url whose path we will match against. + * @return The code for the matched node (added using addURI), + * or null if there is no matched node. + */ + public Object match(Uri uri) { + final List pathSegments = uri.getPathSegments(); + final int li = pathSegments.size(); + + UriMatcher node = this; + + if (li == 0 && uri.getAuthority() == null) { + return this.mCode; + } + + for (int i = -2; i < li; i++) { + String u; + if (i == -2) u = uri.getScheme(); else if (i == -1) u = uri.getAuthority(); else u = pathSegments.get(i); + ArrayList list = node.mChildren; + if (list == null) { + break; + } + node = null; + int lj = list.size(); + for (int j = 0; j < lj; j++) { + UriMatcher n = list.get(j); + which_switch:switch (n.mWhich) { + case MASK: + if (HostMask.Parser.parse(n.mText).matches(u)) { + node = n; + } + break; + case EXACT: + if (n.mText.equals(u)) { + node = n; + } + break; + case TEXT: + node = n; + break; + case REST: + return n.mCode; + } + if (node != null) { + break; + } + } + if (node == null) { + return null; + } + } + + return node.mCode; + } + + private static final int EXACT = 0; + private static final int TEXT = 1; + private static final int REST = 2; + private static final int MASK = 3; + + private Object mCode; + private int mWhich; + private String mText; + private ArrayList mChildren; +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/WebViewListener.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/WebViewListener.java new file mode 100644 index 0000000..6df4f6c --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/WebViewListener.java @@ -0,0 +1,57 @@ +package com.getcapacitor; + +import android.webkit.RenderProcessGoneDetail; +import android.webkit.WebView; + +/** + * Provides callbacks associated with the {@link BridgeWebViewClient} + */ +public abstract class WebViewListener { + + /** + * Callback for page load event. + * + * @param webView The WebView that loaded + */ + public void onPageLoaded(WebView webView) { + // Override me to add behavior to the page loaded event + } + + /** + * Callback for onReceivedError event. + * + * @param webView The WebView that loaded + */ + public void onReceivedError(WebView webView) { + // Override me to add behavior to handle the onReceivedError event + } + + /** + * Callback for onReceivedHttpError event. + * + * @param webView The WebView that loaded + */ + public void onReceivedHttpError(WebView webView) { + // Override me to add behavior to handle the onReceivedHttpError event + } + + /** + * Callback for page start event. + * + * @param webView The WebView that loaded + */ + public void onPageStarted(WebView webView) { + // Override me to add behavior to the page started event + } + + /** + * Callback for render process gone event. Return true if the state is handled. + * + * @param webView The WebView that loaded + * @return returns false by default if the listener is not overridden and used + */ + public boolean onRenderProcessGone(WebView webView, RenderProcessGoneDetail detail) { + // Override me to add behavior to the web view render process gone event + return false; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/WebViewLocalServer.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/WebViewLocalServer.java new file mode 100755 index 0000000..fd8cf89 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/WebViewLocalServer.java @@ -0,0 +1,730 @@ +/* +Copyright 2015 Google Inc. All rights reserved. + +Licensed 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 com.getcapacitor; + +import static com.getcapacitor.plugin.util.HttpRequestHandler.isDomainExcludedFromSSL; + +import android.content.Context; +import android.net.Uri; +import android.util.Base64; +import android.webkit.CookieManager; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import com.getcapacitor.plugin.util.CapacitorHttpUrlConnection; +import com.getcapacitor.plugin.util.HttpRequestHandler; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Helper class meant to be used with the android.webkit.WebView class to enable hosting assets, + * resources and other data on 'virtual' https:// URL. + * Hosting assets and resources on https:// URLs is desirable as it is compatible with the + * Same-Origin policy. + *

+ * This class is intended to be used from within the + * {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, String)} and + * {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, + * android.webkit.WebResourceRequest)} + * methods. + */ +public class WebViewLocalServer { + + private static final String capacitorFileStart = Bridge.CAPACITOR_FILE_START; + private static final String capacitorContentStart = Bridge.CAPACITOR_CONTENT_START; + private String basePath; + + private final UriMatcher uriMatcher; + private final AndroidProtocolHandler protocolHandler; + private final ArrayList authorities; + private boolean isAsset; + // Whether to route all requests to paths without extensions back to `index.html` + private final boolean html5mode; + private final JSInjector jsInjector; + private final Bridge bridge; + + /** + * A handler that produces responses for paths on the virtual asset server. + *

+ * Methods of this handler will be invoked on a background thread and care must be taken to + * correctly synchronize access to any shared state. + *

+ * On Android KitKat and above these methods may be called on more than one thread. This thread + * may be different than the thread on which the shouldInterceptRequest method was invoke. + * This means that on Android KitKat and above it is possible to block in this method without + * blocking other resources from loading. The number of threads used to parallelize loading + * is an internal implementation detail of the WebView and may change between updates which + * means that the amount of time spend blocking in this method should be kept to an absolute + * minimum. + */ + public abstract static class PathHandler { + + protected String mimeType; + private String encoding; + private String charset; + private int statusCode; + private String reasonPhrase; + private Map responseHeaders; + + public PathHandler() { + this(null, null, 200, "OK", null); + } + + public PathHandler(String encoding, String charset, int statusCode, String reasonPhrase, Map responseHeaders) { + this.encoding = encoding; + this.charset = charset; + this.statusCode = statusCode; + this.reasonPhrase = reasonPhrase; + Map tempResponseHeaders; + if (responseHeaders == null) { + tempResponseHeaders = new HashMap<>(); + } else { + tempResponseHeaders = responseHeaders; + } + tempResponseHeaders.put("Cache-Control", "no-cache"); + this.responseHeaders = tempResponseHeaders; + } + + public InputStream handle(WebResourceRequest request) { + return handle(request.getUrl()); + } + + public abstract InputStream handle(Uri url); + + public String getEncoding() { + return encoding; + } + + public String getCharset() { + return charset; + } + + public int getStatusCode() { + return statusCode; + } + + public String getReasonPhrase() { + return reasonPhrase; + } + + public Map getResponseHeaders() { + return responseHeaders; + } + } + + WebViewLocalServer(Context context, Bridge bridge, JSInjector jsInjector, ArrayList authorities, boolean html5mode) { + uriMatcher = new UriMatcher(null); + this.html5mode = html5mode; + this.protocolHandler = new AndroidProtocolHandler(context.getApplicationContext()); + this.authorities = authorities; + this.bridge = bridge; + this.jsInjector = jsInjector; + } + + private static Uri parseAndVerifyUrl(String url) { + if (url == null) { + return null; + } + Uri uri = Uri.parse(url); + if (uri == null) { + Logger.error("Malformed URL: " + url); + return null; + } + String path = uri.getPath(); + if (path == null || path.isEmpty()) { + Logger.error("URL does not have a path: " + url); + return null; + } + return uri; + } + + /** + * Attempt to retrieve the WebResourceResponse associated with the given request. + * This method should be invoked from within + * {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, + * android.webkit.WebResourceRequest)}. + * + * @param request the request to process. + * @return a response if the request URL had a matching handler, null if no handler was found. + */ + public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) { + Uri loadingUrl = request.getUrl(); + + if (null != loadingUrl.getPath() && loadingUrl.getPath().startsWith(Bridge.CAPACITOR_HTTP_INTERCEPTOR_START)) { + Logger.debug("Handling CapacitorHttp request: " + loadingUrl); + try { + return handleCapacitorHttpRequest(request); + } catch (Exception e) { + Logger.error(e.getLocalizedMessage()); + return null; + } + } + + PathHandler handler; + synchronized (uriMatcher) { + handler = (PathHandler) uriMatcher.match(request.getUrl()); + } + if (handler == null) { + return null; + } + + if (isLocalFile(loadingUrl) || isMainUrl(loadingUrl) || !isAllowedUrl(loadingUrl) || isErrorUrl(loadingUrl)) { + Logger.debug("Handling local request: " + request.getUrl().toString()); + return handleLocalRequest(request, handler); + } else { + return handleProxyRequest(request, handler); + } + } + + private boolean isLocalFile(Uri uri) { + String path = uri.getPath(); + return path.startsWith(capacitorContentStart) || path.startsWith(capacitorFileStart); + } + + private boolean isErrorUrl(Uri uri) { + String url = uri.toString(); + return url.equals(bridge.getErrorUrl()); + } + + private boolean isMainUrl(Uri loadingUrl) { + return (bridge.getServerUrl() == null && loadingUrl.getHost().equalsIgnoreCase(bridge.getHost())); + } + + private boolean isAllowedUrl(Uri loadingUrl) { + return !(bridge.getServerUrl() == null && !bridge.getAppAllowNavigationMask().matches(loadingUrl.getHost())); + } + + private String getReasonPhraseFromResponseCode(int code) { + return switch (code) { + case 100 -> "Continue"; + case 101 -> "Switching Protocols"; + case 200 -> "OK"; + case 201 -> "Created"; + case 202 -> "Accepted"; + case 203 -> "Non-Authoritative Information"; + case 204 -> "No Content"; + case 205 -> "Reset Content"; + case 206 -> "Partial Content"; + case 300 -> "Multiple Choices"; + case 301 -> "Moved Permanently"; + case 302 -> "Found"; + case 303 -> "See Other"; + case 304 -> "Not Modified"; + case 400 -> "Bad Request"; + case 401 -> "Unauthorized"; + case 403 -> "Forbidden"; + case 404 -> "Not Found"; + case 405 -> "Method Not Allowed"; + case 406 -> "Not Acceptable"; + case 407 -> "Proxy Authentication Required"; + case 408 -> "Request Timeout"; + case 409 -> "Conflict"; + case 410 -> "Gone"; + case 500 -> "Internal Server Error"; + case 501 -> "Not Implemented"; + case 502 -> "Bad Gateway"; + case 503 -> "Service Unavailable"; + case 504 -> "Gateway Timeout"; + case 505 -> "HTTP Version Not Supported"; + default -> "Unknown"; + }; + } + + private WebResourceResponse handleCapacitorHttpRequest(WebResourceRequest request) throws IOException { + String urlString = request.getUrl().getQueryParameter(Bridge.CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM); + URL url = new URL(urlString); + JSObject headers = new JSObject(); + + for (Map.Entry header : request.getRequestHeaders().entrySet()) { + headers.put(header.getKey(), header.getValue()); + } + + HttpRequestHandler.HttpURLConnectionBuilder connectionBuilder = new HttpRequestHandler.HttpURLConnectionBuilder() + .setUrl(url) + .setMethod(request.getMethod()) + .setHeaders(headers) + .openConnection(); + + CapacitorHttpUrlConnection connection = connectionBuilder.build(); + + if (!isDomainExcludedFromSSL(bridge, url)) { + connection.setSSLSocketFactory(bridge); + } + + connection.connect(); + + String mimeType = null; + String encoding = null; + Map responseHeaders = new LinkedHashMap<>(); + for (Map.Entry> entry : connection.getHeaderFields().entrySet()) { + StringBuilder builder = new StringBuilder(); + for (String value : entry.getValue()) { + builder.append(value); + builder.append(", "); + } + builder.setLength(builder.length() - 2); + + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + String[] contentTypeParts = builder.toString().split(";"); + mimeType = contentTypeParts[0].trim(); + if (contentTypeParts.length > 1) { + String[] encodingParts = contentTypeParts[1].split("="); + if (encodingParts.length > 1) { + encoding = encodingParts[1].trim(); + } + } + } else { + responseHeaders.put(entry.getKey(), builder.toString()); + } + } + + InputStream inputStream = connection.getErrorStream(); + if (inputStream == null) { + inputStream = connection.getInputStream(); + } + + if (null == mimeType) { + mimeType = getMimeType(request.getUrl().getPath(), inputStream); + } + + int responseCode = connection.getResponseCode(); + String reasonPhrase = getReasonPhraseFromResponseCode(responseCode); + + return new WebResourceResponse(mimeType, encoding, responseCode, reasonPhrase, responseHeaders, inputStream); + } + + private WebResourceResponse handleLocalRequest(WebResourceRequest request, PathHandler handler) { + String path = request.getUrl().getPath(); + + if (request.getRequestHeaders().get("Range") != null) { + InputStream responseStream = new LollipopLazyInputStream(handler, request); + String mimeType = getMimeType(path, responseStream); + Map tempResponseHeaders = handler.getResponseHeaders(); + int statusCode = 206; + try { + int totalRange = responseStream.available(); + String rangeString = request.getRequestHeaders().get("Range"); + String[] parts = rangeString.split("="); + String[] streamParts = parts[1].split("-"); + String fromRange = streamParts[0]; + int range = totalRange - 1; + if (streamParts.length > 1) { + range = Integer.parseInt(streamParts[1]); + } + tempResponseHeaders.put("Accept-Ranges", "bytes"); + tempResponseHeaders.put("Content-Range", "bytes " + fromRange + "-" + range + "/" + totalRange); + } catch (IOException e) { + statusCode = 404; + } + return new WebResourceResponse( + mimeType, + handler.getEncoding(), + statusCode, + handler.getReasonPhrase(), + tempResponseHeaders, + responseStream + ); + } + + if (isLocalFile(request.getUrl()) || isErrorUrl(request.getUrl())) { + InputStream responseStream = new LollipopLazyInputStream(handler, request); + String mimeType = getMimeType(request.getUrl().getPath(), responseStream); + int statusCode = getStatusCode(responseStream, handler.getStatusCode()); + return new WebResourceResponse( + mimeType, + handler.getEncoding(), + statusCode, + handler.getReasonPhrase(), + handler.getResponseHeaders(), + responseStream + ); + } + + if (path.equals("/cordova.js")) { + return new WebResourceResponse( + "application/javascript", + handler.getEncoding(), + handler.getStatusCode(), + handler.getReasonPhrase(), + handler.getResponseHeaders(), + null + ); + } + + if (path.equals("/") || (!request.getUrl().getLastPathSegment().contains(".") && html5mode)) { + InputStream responseStream; + try { + String startPath = this.basePath + "/index.html"; + if (bridge.getRouteProcessor() != null) { + ProcessedRoute processedRoute = bridge.getRouteProcessor().process(this.basePath, "/index.html"); + startPath = processedRoute.getPath(); + isAsset = processedRoute.isAsset(); + } + + if (isAsset) { + responseStream = protocolHandler.openAsset(startPath); + } else { + responseStream = protocolHandler.openFile(startPath); + } + } catch (IOException e) { + Logger.error("Unable to open index.html", e); + return null; + } + + responseStream = jsInjector.getInjectedStream(responseStream); + + int statusCode = getStatusCode(responseStream, handler.getStatusCode()); + return new WebResourceResponse( + "text/html", + handler.getEncoding(), + statusCode, + handler.getReasonPhrase(), + handler.getResponseHeaders(), + responseStream + ); + } + + if ("/favicon.ico".equalsIgnoreCase(path)) { + try { + return new WebResourceResponse("image/png", null, null); + } catch (Exception e) { + Logger.error("favicon handling failed", e); + } + } + + int periodIndex = path.lastIndexOf("."); + if (periodIndex >= 0) { + String ext = path.substring(path.lastIndexOf(".")); + + InputStream responseStream = new LollipopLazyInputStream(handler, request); + + // TODO: Conjure up a bit more subtlety than this + if (ext.equals(".html")) { + responseStream = jsInjector.getInjectedStream(responseStream); + } + + String mimeType = getMimeType(path, responseStream); + int statusCode = getStatusCode(responseStream, handler.getStatusCode()); + return new WebResourceResponse( + mimeType, + handler.getEncoding(), + statusCode, + handler.getReasonPhrase(), + handler.getResponseHeaders(), + responseStream + ); + } + + return null; + } + + /** + * Instead of reading files from the filesystem/assets, proxy through to the URL + * and let an external server handle it. + * @param request + * @param handler + * @return + */ + private WebResourceResponse handleProxyRequest(WebResourceRequest request, PathHandler handler) { + final String method = request.getMethod(); + if (method.equals("GET")) { + try { + String url = request.getUrl().toString(); + Map headers = request.getRequestHeaders(); + boolean isHtmlText = false; + for (Map.Entry header : headers.entrySet()) { + if (header.getKey().equalsIgnoreCase("Accept") && header.getValue().toLowerCase().contains("text/html")) { + isHtmlText = true; + break; + } + } + if (isHtmlText) { + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); + for (Map.Entry header : headers.entrySet()) { + conn.setRequestProperty(header.getKey(), header.getValue()); + } + String getCookie = CookieManager.getInstance().getCookie(url); + if (getCookie != null) { + conn.setRequestProperty("Cookie", getCookie); + } + conn.setRequestMethod(method); + conn.setReadTimeout(30 * 1000); + conn.setConnectTimeout(30 * 1000); + if (request.getUrl().getUserInfo() != null) { + byte[] userInfoBytes = request.getUrl().getUserInfo().getBytes(StandardCharsets.UTF_8); + String base64 = Base64.encodeToString(userInfoBytes, Base64.NO_WRAP); + conn.setRequestProperty("Authorization", "Basic " + base64); + } + + List cookies = conn.getHeaderFields().get("Set-Cookie"); + if (cookies != null) { + for (String cookie : cookies) { + CookieManager.getInstance().setCookie(url, cookie); + } + } + InputStream responseStream = conn.getInputStream(); + responseStream = jsInjector.getInjectedStream(responseStream); + return new WebResourceResponse( + "text/html", + handler.getEncoding(), + handler.getStatusCode(), + handler.getReasonPhrase(), + handler.getResponseHeaders(), + responseStream + ); + } + } catch (Exception ex) { + bridge.handleAppUrlLoadError(ex); + } + } + return null; + } + + private String getMimeType(String path, InputStream stream) { + String mimeType = null; + try { + mimeType = URLConnection.guessContentTypeFromName(path); // Does not recognize *.js + if (mimeType != null && path.endsWith(".js") && mimeType.equals("image/x-icon")) { + Logger.debug("We shouldn't be here"); + } + if (mimeType == null) { + if (path.endsWith(".js") || path.endsWith(".mjs")) { + // Make sure JS files get the proper mimetype to support ES modules + mimeType = "application/javascript"; + } else if (path.endsWith(".wasm")) { + mimeType = "application/wasm"; + } else { + mimeType = URLConnection.guessContentTypeFromStream(stream); + } + } + } catch (Exception ex) { + Logger.error("Unable to get mime type" + path, ex); + } + return mimeType; + } + + private int getStatusCode(InputStream stream, int defaultCode) { + int finalStatusCode = defaultCode; + try { + if (stream.available() == -1) { + finalStatusCode = 404; + } + } catch (IOException e) { + finalStatusCode = 500; + } + return finalStatusCode; + } + + /** + * Registers a handler for the given uri. The handler will be invoked + * every time the shouldInterceptRequest method of the instance is called with + * a matching uri. + * + * @param uri the uri to use the handler for. The scheme and authority (domain) will be matched + * exactly. The path may contain a '*' element which will match a single element of + * a path (so a handler registered for /a/* will be invoked for /a/b and /a/c.html + * but not for /a/b/b) or the '**' element which will match any number of path + * elements. + * @param handler the handler to use for the uri. + */ + void register(Uri uri, PathHandler handler) { + synchronized (uriMatcher) { + uriMatcher.addURI(uri.getScheme(), uri.getAuthority(), uri.getPath(), handler); + } + } + + /** + * Hosts the application's assets on an https:// URL. Assets from the local path + * assetPath/... will be available under + * https://{uuid}.androidplatform.net/assets/.... + * + * @param assetPath the local path in the application's asset folder which will be made + * available by the server (for example "/www"). + * @return prefixes under which the assets are hosted. + */ + public void hostAssets(String assetPath) { + this.isAsset = true; + this.basePath = assetPath; + createHostingDetails(); + } + + /** + * Hosts the application's files on an https:// URL. Files from the basePath + * basePath/... will be available under + * https://{uuid}.androidplatform.net/.... + * + * @param basePath the local path in the application's data folder which will be made + * available by the server (for example "/www"). + * @return prefixes under which the assets are hosted. + */ + public void hostFiles(final String basePath) { + this.isAsset = false; + this.basePath = basePath; + createHostingDetails(); + } + + private void createHostingDetails() { + final String assetPath = this.basePath; + + if (assetPath.indexOf('*') != -1) { + throw new IllegalArgumentException("assetPath cannot contain the '*' character."); + } + + PathHandler handler = new PathHandler() { + @Override + public InputStream handle(Uri url) { + InputStream stream = null; + String path = url.getPath(); + + // Pass path to routeProcessor if present + RouteProcessor routeProcessor = bridge.getRouteProcessor(); + boolean ignoreAssetPath = false; + if (routeProcessor != null) { + ProcessedRoute processedRoute = bridge.getRouteProcessor().process("", path); + path = processedRoute.getPath(); + isAsset = processedRoute.isAsset(); + ignoreAssetPath = processedRoute.isIgnoreAssetPath(); + } + + try { + if (path.startsWith(capacitorContentStart)) { + stream = protocolHandler.openContentUrl(url); + } else if (path.startsWith(capacitorFileStart)) { + stream = protocolHandler.openFile(path); + } else if (!isAsset) { + if (routeProcessor == null) { + path = basePath + url.getPath(); + } + + stream = protocolHandler.openFile(path); + } else if (ignoreAssetPath) { + stream = protocolHandler.openAsset(path); + } else { + stream = protocolHandler.openAsset(assetPath + path); + } + } catch (IOException e) { + Logger.error("Unable to open asset URL: " + url); + return null; + } + + return stream; + } + }; + + for (String authority : authorities) { + registerUriForScheme(Bridge.CAPACITOR_HTTP_SCHEME, handler, authority); + registerUriForScheme(Bridge.CAPACITOR_HTTPS_SCHEME, handler, authority); + + String customScheme = this.bridge.getScheme(); + if (!customScheme.equals(Bridge.CAPACITOR_HTTP_SCHEME) && !customScheme.equals(Bridge.CAPACITOR_HTTPS_SCHEME)) { + registerUriForScheme(customScheme, handler, authority); + } + } + } + + private void registerUriForScheme(String scheme, PathHandler handler, String authority) { + Uri.Builder uriBuilder = new Uri.Builder(); + uriBuilder.scheme(scheme); + uriBuilder.authority(authority); + uriBuilder.path(""); + Uri uriPrefix = uriBuilder.build(); + + register(Uri.withAppendedPath(uriPrefix, "/"), handler); + register(Uri.withAppendedPath(uriPrefix, "**"), handler); + } + + /** + * The KitKat WebView reads the InputStream on a separate threadpool. We can use that to + * parallelize loading. + */ + private abstract static class LazyInputStream extends InputStream { + + protected final PathHandler handler; + private InputStream is = null; + + public LazyInputStream(PathHandler handler) { + this.handler = handler; + } + + private InputStream getInputStream() { + if (is == null) { + is = handle(); + } + return is; + } + + protected abstract InputStream handle(); + + @Override + public int available() throws IOException { + InputStream is = getInputStream(); + return (is != null) ? is.available() : -1; + } + + @Override + public int read() throws IOException { + InputStream is = getInputStream(); + return (is != null) ? is.read() : -1; + } + + @Override + public int read(byte[] b) throws IOException { + InputStream is = getInputStream(); + return (is != null) ? is.read(b) : -1; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + InputStream is = getInputStream(); + return (is != null) ? is.read(b, off, len) : -1; + } + + @Override + public long skip(long n) throws IOException { + InputStream is = getInputStream(); + return (is != null) ? is.skip(n) : 0; + } + } + + // For L and above. + private static class LollipopLazyInputStream extends LazyInputStream { + + private WebResourceRequest request; + private InputStream is; + + public LollipopLazyInputStream(PathHandler handler, WebResourceRequest request) { + super(handler); + this.request = request; + } + + @Override + protected InputStream handle() { + return handler.handle(request); + } + } + + public String getBasePath() { + return this.basePath; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/ActivityCallback.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/ActivityCallback.java new file mode 100644 index 0000000..a158145 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/ActivityCallback.java @@ -0,0 +1,11 @@ +package com.getcapacitor.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface ActivityCallback { +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/CapacitorPlugin.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/CapacitorPlugin.java new file mode 100644 index 0000000..903378d --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/CapacitorPlugin.java @@ -0,0 +1,35 @@ +package com.getcapacitor.annotation; + +import android.content.Intent; +import com.getcapacitor.PluginCall; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Base annotation for all Plugins + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface CapacitorPlugin { + /** + * A custom name for the plugin, otherwise uses the + * simple class name. + */ + String name() default ""; + + /** + * Request codes this plugin uses and responds to, in order to tie + * Android events back the plugin to handle. + * + * NOTE: This is a legacy option provided to support third party libraries + * not currently implementing the new AndroidX Activity Results API. Plugins + * without this limitation should use a registered callback with + * {@link com.getcapacitor.Plugin#startActivityForResult(PluginCall, Intent, String)} + */ + int[] requestCodes() default {}; + + /** + * Permissions this plugin needs, in order to make permission requests + * easy if the plugin only needs basic permission prompting + */ + Permission[] permissions() default {}; +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/Permission.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/Permission.java new file mode 100644 index 0000000..3511437 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/Permission.java @@ -0,0 +1,22 @@ +package com.getcapacitor.annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Permission annotation for use with @CapacitorPlugin + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface Permission { + /** + * An array of Android permission strings. + * Eg: {Manifest.permission.ACCESS_COARSE_LOCATION} + * or {"android.permission.ACCESS_COARSE_LOCATION"} + */ + String[] strings() default {}; + + /** + * An optional name to use instead of the Android permission string. + */ + String alias() default ""; +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/PermissionCallback.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/PermissionCallback.java new file mode 100644 index 0000000..d4ca099 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/annotation/PermissionCallback.java @@ -0,0 +1,11 @@ +package com.getcapacitor.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface PermissionCallback { +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/CapacitorCordovaCookieManager.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/CapacitorCordovaCookieManager.java new file mode 100644 index 0000000..72ac4ee --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/CapacitorCordovaCookieManager.java @@ -0,0 +1,42 @@ +package com.getcapacitor.cordova; + +import android.webkit.CookieManager; +import android.webkit.WebView; +import org.apache.cordova.ICordovaCookieManager; + +class CapacitorCordovaCookieManager implements ICordovaCookieManager { + + protected final WebView webView; + private final CookieManager cookieManager; + + public CapacitorCordovaCookieManager(WebView webview) { + webView = webview; + cookieManager = CookieManager.getInstance(); + cookieManager.setAcceptThirdPartyCookies(webView, true); + } + + @Override + public void setCookiesEnabled(boolean accept) { + cookieManager.setAcceptCookie(accept); + } + + @Override + public void setCookie(final String url, final String value) { + cookieManager.setCookie(url, value); + } + + @Override + public String getCookie(final String url) { + return cookieManager.getCookie(url); + } + + @Override + public void clearCookies() { + cookieManager.removeAllCookies(null); + } + + @Override + public void flush() { + cookieManager.flush(); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaInterfaceImpl.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaInterfaceImpl.java new file mode 100644 index 0000000..7e8358d --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaInterfaceImpl.java @@ -0,0 +1,39 @@ +package com.getcapacitor.cordova; + +import android.util.Pair; +import androidx.appcompat.app.AppCompatActivity; +import java.util.concurrent.Executors; +import org.apache.cordova.CordovaInterfaceImpl; +import org.apache.cordova.CordovaPlugin; +import org.json.JSONException; + +public class MockCordovaInterfaceImpl extends CordovaInterfaceImpl { + + public MockCordovaInterfaceImpl(AppCompatActivity activity) { + super(activity, Executors.newCachedThreadPool()); + } + + public CordovaPlugin getActivityResultCallback() { + return this.activityResultCallback; + } + + /** + * Checks Cordova permission callbacks to handle permissions defined by a Cordova plugin. + * Returns true if Cordova is handling the permission request with a registered code. + * + * @param requestCode + * @param permissions + * @param grantResults + * @return true if Cordova handled the permission request, false if not + */ + @SuppressWarnings("deprecation") + public boolean handlePermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { + Pair callback = permissionResultCallbacks.getAndRemoveCallback(requestCode); + if (callback != null) { + callback.first.onRequestPermissionResult(callback.second, permissions, grantResults); + return true; + } + + return false; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaWebViewImpl.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaWebViewImpl.java new file mode 100644 index 0000000..d5b77cd --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/cordova/MockCordovaWebViewImpl.java @@ -0,0 +1,284 @@ +package com.getcapacitor.cordova; + +import android.content.Context; +import android.content.Intent; +import android.os.Handler; +import android.view.View; +import android.webkit.ValueCallback; +import android.webkit.WebChromeClient; +import android.webkit.WebView; +import java.util.List; +import java.util.Map; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPreferences; +import org.apache.cordova.CordovaResourceApi; +import org.apache.cordova.CordovaWebView; +import org.apache.cordova.CordovaWebViewEngine; +import org.apache.cordova.ICordovaCookieManager; +import org.apache.cordova.NativeToJsMessageQueue; +import org.apache.cordova.PluginEntry; +import org.apache.cordova.PluginManager; +import org.apache.cordova.PluginResult; + +public class MockCordovaWebViewImpl implements CordovaWebView { + + private Context context; + private PluginManager pluginManager; + private CordovaPreferences preferences; + private CordovaResourceApi resourceApi; + private NativeToJsMessageQueue nativeToJsMessageQueue; + private CordovaInterface cordova; + private CapacitorCordovaCookieManager cookieManager; + private WebView webView; + private boolean hasPausedEver; + + public MockCordovaWebViewImpl(Context context) { + this.context = context; + } + + @Override + public void init(CordovaInterface cordova, List pluginEntries, CordovaPreferences preferences) { + this.cordova = cordova; + this.preferences = preferences; + this.pluginManager = new PluginManager(this, this.cordova, pluginEntries); + this.resourceApi = new CordovaResourceApi(this.context, this.pluginManager); + this.pluginManager.init(); + } + + public void init(CordovaInterface cordova, List pluginEntries, CordovaPreferences preferences, WebView webView) { + this.cordova = cordova; + this.webView = webView; + this.preferences = preferences; + this.pluginManager = new PluginManager(this, this.cordova, pluginEntries); + this.resourceApi = new CordovaResourceApi(this.context, this.pluginManager); + nativeToJsMessageQueue = new NativeToJsMessageQueue(); + nativeToJsMessageQueue.addBridgeMode(new CapacitorEvalBridgeMode(webView, this.cordova)); + nativeToJsMessageQueue.setBridgeMode(0); + this.cookieManager = new CapacitorCordovaCookieManager(webView); + this.pluginManager.init(); + } + + public static class CapacitorEvalBridgeMode extends NativeToJsMessageQueue.BridgeMode { + + private final WebView webView; + private final CordovaInterface cordova; + + public CapacitorEvalBridgeMode(WebView webView, CordovaInterface cordova) { + this.webView = webView; + this.cordova = cordova; + } + + @Override + public void onNativeToJsMessageAvailable(final NativeToJsMessageQueue queue) { + cordova + .getActivity() + .runOnUiThread( + () -> { + String js = queue.popAndEncodeAsJs(); + if (js != null) { + webView.evaluateJavascript(js, null); + } + } + ); + } + } + + @Override + public boolean isInitialized() { + return cordova != null; + } + + @Override + public View getView() { + return this.webView; + } + + @Override + public void loadUrlIntoView(String url, boolean recreatePlugins) { + if (url.equals("about:blank") || url.startsWith("javascript:")) { + webView.loadUrl(url); + return; + } + } + + @Override + public void stopLoading() {} + + @Override + public boolean canGoBack() { + return false; + } + + @Override + public void clearCache() {} + + @Deprecated + @Override + public void clearCache(boolean b) {} + + @Override + public void clearHistory() {} + + @Override + public boolean backHistory() { + return false; + } + + @Override + public void handlePause(boolean keepRunning) { + if (!isInitialized()) { + return; + } + hasPausedEver = true; + pluginManager.onPause(keepRunning); + triggerDocumentEvent("pause"); + // If app doesn't want to run in background + if (!keepRunning) { + // Pause JavaScript timers. This affects all webviews within the app! + this.setPaused(true); + } + } + + @Override + public void onNewIntent(Intent intent) { + if (this.pluginManager != null) { + this.pluginManager.onNewIntent(intent); + } + } + + @Override + public void handleResume(boolean keepRunning) { + if (!isInitialized()) { + return; + } + this.setPaused(false); + this.pluginManager.onResume(keepRunning); + if (hasPausedEver) { + triggerDocumentEvent("resume"); + } + } + + @Override + public void handleStart() { + if (!isInitialized()) { + return; + } + pluginManager.onStart(); + } + + @Override + public void handleStop() { + if (!isInitialized()) { + return; + } + pluginManager.onStop(); + } + + @Override + public void handleDestroy() { + if (!isInitialized()) { + return; + } + this.pluginManager.onDestroy(); + } + + @Deprecated + @Override + public void sendJavascript(String statememt) { + nativeToJsMessageQueue.addJavaScript(statememt); + } + + public void eval(final String js, final ValueCallback callback) { + Handler mainHandler = new Handler(context.getMainLooper()); + mainHandler.post(() -> webView.evaluateJavascript(js, callback)); + } + + public void triggerDocumentEvent(final String eventName) { + eval("window.Capacitor.triggerEvent('" + eventName + "', 'document');", s -> {}); + } + + @Override + public void showWebPage(String url, boolean openExternal, boolean clearHistory, Map params) {} + + @Deprecated + @Override + public boolean isCustomViewShowing() { + return false; + } + + @Deprecated + @Override + public void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {} + + @Deprecated + @Override + public void hideCustomView() {} + + @Override + public CordovaResourceApi getResourceApi() { + return this.resourceApi; + } + + @Override + public void setButtonPlumbedToJs(int keyCode, boolean override) {} + + @Override + public boolean isButtonPlumbedToJs(int keyCode) { + return false; + } + + @Override + public void sendPluginResult(PluginResult cr, String callbackId) { + nativeToJsMessageQueue.addPluginResult(cr, callbackId); + } + + @Override + public PluginManager getPluginManager() { + return this.pluginManager; + } + + @Override + public CordovaWebViewEngine getEngine() { + return null; + } + + @Override + public CordovaPreferences getPreferences() { + return this.preferences; + } + + @Override + public ICordovaCookieManager getCookieManager() { + return cookieManager; + } + + @Override + public String getUrl() { + return webView.getUrl(); + } + + @Override + public Context getContext() { + return this.webView.getContext(); + } + + @Override + public void loadUrl(String url) { + loadUrlIntoView(url, true); + } + + @Override + public Object postMessage(String id, Object data) { + return pluginManager.postMessage(id, data); + } + + public void setPaused(boolean value) { + if (value) { + webView.onPause(); + webView.pauseTimers(); + } else { + webView.onResume(); + webView.resumeTimers(); + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookieManager.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookieManager.java new file mode 100644 index 0000000..1baf166 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookieManager.java @@ -0,0 +1,236 @@ +package com.getcapacitor.plugin; + +import com.getcapacitor.Bridge; +import com.getcapacitor.Logger; +import java.net.CookieManager; +import java.net.CookiePolicy; +import java.net.CookieStore; +import java.net.HttpCookie; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; + +public class CapacitorCookieManager extends CookieManager { + + private final android.webkit.CookieManager webkitCookieManager; + + private final String localUrl; + + private final String serverUrl; + + private final String TAG = "CapacitorCookies"; + + /** + * Create a new cookie manager with the default cookie store and policy + */ + public CapacitorCookieManager(Bridge bridge) { + this(null, null, bridge); + } + + /** + * Create a new cookie manager with specified cookie store and cookie policy. + * @param store a {@code CookieStore} to be used by CookieManager. if {@code null}, cookie + * manager will use a default one, which is an in-memory CookieStore implementation. + * @param policy a {@code CookiePolicy} instance to be used by cookie manager as policy + * callback. if {@code null}, ACCEPT_ORIGINAL_SERVER will be used. + */ + public CapacitorCookieManager(CookieStore store, CookiePolicy policy, Bridge bridge) { + super(store, policy); + webkitCookieManager = android.webkit.CookieManager.getInstance(); + this.localUrl = bridge.getLocalUrl(); + this.serverUrl = bridge.getServerUrl(); + } + + public void removeSessionCookies() { + this.webkitCookieManager.removeSessionCookies(null); + } + + public String getSanitizedDomain(String url) throws URISyntaxException { + if (url == null || url.isEmpty()) { + url = this.serverUrl; + } + + try { + new URI(url); + } catch (Exception ignored) { + url = this.localUrl; + + try { + new URI(url); + } catch (Exception error) { + Logger.error(TAG, "Failed to get sanitized URL.", error); + throw error; + } + } + + return url; + } + + private String getDomainFromCookieString(String cookie) throws URISyntaxException { + String[] domain = cookie.toLowerCase(Locale.ROOT).split("domain="); + return getSanitizedDomain(domain.length <= 1 ? null : domain[1].split(";")[0].trim()); + } + + /** + * Gets the cookies for the given URL. + * @param url the URL for which the cookies are requested + * @return value the cookies as a string, using the format of the 'Cookie' HTTP request header + */ + public String getCookieString(String url) { + try { + url = getSanitizedDomain(url); + Logger.info(TAG, "Getting cookies at: '" + url + "'"); + return webkitCookieManager.getCookie(url); + } catch (Exception error) { + Logger.error(TAG, "Failed to get cookies at the given URL.", error); + } + + return null; + } + + /** + * Gets a cookie value for the given URL and key. + * @param url the URL for which the cookies are requested + * @param key the key of the cookie to search for + * @return the {@code HttpCookie} value of the cookie at the key, + * otherwise it will return a new empty {@code HttpCookie} + */ + public HttpCookie getCookie(String url, String key) { + HttpCookie[] cookies = getCookies(url); + for (HttpCookie cookie : cookies) { + if (cookie.getName().equals(key)) { + return cookie; + } + } + + return null; + } + + /** + * Gets an array of {@code HttpCookie} given a URL. + * @param url the URL for which the cookies are requested + * @return an {@code HttpCookie} array of non-expired cookies + */ + public HttpCookie[] getCookies(String url) { + try { + ArrayList cookieList = new ArrayList<>(); + String cookieString = getCookieString(url); + if (cookieString != null) { + String[] singleCookie = cookieString.split(";"); + for (String c : singleCookie) { + HttpCookie parsed = HttpCookie.parse(c).get(0); + parsed.setValue(parsed.getValue()); + cookieList.add(parsed); + } + } + HttpCookie[] cookies = new HttpCookie[cookieList.size()]; + return cookieList.toArray(cookies); + } catch (Exception ex) { + return new HttpCookie[0]; + } + } + + /** + * Sets a cookie for the given URL. Any existing cookie with the same host, path and name will + * be replaced with the new cookie. The cookie being set will be ignored if it is expired. + * @param url the URL for which the cookie is to be set + * @param value the cookie as a string, using the format of the 'Set-Cookie' HTTP response header + */ + public void setCookie(String url, String value) { + try { + url = getSanitizedDomain(url); + Logger.info(TAG, "Setting cookie '" + value + "' at: '" + url + "'"); + webkitCookieManager.setCookie(url, value); + flush(); + } catch (Exception error) { + Logger.error(TAG, "Failed to set cookie.", error); + } + } + + /** + * Sets a cookie for the given URL. Any existing cookie with the same host, path and name will + * be replaced with the new cookie. The cookie being set will be ignored if it is expired. + * @param url the URL for which the cookie is to be set + * @param key the {@code HttpCookie} name to use for lookup + * @param value the value of the {@code HttpCookie} given a key + */ + public void setCookie(String url, String key, String value) { + String cookieValue = key + "=" + value; + setCookie(url, cookieValue); + } + + public void setCookie(String url, String key, String value, String expires, String path) { + String cookieValue = key + "=" + value + "; expires=" + expires + "; path=" + path; + setCookie(url, cookieValue); + } + + /** + * Removes all cookies. This method is asynchronous. + */ + public void removeAllCookies() { + webkitCookieManager.removeAllCookies(null); + flush(); + } + + /** + * Ensures all cookies currently accessible through the getCookie API are written to persistent + * storage. This call will block the caller until it is done and may perform I/O. + */ + public void flush() { + webkitCookieManager.flush(); + } + + @Override + public void put(URI uri, Map> responseHeaders) { + // make sure our args are valid + if ((uri == null) || (responseHeaders == null)) return; + + // go over the headers + for (String headerKey : responseHeaders.keySet()) { + // ignore headers which aren't cookie related + if ((headerKey == null) || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) continue; + + // process each of the headers + for (String headerValue : Objects.requireNonNull(responseHeaders.get(headerKey))) { + try { + // Set at the requested server url + setCookie(uri.toString(), headerValue); + + // Set at the defined domain in the response or at default capacitor hosted url + setCookie(getDomainFromCookieString(headerValue), headerValue); + } catch (Exception ignored) {} + } + } + } + + @Override + public Map> get(URI uri, Map> requestHeaders) { + // make sure our args are valid + if ((uri == null) || (requestHeaders == null)) throw new IllegalArgumentException("Argument is null"); + + // save our url once + String url = uri.toString(); + + // prepare our response + Map> res = new HashMap<>(); + + // get the cookie + String cookie = getCookieString(url); + + // return it + if (cookie != null) res.put("Cookie", Collections.singletonList(cookie)); + return res; + } + + @Override + public CookieStore getCookieStore() { + // we don't want anyone to work with this cookie store directly + throw new UnsupportedOperationException(); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java new file mode 100644 index 0000000..45c01be --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorCookies.java @@ -0,0 +1,137 @@ +package com.getcapacitor.plugin; + +import android.webkit.JavascriptInterface; +import com.getcapacitor.JSObject; +import com.getcapacitor.Plugin; +import com.getcapacitor.PluginCall; +import com.getcapacitor.PluginConfig; +import com.getcapacitor.PluginMethod; +import com.getcapacitor.annotation.CapacitorPlugin; +import java.io.UnsupportedEncodingException; +import java.net.CookieHandler; +import java.net.HttpCookie; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; + +@CapacitorPlugin +public class CapacitorCookies extends Plugin { + + CapacitorCookieManager cookieManager; + + @Override + public void load() { + this.bridge.getWebView().addJavascriptInterface(this, "CapacitorCookiesAndroidInterface"); + this.cookieManager = new CapacitorCookieManager(null, java.net.CookiePolicy.ACCEPT_ALL, this.bridge); + this.cookieManager.removeSessionCookies(); + CookieHandler.setDefault(this.cookieManager); + super.load(); + } + + @Override + protected void handleOnDestroy() { + super.handleOnDestroy(); + this.cookieManager.removeSessionCookies(); + } + + @JavascriptInterface + public boolean isEnabled() { + PluginConfig pluginConfig = getBridge().getConfig().getPluginConfiguration("CapacitorCookies"); + return pluginConfig.getBoolean("enabled", false); + } + + private boolean isAllowingInsecureCookies() { + PluginConfig pluginConfig = getBridge().getConfig().getPluginConfiguration("CapacitorCookies"); + return pluginConfig.getBoolean("androidCustomSchemeAllowInsecureAccess", false); + } + + @JavascriptInterface + public void setCookie(String domain, String action) { + cookieManager.setCookie(domain, action); + } + + @PluginMethod + public void getCookies(PluginCall call) { + if (isAllowingInsecureCookies()) { + String url = call.getString("url"); + JSObject cookiesMap = new JSObject(); + HttpCookie[] cookies = cookieManager.getCookies(url); + for (HttpCookie cookie : cookies) { + cookiesMap.put(cookie.getName(), cookie.getValue()); + } + call.resolve(cookiesMap); + } else { + this.bridge.eval( + "document.cookie", + value -> { + String cookies = value.substring(1, value.length() - 1); + String[] cookieArray = cookies.split(";"); + + JSObject cookieMap = new JSObject(); + + for (String cookie : cookieArray) { + if (cookie.length() > 0) { + String[] keyValue = cookie.split("=", 2); + + if (keyValue.length == 2) { + String key = keyValue[0].trim(); + String val = keyValue[1].trim(); + try { + key = URLDecoder.decode(keyValue[0].trim(), StandardCharsets.UTF_8.name()); + val = URLDecoder.decode(keyValue[1].trim(), StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException ignored) {} + + cookieMap.put(key, val); + } + } + } + + call.resolve(cookieMap); + } + ); + } + } + + @PluginMethod + public void setCookie(PluginCall call) { + String key = call.getString("key"); + if (null == key) { + call.reject("Must provide key"); + } + String value = call.getString("value"); + if (null == value) { + call.reject("Must provide value"); + } + String url = call.getString("url"); + String expires = call.getString("expires", ""); + String path = call.getString("path", "/"); + cookieManager.setCookie(url, key, value, expires, path); + call.resolve(); + } + + @PluginMethod + public void deleteCookie(PluginCall call) { + String key = call.getString("key"); + if (null == key) { + call.reject("Must provide key"); + } + String url = call.getString("url"); + cookieManager.setCookie(url, key + "=; Expires=Wed, 31 Dec 2000 23:59:59 GMT"); + call.resolve(); + } + + @PluginMethod + public void clearCookies(PluginCall call) { + String url = call.getString("url"); + HttpCookie[] cookies = cookieManager.getCookies(url); + for (HttpCookie cookie : cookies) { + cookieManager.setCookie(url, cookie.getName() + "=; Expires=Wed, 31 Dec 2000 23:59:59 GMT"); + } + call.resolve(); + } + + @PluginMethod + public void clearAllCookies(PluginCall call) { + cookieManager.removeAllCookies(); + call.resolve(); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorHttp.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorHttp.java new file mode 100644 index 0000000..46bc174 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/CapacitorHttp.java @@ -0,0 +1,119 @@ +package com.getcapacitor.plugin; + +import android.Manifest; +import android.webkit.JavascriptInterface; +import com.getcapacitor.JSObject; +import com.getcapacitor.Plugin; +import com.getcapacitor.PluginCall; +import com.getcapacitor.PluginConfig; +import com.getcapacitor.PluginMethod; +import com.getcapacitor.annotation.CapacitorPlugin; +import com.getcapacitor.annotation.Permission; +import com.getcapacitor.plugin.util.CapacitorHttpUrlConnection; +import com.getcapacitor.plugin.util.HttpRequestHandler; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@CapacitorPlugin( + permissions = { + @Permission(strings = { Manifest.permission.WRITE_EXTERNAL_STORAGE }, alias = "HttpWrite"), + @Permission(strings = { Manifest.permission.READ_EXTERNAL_STORAGE }, alias = "HttpRead") + } +) +public class CapacitorHttp extends Plugin { + + private final Map activeRequests = new ConcurrentHashMap<>(); + private final ExecutorService executor = Executors.newCachedThreadPool(); + + @Override + public void load() { + this.bridge.getWebView().addJavascriptInterface(this, "CapacitorHttpAndroidInterface"); + super.load(); + } + + @Override + protected void handleOnDestroy() { + super.handleOnDestroy(); + + for (Map.Entry entry : activeRequests.entrySet()) { + Runnable job = entry.getKey(); + PluginCall call = entry.getValue(); + + if (call.getData().has("activeCapacitorHttpUrlConnection")) { + try { + CapacitorHttpUrlConnection connection = (CapacitorHttpUrlConnection) call + .getData() + .get("activeCapacitorHttpUrlConnection"); + connection.disconnect(); + call.getData().remove("activeCapacitorHttpUrlConnection"); + } catch (Exception ignored) {} + } + + getBridge().releaseCall(call); + } + + activeRequests.clear(); + executor.shutdownNow(); + } + + private void http(final PluginCall call, final String httpMethod) { + Runnable asyncHttpCall = new Runnable() { + @Override + public void run() { + try { + JSObject response = HttpRequestHandler.request(call, httpMethod, getBridge()); + call.resolve(response); + } catch (Exception e) { + call.reject(e.getLocalizedMessage(), e.getClass().getSimpleName(), e); + } finally { + activeRequests.remove(this); + } + } + }; + + if (!executor.isShutdown()) { + activeRequests.put(asyncHttpCall, call); + executor.submit(asyncHttpCall); + } else { + call.reject("Failed to execute request - Http Plugin was shutdown"); + } + } + + @JavascriptInterface + public boolean isEnabled() { + PluginConfig pluginConfig = getBridge().getConfig().getPluginConfiguration("CapacitorHttp"); + return pluginConfig.getBoolean("enabled", false); + } + + @PluginMethod + public void request(final PluginCall call) { + this.http(call, null); + } + + @PluginMethod + public void get(final PluginCall call) { + this.http(call, "GET"); + } + + @PluginMethod + public void post(final PluginCall call) { + this.http(call, "POST"); + } + + @PluginMethod + public void put(final PluginCall call) { + this.http(call, "PUT"); + } + + @PluginMethod + public void patch(final PluginCall call) { + this.http(call, "PATCH"); + } + + @PluginMethod + public void delete(final PluginCall call) { + this.http(call, "DELETE"); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/WebView.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/WebView.java new file mode 100644 index 0000000..096d62a --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/WebView.java @@ -0,0 +1,48 @@ +package com.getcapacitor.plugin; + +import android.app.Activity; +import android.content.SharedPreferences; +import com.getcapacitor.JSObject; +import com.getcapacitor.Plugin; +import com.getcapacitor.PluginCall; +import com.getcapacitor.PluginMethod; +import com.getcapacitor.annotation.CapacitorPlugin; + +@CapacitorPlugin +public class WebView extends Plugin { + + public static final String WEBVIEW_PREFS_NAME = "CapWebViewSettings"; + public static final String CAP_SERVER_PATH = "serverBasePath"; + + @PluginMethod + public void setServerAssetPath(PluginCall call) { + String path = call.getString("path"); + bridge.setServerAssetPath(path); + call.resolve(); + } + + @PluginMethod + public void setServerBasePath(PluginCall call) { + String path = call.getString("path"); + bridge.setServerBasePath(path); + call.resolve(); + } + + @PluginMethod + public void getServerBasePath(PluginCall call) { + String path = bridge.getServerBasePath(); + JSObject ret = new JSObject(); + ret.put("path", path); + call.resolve(ret); + } + + @PluginMethod + public void persistServerBasePath(PluginCall call) { + String path = bridge.getServerBasePath(); + SharedPreferences prefs = getContext().getSharedPreferences(WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE); + SharedPreferences.Editor editor = prefs.edit(); + editor.putString(CAP_SERVER_PATH, path); + editor.apply(); + call.resolve(); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/AssetUtil.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/AssetUtil.java new file mode 100644 index 0000000..3a7043b --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/AssetUtil.java @@ -0,0 +1,358 @@ +package com.getcapacitor.plugin.util; + +import android.content.ContentResolver; +import android.content.Context; +import android.content.res.AssetManager; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.net.Uri; +import android.os.StrictMode; +import androidx.core.content.FileProvider; +import com.getcapacitor.Logger; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; + +/** + * Manager for assets. + */ +public final class AssetUtil { + + public static final int RESOURCE_ID_ZERO_VALUE = 0; + // Name of the storage folder + private static final String STORAGE_FOLDER = "/capacitorassets"; + + // Ref to the context passed through the constructor to access the + // resources and app directory. + private final Context context; + + /** + * Constructor + * + * @param context Application context. + */ + private AssetUtil(Context context) { + this.context = context; + } + + /** + * Static method to retrieve class instance. + * + * @param context Application context. + */ + public static AssetUtil getInstance(Context context) { + return new AssetUtil(context); + } + + /** + * The URI for a path. + * + * @param path The given path. + */ + public Uri parse(String path) { + if (path == null || path.isEmpty()) { + return Uri.EMPTY; + } else if (path.startsWith("res:")) { + return getUriForResourcePath(path); + } else if (path.startsWith("file:///")) { + return getUriFromPath(path); + } else if (path.startsWith("file://")) { + return getUriFromAsset(path); + } else if (path.startsWith("http")) { + return getUriFromRemote(path); + } else if (path.startsWith("content://")) { + return Uri.parse(path); + } + + return Uri.EMPTY; + } + + /** + * URI for a file. + * + * @param path Absolute path like file:///... + * + * @return URI pointing to the given path. + */ + private Uri getUriFromPath(String path) { + String absPath = path.replaceFirst("file://", "").replaceFirst("\\?.*$", ""); + File file = new File(absPath); + + if (!file.exists()) { + Logger.error("File not found: " + file.getAbsolutePath()); + return Uri.EMPTY; + } + + return getUriFromFile(file); + } + + /** + * URI for an asset. + * + * @param path Asset path like file://... + * + * @return URI pointing to the given path. + */ + private Uri getUriFromAsset(String path) { + String resPath = path.replaceFirst("file:/", "www").replaceFirst("\\?.*$", ""); + String fileName = resPath.substring(resPath.lastIndexOf('/') + 1); + File file = getTmpFile(fileName); + + if (file == null) return Uri.EMPTY; + + try { + AssetManager assets = context.getAssets(); + InputStream in = assets.open(resPath); + FileOutputStream out = new FileOutputStream(file); + copyFile(in, out); + } catch (Exception e) { + Logger.error("File not found: assets/" + resPath); + return Uri.EMPTY; + } + + return getUriFromFile(file); + } + + /** + * The URI for a resource. + * + * @param path The given relative path. + * + * @return URI pointing to the given path. + */ + private Uri getUriForResourcePath(String path) { + Resources res = context.getResources(); + String resPath = path.replaceFirst("res://", ""); + int resId = getResId(resPath); + + if (resId == 0) { + Logger.error("File not found: " + resPath); + return Uri.EMPTY; + } + + return new Uri.Builder() + .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) + .authority(res.getResourcePackageName(resId)) + .appendPath(res.getResourceTypeName(resId)) + .appendPath(res.getResourceEntryName(resId)) + .build(); + } + + /** + * Uri from remote located content. + * + * @param path Remote address. + * + * @return Uri of the downloaded file. + */ + private Uri getUriFromRemote(String path) { + File file = getTmpFile(); + + if (file == null) return Uri.EMPTY; + + try { + URL url = new URL(path); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + + StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); + + StrictMode.setThreadPolicy(policy); + + connection.setRequestProperty("Connection", "close"); + connection.setConnectTimeout(5000); + connection.connect(); + + InputStream in = connection.getInputStream(); + FileOutputStream out = new FileOutputStream(file); + + copyFile(in, out); + return getUriFromFile(file); + } catch (MalformedURLException e) { + Logger.error(Logger.tags("Asset"), "Incorrect URL", e); + } catch (FileNotFoundException e) { + Logger.error(Logger.tags("Asset"), "Failed to create new File from HTTP Content", e); + } catch (IOException e) { + Logger.error(Logger.tags("Asset"), "No Input can be created from http Stream", e); + } + + return Uri.EMPTY; + } + + /** + * Copy content from input stream into output stream. + * + * @param in The input stream. + * @param out The output stream. + */ + private void copyFile(InputStream in, FileOutputStream out) { + byte[] buffer = new byte[1024]; + int read; + + try { + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + out.flush(); + out.close(); + } catch (Exception e) { + Logger.error("Error copying", e); + } + } + + /** + * Resource ID for drawable. + * + * @param resPath Resource path as string. + * + * @return The resource ID or 0 if not found. + */ + public int getResId(String resPath) { + int resId = getResId(context.getResources(), resPath); + + if (resId == 0) { + resId = getResId(Resources.getSystem(), resPath); + } + + return resId; + } + + /** + * Get resource ID. + * + * @param res The resources where to look for. + * @param resPath The name of the resource. + * + * @return The resource ID or 0 if not found. + */ + private int getResId(Resources res, String resPath) { + String pkgName = getPkgName(res); + String resName = getBaseName(resPath); + int resId; + + resId = res.getIdentifier(resName, "mipmap", pkgName); + + if (resId == 0) { + resId = res.getIdentifier(resName, "drawable", pkgName); + } + + if (resId == 0) { + resId = res.getIdentifier(resName, "raw", pkgName); + } + + return resId; + } + + /** + * Convert URI to Bitmap. + * + * @param uri Internal image URI + */ + public Bitmap getIconFromUri(Uri uri) throws IOException { + InputStream input = context.getContentResolver().openInputStream(uri); + return BitmapFactory.decodeStream(input); + } + + /** + * Extract name of drawable resource from path. + * + * @param resPath Resource path as string. + */ + private String getBaseName(String resPath) { + String drawable = resPath; + + if (drawable.contains("/")) { + drawable = drawable.substring(drawable.lastIndexOf('/') + 1); + } + + if (resPath.contains(".")) { + drawable = drawable.substring(0, drawable.lastIndexOf('.')); + } + + return drawable; + } + + /** + * Returns a file located under the external cache dir of that app. + * + * @return File with a random UUID name. + */ + private File getTmpFile() { + return getTmpFile(UUID.randomUUID().toString()); + } + + /** + * Returns a file located under the external cache dir of that app. + * + * @param name The name of the file. + * + * @return File with the provided name. + */ + private File getTmpFile(String name) { + File dir = context.getExternalCacheDir(); + + if (dir == null) { + dir = context.getCacheDir(); + } + + if (dir == null) { + Logger.error(Logger.tags("Asset"), "Missing cache dir", null); + return null; + } + + String storage = dir.toString() + STORAGE_FOLDER; + + //noinspection ResultOfMethodCallIgnored + new File(storage).mkdir(); + + return new File(storage, name); + } + + /** + * Get content URI for the specified file. + * + * @param file The file to get the URI. + * + * @return content://... + */ + private Uri getUriFromFile(File file) { + try { + String authority = context.getPackageName() + ".provider"; + return FileProvider.getUriForFile(context, authority, file); + } catch (IllegalArgumentException e) { + Logger.error("File not supported by provider", e); + return Uri.EMPTY; + } + } + + /** + * Package name specified by the resource bundle. + */ + private String getPkgName(Resources res) { + return res == Resources.getSystem() ? "android" : context.getPackageName(); + } + + public static int getResourceID(Context context, String resourceName, String dir) { + return context.getResources().getIdentifier(resourceName, dir, context.getPackageName()); + } + + public static String getResourceBaseName(String resPath) { + if (resPath == null) return null; + + if (resPath.contains("/")) { + return resPath.substring(resPath.lastIndexOf('/') + 1); + } + + if (resPath.contains(".")) { + return resPath.substring(0, resPath.lastIndexOf('.')); + } + + return resPath; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/CapacitorHttpUrlConnection.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/CapacitorHttpUrlConnection.java new file mode 100644 index 0000000..cc784de --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/CapacitorHttpUrlConnection.java @@ -0,0 +1,475 @@ +package com.getcapacitor.plugin.util; + +import android.os.Build; +import android.os.LocaleList; +import android.text.TextUtils; +import com.getcapacitor.Bridge; +import com.getcapacitor.JSArray; +import com.getcapacitor.JSObject; +import com.getcapacitor.JSValue; +import com.getcapacitor.PluginCall; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.HttpURLConnection; +import java.net.ProtocolException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLEncoder; +import java.net.UnknownServiceException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSocketFactory; +import org.json.JSONException; +import org.json.JSONObject; + +public class CapacitorHttpUrlConnection implements ICapacitorHttpUrlConnection { + + private final HttpURLConnection connection; + + /** + * Make a new CapacitorHttpUrlConnection instance, which wraps around HttpUrlConnection + * and provides some helper functions for setting request headers and the request body + * @param conn the base HttpUrlConnection. You can pass the value from + * {@code (HttpUrlConnection) URL.openConnection()} + */ + public CapacitorHttpUrlConnection(HttpURLConnection conn) { + connection = conn; + this.setDefaultRequestProperties(); + } + + /** + * Returns the underlying HttpUrlConnection value + * @return the underlying HttpUrlConnection value + */ + public HttpURLConnection getHttpConnection() { + return connection; + } + + public void disconnect() { + connection.disconnect(); + } + + /** + * Set the value of the {@code allowUserInteraction} field of + * this {@code URLConnection}. + * + * @param isAllowedInteraction the new value. + * @throws IllegalStateException if already connected + */ + public void setAllowUserInteraction(boolean isAllowedInteraction) { + connection.setAllowUserInteraction(isAllowedInteraction); + } + + /** + * Set the method for the URL request, one of: + *

    + *
  • GET + *
  • POST + *
  • HEAD + *
  • OPTIONS + *
  • PUT + *
  • DELETE + *
  • TRACE + *
are legal, subject to protocol restrictions. The default + * method is GET. + * + * @param method the HTTP method + * @exception ProtocolException if the method cannot be reset or if + * the requested method isn't valid for HTTP. + * @exception SecurityException if a security manager is set and the + * method is "TRACE", but the "allowHttpTrace" + * NetPermission is not granted. + */ + public void setRequestMethod(String method) throws ProtocolException { + connection.setRequestMethod(method); + } + + /** + * Sets a specified timeout value, in milliseconds, to be used + * when opening a communications link to the resource referenced + * by this URLConnection. If the timeout expires before the + * connection can be established, a + * java.net.SocketTimeoutException is raised. A timeout of zero is + * interpreted as an infinite timeout. + * + *

Warning: If the hostname resolves to multiple IP + * addresses, Android's default implementation of {@link HttpURLConnection} + * will try each in + * RFC 3484 order. If + * connecting to each of these addresses fails, multiple timeouts will + * elapse before the connect attempt throws an exception. Host names + * that support both IPv6 and IPv4 always have at least 2 IP addresses. + * + * @param timeout an {@code int} that specifies the connect + * timeout value in milliseconds + * @throws IllegalArgumentException if the timeout parameter is negative + */ + public void setConnectTimeout(int timeout) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout can not be negative"); + } + connection.setConnectTimeout(timeout); + } + + /** + * Sets the read timeout to a specified timeout, in + * milliseconds. A non-zero value specifies the timeout when + * reading from Input stream when a connection is established to a + * resource. If the timeout expires before there is data available + * for read, a java.net.SocketTimeoutException is raised. A + * timeout of zero is interpreted as an infinite timeout. + * + * @param timeout an {@code int} that specifies the timeout + * value to be used in milliseconds + * @throws IllegalArgumentException if the timeout parameter is negative + */ + public void setReadTimeout(int timeout) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout can not be negative"); + } + connection.setReadTimeout(timeout); + } + + /** + * Sets whether automatic HTTP redirects should be disabled + * @param disableRedirects the flag to determine if redirects should be followed + */ + public void setDisableRedirects(boolean disableRedirects) { + connection.setInstanceFollowRedirects(!disableRedirects); + } + + /** + * Sets the request headers given a JSObject of key-value pairs + * @param headers the JSObject values to map to the HttpUrlConnection request headers + */ + public void setRequestHeaders(JSObject headers) { + Iterator keys = headers.keys(); + while (keys.hasNext()) { + String key = keys.next(); + String value = headers.getString(key); + connection.setRequestProperty(key, value); + } + } + + /** + * Sets the value of the {@code doOutput} field for this + * {@code URLConnection} to the specified value. + *

+ * A URL connection can be used for input and/or output. Set the DoOutput + * flag to true if you intend to use the URL connection for output, + * false if not. The default is false. + * + * @param shouldDoOutput the new value. + * @throws IllegalStateException if already connected + */ + public void setDoOutput(boolean shouldDoOutput) { + connection.setDoOutput(shouldDoOutput); + } + + /** + * + * @param call + * @throws JSONException + * @throws IOException + */ + public void setRequestBody(PluginCall call, JSValue body) throws JSONException, IOException { + setRequestBody(call, body, null); + } + + /** + * + * @param call + * @throws JSONException + * @throws IOException + */ + public void setRequestBody(PluginCall call, JSValue body, String bodyType) throws JSONException, IOException { + String contentType = connection.getRequestProperty("Content-Type"); + String dataString = ""; + + if (contentType == null || contentType.isEmpty()) return; + + if (contentType.contains("application/json")) { + JSArray jsArray = null; + if (body != null) { + dataString = body.toString(); + } else { + jsArray = call.getArray("data", null); + } + if (jsArray != null) { + dataString = jsArray.toString(); + } else if (body == null) { + dataString = call.getString("data"); + } + this.writeRequestBody(dataString != null ? dataString : ""); + } else if (bodyType != null && bodyType.equals("file")) { + try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + os.write(Base64.getDecoder().decode(body.toString())); + } + os.flush(); + } + } else if (contentType.contains("application/x-www-form-urlencoded")) { + try { + JSObject obj = body.toJSObject(); + this.writeObjectRequestBody(obj); + } catch (Exception e) { + // Body is not a valid JSON, treat it as an already formatted string + this.writeRequestBody(body.toString()); + } + } else if (bodyType != null && bodyType.equals("formData")) { + this.writeFormDataRequestBody(contentType, body.toJSArray()); + } else { + this.writeRequestBody(body.toString()); + } + } + + /** + * Writes the provided string to the HTTP connection managed by this instance. + * + * @param body The string value to write to the connection stream. + */ + private void writeRequestBody(String body) throws IOException { + try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { + os.write(body.getBytes(StandardCharsets.UTF_8)); + os.flush(); + } + } + + private void writeObjectRequestBody(JSObject object) throws IOException, JSONException { + try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { + Iterator keys = object.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object d = object.get(key); + os.writeBytes(key); + os.writeBytes("="); + os.writeBytes(URLEncoder.encode(d.toString(), "UTF-8")); + + if (keys.hasNext()) { + os.writeBytes("&"); + } + } + os.flush(); + } + } + + private void writeFormDataRequestBody(String contentType, JSArray entries) throws IOException, JSONException { + try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { + String boundary = contentType.split(";")[1].split("=")[1]; + String lineEnd = "\r\n"; + String twoHyphens = "--"; + + for (Object e : entries.toList()) { + if (e instanceof JSONObject) { + JSONObject entry = (JSONObject) e; + String type = entry.getString("type"); + String key = entry.getString("key"); + String value = entry.getString("value"); + if (type.equals("string")) { + os.writeBytes(twoHyphens + boundary + lineEnd); + os.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd + lineEnd); + os.write(value.getBytes(StandardCharsets.UTF_8)); + os.writeBytes(lineEnd); + } else if (type.equals("base64File")) { + String fileName = entry.getString("fileName"); + String fileContentType = entry.getString("contentType"); + + os.writeBytes(twoHyphens + boundary + lineEnd); + os.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + fileName + "\"" + lineEnd); + os.writeBytes("Content-Type: " + fileContentType + lineEnd); + os.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); + os.writeBytes(lineEnd); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + os.write(Base64.getDecoder().decode(value)); + } else { + os.write(android.util.Base64.decode(value, android.util.Base64.DEFAULT)); + } + + os.writeBytes(lineEnd); + } + } + } + + os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); + os.flush(); + } + } + + /** + * Opens a communications link to the resource referenced by this + * URL, if such a connection has not already been established. + *

+ * If the {@code connect} method is called when the connection + * has already been opened (indicated by the {@code connected} + * field having the value {@code true}), the call is ignored. + *

+ * URLConnection objects go through two phases: first they are + * created, then they are connected. After being created, and + * before being connected, various options can be specified + * (e.g., doInput and UseCaches). After connecting, it is an + * error to try to set them. Operations that depend on being + * connected, like getContentLength, will implicitly perform the + * connection, if necessary. + * + * @throws SocketTimeoutException if the timeout expires before + * the connection can be established + * @exception IOException if an I/O error occurs while opening the + * connection. + */ + public void connect() throws IOException { + connection.connect(); + } + + /** + * Gets the status code from an HTTP response message. + * For example, in the case of the following status lines: + *

+     * HTTP/1.0 200 OK
+     * HTTP/1.0 401 Unauthorized
+     * 
+ * It will return 200 and 401 respectively. + * Returns -1 if no code can be discerned + * from the response (i.e., the response is not valid HTTP). + * @throws IOException if an error occurred connecting to the server. + * @return the HTTP Status-Code, or -1 + */ + public int getResponseCode() throws IOException { + return connection.getResponseCode(); + } + + /** + * Returns the value of this {@code URLConnection}'s {@code URL} + * field. + * + * @return the value of this {@code URLConnection}'s {@code URL} + * field. + */ + public URL getURL() { + return connection.getURL(); + } + + /** + * Returns the error stream if the connection failed + * but the server sent useful data nonetheless. The + * typical example is when an HTTP server responds + * with a 404, which will cause a FileNotFoundException + * to be thrown in connect, but the server sent an HTML + * help page with suggestions as to what to do. + * + *

This method will not cause a connection to be initiated. If + * the connection was not connected, or if the server did not have + * an error while connecting or if the server had an error but + * no error data was sent, this method will return null. This is + * the default. + * + * @return an error stream if any, null if there have been no + * errors, the connection is not connected or the server sent no + * useful data. + */ + @Override + public InputStream getErrorStream() { + return connection.getErrorStream(); + } + + /** + * Returns the value of the named header field. + *

+ * If called on a connection that sets the same header multiple times + * with possibly different values, only the last value is returned. + * + * + * @param name the name of a header field. + * @return the value of the named header field, or {@code null} + * if there is no such field in the header. + */ + @Override + public String getHeaderField(String name) { + return connection.getHeaderField(name); + } + + /** + * Returns an input stream that reads from this open connection. + * + * A SocketTimeoutException can be thrown when reading from the + * returned input stream if the read timeout expires before data + * is available for read. + * + * @return an input stream that reads from this open connection. + * @exception IOException if an I/O error occurs while + * creating the input stream. + * @exception UnknownServiceException if the protocol does not support + * input. + * @see #setReadTimeout(int) + */ + @Override + public InputStream getInputStream() throws IOException { + return connection.getInputStream(); + } + + /** + * Returns an unmodifiable Map of the header fields. + * The Map keys are Strings that represent the + * response-header field names. Each Map value is an + * unmodifiable List of Strings that represents + * the corresponding field values. + * + * @return a Map of header fields + */ + public Map> getHeaderFields() { + return connection.getHeaderFields(); + } + + /** + * Sets the default request properties on the newly created connection. + * This is called as early as possible to allow overrides by user-provided values. + */ + private void setDefaultRequestProperties() { + String acceptLanguage = buildDefaultAcceptLanguageProperty(); + if (!TextUtils.isEmpty(acceptLanguage)) { + connection.setRequestProperty("Accept-Language", acceptLanguage); + } + } + + /** + * Builds and returns a locale string describing the device's current locale preferences. + */ + private String buildDefaultAcceptLanguageProperty() { + Locale locale; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + locale = LocaleList.getDefault().get(0); + } else { + locale = Locale.getDefault(); + } + String result = ""; + String lang = locale.getLanguage(); + String country = locale.getCountry(); + if (!TextUtils.isEmpty(lang)) { + if (!TextUtils.isEmpty(country)) { + result = String.format("%s-%s,%s;q=0.5", lang, country, lang); + } else { + result = String.format("%s;q=0.5", lang); + } + } + return result; + } + + public void setSSLSocketFactory(Bridge bridge) { + // Attach SSL Certificates if Enterprise Plugin is available + try { + Class sslPinningImpl = Class.forName("io.ionic.sslpinning.SSLPinning"); + Method method = sslPinningImpl.getDeclaredMethod("getSSLSocketFactory", Bridge.class); + SSLSocketFactory sslSocketFactory = (SSLSocketFactory) method.invoke(sslPinningImpl.newInstance(), bridge); + if (sslSocketFactory != null) { + ((HttpsURLConnection) this.connection).setSSLSocketFactory(sslSocketFactory); + } + } catch (Exception ignored) {} + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/HttpRequestHandler.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/HttpRequestHandler.java new file mode 100644 index 0000000..6e4bb74 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/HttpRequestHandler.java @@ -0,0 +1,452 @@ +package com.getcapacitor.plugin.util; + +import android.text.TextUtils; +import android.util.Base64; +import com.getcapacitor.Bridge; +import com.getcapacitor.JSArray; +import com.getcapacitor.JSObject; +import com.getcapacitor.JSValue; +import com.getcapacitor.PluginCall; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class HttpRequestHandler { + + /** + * An enum specifying conventional HTTP Response Types + * See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType + */ + public enum ResponseType { + ARRAY_BUFFER("arraybuffer"), + BLOB("blob"), + DOCUMENT("document"), + JSON("json"), + TEXT("text"); + + private final String name; + + ResponseType(String name) { + this.name = name; + } + + static final ResponseType DEFAULT = TEXT; + + public static ResponseType parse(String value) { + for (ResponseType responseType : values()) { + if (responseType.name.equalsIgnoreCase(value)) { + return responseType; + } + } + return DEFAULT; + } + } + + /** + * Internal builder class for building a CapacitorHttpUrlConnection + */ + public static class HttpURLConnectionBuilder { + + public Integer connectTimeout; + public Integer readTimeout; + public Boolean disableRedirects; + public JSObject headers; + public String method; + public URL url; + + public CapacitorHttpUrlConnection connection; + + public HttpURLConnectionBuilder setConnectTimeout(Integer connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + public HttpURLConnectionBuilder setReadTimeout(Integer readTimeout) { + this.readTimeout = readTimeout; + return this; + } + + public HttpURLConnectionBuilder setDisableRedirects(Boolean disableRedirects) { + this.disableRedirects = disableRedirects; + return this; + } + + public HttpURLConnectionBuilder setHeaders(JSObject headers) { + this.headers = headers; + return this; + } + + public HttpURLConnectionBuilder setMethod(String method) { + this.method = method; + return this; + } + + public HttpURLConnectionBuilder setUrl(URL url) { + this.url = url; + return this; + } + + public HttpURLConnectionBuilder openConnection() throws IOException { + connection = new CapacitorHttpUrlConnection((HttpURLConnection) url.openConnection()); + + connection.setAllowUserInteraction(false); + connection.setRequestMethod(method); + + if (connectTimeout != null) connection.setConnectTimeout(connectTimeout); + if (readTimeout != null) connection.setReadTimeout(readTimeout); + if (disableRedirects != null) connection.setDisableRedirects(disableRedirects); + + connection.setRequestHeaders(headers); + return this; + } + + public HttpURLConnectionBuilder setUrlParams(JSObject params) throws MalformedURLException, URISyntaxException, JSONException { + return this.setUrlParams(params, true); + } + + public HttpURLConnectionBuilder setUrlParams(JSObject params, boolean shouldEncode) + throws URISyntaxException, MalformedURLException { + String initialQuery = url.getQuery(); + String initialQueryBuilderStr = initialQuery == null ? "" : initialQuery; + + Iterator keys = params.keys(); + + if (!keys.hasNext()) { + return this; + } + + StringBuilder urlQueryBuilder = new StringBuilder(initialQueryBuilderStr); + + // Build the new query string + while (keys.hasNext()) { + String key = keys.next(); + + // Attempt as JSONArray and fallback to string if it fails + try { + StringBuilder value = new StringBuilder(); + JSONArray arr = params.getJSONArray(key); + for (int x = 0; x < arr.length(); x++) { + this.addUrlParam(value, key, arr.getString(x), shouldEncode); + if (x != arr.length() - 1) { + value.append("&"); + } + } + if (urlQueryBuilder.length() > 0) { + urlQueryBuilder.append("&"); + } + urlQueryBuilder.append(value); + } catch (JSONException e) { + if (urlQueryBuilder.length() > 0) { + urlQueryBuilder.append("&"); + } + this.addUrlParam(urlQueryBuilder, key, params.getString(key), shouldEncode); + } + } + + String urlQuery = urlQueryBuilder.toString(); + + URI uri = url.toURI(); + String unEncodedUrlString = + uri.getScheme() + + "://" + + uri.getAuthority() + + uri.getPath() + + ((!urlQuery.equals("")) ? "?" + urlQuery : "") + + ((uri.getFragment() != null) ? uri.getFragment() : ""); + this.url = new URL(unEncodedUrlString); + + return this; + } + + private static void addUrlParam(StringBuilder sb, String key, String value, boolean shouldEncode) { + if (shouldEncode) { + try { + key = URLEncoder.encode(key, "UTF-8"); + value = URLEncoder.encode(value, "UTF-8"); + } catch (UnsupportedEncodingException ex) { + throw new RuntimeException(ex.getCause()); + } + } + sb.append(key).append("=").append(value); + } + + public CapacitorHttpUrlConnection build() { + return connection; + } + } + + /** + * Builds an HTTP Response given CapacitorHttpUrlConnection and ResponseType objects. + * Defaults to ResponseType.DEFAULT + * @param connection The CapacitorHttpUrlConnection to respond with + * @throws IOException Thrown if the InputStream is unable to be parsed correctly + * @throws JSONException Thrown if the JSON is unable to be parsed + */ + public static JSObject buildResponse(CapacitorHttpUrlConnection connection) throws IOException, JSONException { + return buildResponse(connection, ResponseType.DEFAULT); + } + + /** + * Builds an HTTP Response given CapacitorHttpUrlConnection and ResponseType objects + * @param connection The CapacitorHttpUrlConnection to respond with + * @param responseType The requested ResponseType + * @return A JSObject that contains the HTTPResponse to return to the browser + * @throws IOException Thrown if the InputStream is unable to be parsed correctly + * @throws JSONException Thrown if the JSON is unable to be parsed + */ + public static JSObject buildResponse(CapacitorHttpUrlConnection connection, ResponseType responseType) + throws IOException, JSONException { + int statusCode = connection.getResponseCode(); + + JSObject output = new JSObject(); + output.put("status", statusCode); + output.put("headers", buildResponseHeaders(connection)); + output.put("url", connection.getURL()); + output.put("data", readData(connection, responseType)); + + InputStream errorStream = connection.getErrorStream(); + if (errorStream != null) { + output.put("error", true); + } + + return output; + } + + /** + * Read the existing ICapacitorHttpUrlConnection data + * @param connection The ICapacitorHttpUrlConnection object to read in + * @param responseType The type of HTTP response to return to the API + * @return The parsed data from the connection + * @throws IOException Thrown if the InputStreams cannot be properly parsed + * @throws JSONException Thrown if the JSON is malformed when parsing as JSON + */ + public static Object readData(ICapacitorHttpUrlConnection connection, ResponseType responseType) throws IOException, JSONException { + InputStream errorStream = connection.getErrorStream(); + String contentType = connection.getHeaderField("Content-Type"); + + if (errorStream != null) { + if (isOneOf(contentType, MimeType.APPLICATION_JSON, MimeType.APPLICATION_VND_API_JSON)) { + return parseJSON(readStreamAsString(errorStream)); + } else { + return readStreamAsString(errorStream); + } + } else if (contentType != null && contentType.contains(MimeType.APPLICATION_JSON.getValue())) { + // backward compatibility + return parseJSON(readStreamAsString(connection.getInputStream())); + } else { + InputStream stream = connection.getInputStream(); + switch (responseType) { + case ARRAY_BUFFER: + case BLOB: + return readStreamAsBase64(stream); + case JSON: + return parseJSON(readStreamAsString(stream)); + case DOCUMENT: + case TEXT: + default: + return readStreamAsString(stream); + } + } + } + + /** + * Helper function for determining if the Content-Type is a typeof an existing Mime-Type + * @param contentType The Content-Type string to check for + * @param mimeTypes The Mime-Type values to check against + * @return + */ + public static boolean isOneOf(String contentType, MimeType... mimeTypes) { + if (contentType != null) { + for (MimeType mimeType : mimeTypes) { + if (contentType.contains(mimeType.getValue())) { + return true; + } + } + } + return false; + } + + /** + * Build the JSObject response headers based on the connection header map + * @param connection The CapacitorHttpUrlConnection connection + * @return A JSObject of the header values from the CapacitorHttpUrlConnection + */ + public static JSObject buildResponseHeaders(CapacitorHttpUrlConnection connection) { + JSObject output = new JSObject(); + + for (Map.Entry> entry : connection.getHeaderFields().entrySet()) { + String valuesString = TextUtils.join(", ", entry.getValue()); + output.put(entry.getKey(), valuesString); + } + + return output; + } + + /** + * Returns a JSObject or a JSArray based on a string-ified input + * @param input String-ified JSON that needs parsing + * @return A JSObject or JSArray + * @throws JSONException thrown if the JSON is malformed + */ + public static Object parseJSON(String input) throws JSONException { + JSONObject json = new JSONObject(); + try { + if ("null".equals(input.trim())) { + return JSONObject.NULL; + } else if ("true".equals(input.trim())) { + return true; + } else if ("false".equals(input.trim())) { + return false; + } else if (input.trim().length() <= 0) { + return ""; + } else if (input.trim().matches("^\".*\"$")) { + // a string enclosed in " " is a json value, return the string without the quotes + return input.trim().substring(1, input.trim().length() - 1); + } else if (input.trim().matches("^-?\\d+$")) { + return Integer.parseInt(input.trim()); + } else if (input.trim().matches("^-?\\d+(\\.\\d+)?$")) { + return Double.parseDouble(input.trim()); + } else { + try { + return new JSObject(input); + } catch (JSONException e) { + return new JSArray(input); + } + } + } catch (JSONException e) { + return input; + } + } + + /** + * Returns a string based on a base64 InputStream + * @param in The base64 InputStream to convert to a String + * @return String value of InputStream + * @throws IOException thrown if the InputStream is unable to be read as base64 + */ + public static String readStreamAsBase64(InputStream in) throws IOException { + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buffer = new byte[1024]; + int readBytes; + while ((readBytes = in.read(buffer)) != -1) { + out.write(buffer, 0, readBytes); + } + byte[] result = out.toByteArray(); + return Base64.encodeToString(result, 0, result.length, Base64.DEFAULT); + } + } + + /** + * Returns a string based on an InputStream + * @param in The InputStream to convert to a String + * @return String value of InputStream + * @throws IOException thrown if the InputStream is unable to be read + */ + public static String readStreamAsString(InputStream in) throws IOException { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { + StringBuilder builder = new StringBuilder(); + String line = reader.readLine(); + while (line != null) { + builder.append(line); + line = reader.readLine(); + if (line != null) { + builder.append(System.getProperty("line.separator")); + } + } + return builder.toString(); + } + } + + /** + * Makes an Http Request based on the PluginCall parameters + * @param call The Capacitor PluginCall that contains the options need for an Http request + * @param httpMethod The HTTP method that overrides the PluginCall HTTP method + * @throws IOException throws an IO request when a connection can't be made + * @throws URISyntaxException thrown when the URI is malformed + * @throws JSONException thrown when the incoming JSON is malformed + */ + public static JSObject request(PluginCall call, String httpMethod, Bridge bridge) + throws IOException, URISyntaxException, JSONException { + String urlString = call.getString("url", ""); + JSObject headers = call.getObject("headers", new JSObject()); + JSObject params = call.getObject("params", new JSObject()); + Integer connectTimeout = call.getInt("connectTimeout"); + Integer readTimeout = call.getInt("readTimeout"); + Boolean disableRedirects = call.getBoolean("disableRedirects"); + Boolean shouldEncode = call.getBoolean("shouldEncodeUrlParams", true); + ResponseType responseType = ResponseType.parse(call.getString("responseType")); + String dataType = call.getString("dataType"); + + String method = httpMethod != null ? httpMethod.toUpperCase(Locale.ROOT) : call.getString("method", "GET").toUpperCase(Locale.ROOT); + + boolean isHttpMutate = method.equals("DELETE") || method.equals("PATCH") || method.equals("POST") || method.equals("PUT"); + + URL url = new URL(urlString); + HttpURLConnectionBuilder connectionBuilder = new HttpURLConnectionBuilder() + .setUrl(url) + .setMethod(method) + .setHeaders(headers) + .setUrlParams(params, shouldEncode) + .setConnectTimeout(connectTimeout) + .setReadTimeout(readTimeout) + .setDisableRedirects(disableRedirects) + .openConnection(); + + CapacitorHttpUrlConnection connection = connectionBuilder.build(); + + if (null != bridge && !isDomainExcludedFromSSL(bridge, url)) { + connection.setSSLSocketFactory(bridge); + } + + // Set HTTP body on a non GET or HEAD request + if (isHttpMutate) { + JSValue data = new JSValue(call, "data"); + if (data.getValue() != null) { + connection.setDoOutput(true); + connection.setRequestBody(call, data, dataType); + } + } + + call.getData().put("activeCapacitorHttpUrlConnection", connection); + connection.connect(); + + JSObject response = buildResponse(connection, responseType); + + connection.disconnect(); + call.getData().remove("activeCapacitorHttpUrlConnection"); + + return response; + } + + public static Boolean isDomainExcludedFromSSL(Bridge bridge, URL url) { + try { + Class sslPinningImpl = Class.forName("io.ionic.sslpinning.SSLPinning"); + Method method = sslPinningImpl.getDeclaredMethod("isDomainExcluded", Bridge.class, URL.class); + return (Boolean) method.invoke(sslPinningImpl.newInstance(), bridge, url); + } catch (Exception ignored) { + return false; + } + } + + @FunctionalInterface + public interface ProgressEmitter { + void emit(Integer bytes, Integer contentLength); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/ICapacitorHttpUrlConnection.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/ICapacitorHttpUrlConnection.java new file mode 100644 index 0000000..4ed8881 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/ICapacitorHttpUrlConnection.java @@ -0,0 +1,15 @@ +package com.getcapacitor.plugin.util; + +import java.io.IOException; +import java.io.InputStream; + +/** + * This interface was extracted from {@link CapacitorHttpUrlConnection} to enable mocking that class. + */ +public interface ICapacitorHttpUrlConnection { + InputStream getErrorStream(); + + String getHeaderField(String name); + + InputStream getInputStream() throws IOException; +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/MimeType.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/MimeType.java new file mode 100644 index 0000000..cfc90f8 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/plugin/util/MimeType.java @@ -0,0 +1,17 @@ +package com.getcapacitor.plugin.util; + +enum MimeType { + APPLICATION_JSON("application/json"), + APPLICATION_VND_API_JSON("application/vnd.api+json"), // https://jsonapi.org + TEXT_HTML("text/html"); + + private final String value; + + MimeType(String value) { + this.value = value; + } + + String getValue() { + return value; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/HostMask.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/HostMask.java new file mode 100644 index 0000000..486d0fd --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/HostMask.java @@ -0,0 +1,123 @@ +package com.getcapacitor.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public interface HostMask { + boolean matches(String host); + + class Parser { + + private static HostMask NOTHING = new Nothing(); + + public static HostMask parse(String[] masks) { + return masks == null ? NOTHING : HostMask.Any.parse(masks); + } + + public static HostMask parse(String mask) { + return mask == null ? NOTHING : HostMask.Simple.parse(mask); + } + } + + class Simple implements HostMask { + + private final List maskParts; + + private Simple(List maskParts) { + if (maskParts == null) { + throw new IllegalArgumentException("Mask parts can not be null"); + } + this.maskParts = maskParts; + } + + static Simple parse(String mask) { + List parts = Util.splitAndReverse(mask); + return new Simple(parts); + } + + @Override + public boolean matches(String host) { + if (host == null) { + return false; + } + List hostParts = Util.splitAndReverse(host); + int hostSize = hostParts.size(); + int maskSize = maskParts.size(); + if (maskSize > 1 && hostSize != maskSize) { + return false; + } + + int minSize = Math.min(hostSize, maskSize); + + for (int i = 0; i < minSize; i++) { + String maskPart = maskParts.get(i); + String hostPart = hostParts.get(i); + if (!Util.matches(maskPart, hostPart)) { + return false; + } + } + return true; + } + } + + class Any implements HostMask { + + private final List masks; + + Any(List masks) { + this.masks = masks; + } + + @Override + public boolean matches(String host) { + for (HostMask mask : masks) { + if (mask.matches(host)) { + return true; + } + } + return false; + } + + static Any parse(String... rawMasks) { + List masks = new ArrayList<>(); + for (String raw : rawMasks) { + masks.add(HostMask.Simple.parse(raw)); + } + return new Any(masks); + } + } + + class Nothing implements HostMask { + + @Override + public boolean matches(String host) { + return false; + } + } + + class Util { + + static boolean matches(String mask, String string) { + if (mask == null) { + return false; + } else if ("*".equals(mask)) { + return true; + } else if (string == null) { + return false; + } else { + return mask.toUpperCase().equals(string.toUpperCase()); + } + } + + static List splitAndReverse(String string) { + if (string == null) { + throw new IllegalArgumentException("Can not split null argument"); + } + List parts = Arrays.asList(string.split("\\.")); + Collections.reverse(parts); + return parts; + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/InternalUtils.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/InternalUtils.java new file mode 100644 index 0000000..b735415 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/InternalUtils.java @@ -0,0 +1,27 @@ +package com.getcapacitor.util; + +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.os.Build; + +public class InternalUtils { + + public static PackageInfo getPackageInfo(PackageManager pm, String packageName) throws PackageManager.NameNotFoundException { + return InternalUtils.getPackageInfo(pm, packageName, 0); + } + + public static PackageInfo getPackageInfo(PackageManager pm, String packageName, long flags) + throws PackageManager.NameNotFoundException { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + return pm.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags)); + } else { + return getPackageInfoLegacy(pm, packageName, (int) flags); + } + } + + @SuppressWarnings("deprecation") + private static PackageInfo getPackageInfoLegacy(PackageManager pm, String packageName, long flags) + throws PackageManager.NameNotFoundException { + return pm.getPackageInfo(packageName, (int) flags); + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/JSONUtils.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/JSONUtils.java new file mode 100644 index 0000000..1d2fc20 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/JSONUtils.java @@ -0,0 +1,166 @@ +package com.getcapacitor.util; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Helper methods for parsing JSON objects. + */ +public class JSONUtils { + + /** + * Get a string value from the given JSON object. + * + * @param jsonObject A JSON object to search + * @param key A key to fetch from the JSON object + * @param defaultValue A default value to return if the key cannot be found + * @return The value at the given key in the JSON object, or the default value + */ + public static String getString(JSONObject jsonObject, String key, String defaultValue) { + String k = getDeepestKey(key); + try { + JSONObject o = getDeepestObject(jsonObject, key); + + String value = o.getString(k); + if (value == null) { + return defaultValue; + } + return value; + } catch (JSONException ignore) { + // value was not found + } + + return defaultValue; + } + + /** + * Get a boolean value from the given JSON object. + * + * @param jsonObject A JSON object to search + * @param key A key to fetch from the JSON object + * @param defaultValue A default value to return if the key cannot be found + * @return The value at the given key in the JSON object, or the default value + */ + public static boolean getBoolean(JSONObject jsonObject, String key, boolean defaultValue) { + String k = getDeepestKey(key); + try { + JSONObject o = getDeepestObject(jsonObject, key); + + return o.getBoolean(k); + } catch (JSONException ignore) { + // value was not found + } + + return defaultValue; + } + + /** + * Get an int value from the given JSON object. + * + * @param jsonObject A JSON object to search + * @param key A key to fetch from the JSON object + * @param defaultValue A default value to return if the key cannot be found + * @return The value at the given key in the JSON object, or the default value + */ + public static int getInt(JSONObject jsonObject, String key, int defaultValue) { + String k = getDeepestKey(key); + try { + JSONObject o = getDeepestObject(jsonObject, key); + return o.getInt(k); + } catch (JSONException ignore) { + // value was not found + } + + return defaultValue; + } + + /** + * Get a JSON object value from the given JSON object. + * + * @param jsonObject A JSON object to search + * @param key A key to fetch from the JSON object + * @return The value from the config, if exists. Null if not + */ + public static JSONObject getObject(JSONObject jsonObject, String key) { + String k = getDeepestKey(key); + try { + JSONObject o = getDeepestObject(jsonObject, key); + + return o.getJSONObject(k); + } catch (JSONException ignore) { + // value was not found + } + + return null; + } + + /** + * Get a string array value from the given JSON object. + * + * @param jsonObject A JSON object to search + * @param key A key to fetch from the JSON object + * @param defaultValue A default value to return if the key cannot be found + * @return The value at the given key in the JSON object, or the default value + */ + public static String[] getArray(JSONObject jsonObject, String key, String[] defaultValue) { + String k = getDeepestKey(key); + try { + JSONObject o = getDeepestObject(jsonObject, key); + + JSONArray a = o.getJSONArray(k); + if (a == null) { + return defaultValue; + } + + int l = a.length(); + String[] value = new String[l]; + + for (int i = 0; i < l; i++) { + value[i] = (String) a.get(i); + } + + return value; + } catch (JSONException ignore) { + // value was not found + } + + return defaultValue; + } + + /** + * Given a JSON key path, gets the deepest key. + * + * @param key The key path + * @return The deepest key + */ + private static String getDeepestKey(String key) { + String[] parts = key.split("\\."); + if (parts.length > 0) { + return parts[parts.length - 1]; + } + + return null; + } + + /** + * Given a JSON object and key path, gets the deepest object in the path. + * + * @param jsonObject A JSON object + * @param key The key path to follow + * @return The deepest object along the key path + * @throws JSONException Thrown if any JSON errors + */ + private static JSONObject getDeepestObject(JSONObject jsonObject, String key) throws JSONException { + String[] parts = key.split("\\."); + JSONObject o = jsonObject; + + // Search until the second to last part of the key + for (int i = 0; i < parts.length - 1; i++) { + String k = parts[i]; + o = o.getJSONObject(k); + } + + return o; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/PermissionHelper.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/PermissionHelper.java new file mode 100644 index 0000000..e7b8332 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/PermissionHelper.java @@ -0,0 +1,114 @@ +package com.getcapacitor.util; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import androidx.core.app.ActivityCompat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * A helper class for checking permissions. + * + * @since 3.0.0 + */ +public class PermissionHelper { + + /** + * Checks if a list of given permissions are all granted by the user + * + * @since 3.0.0 + * @param permissions Permissions to check. + * @return True if all permissions are granted, false if at least one is not. + */ + public static boolean hasPermissions(Context context, String[] permissions) { + for (String perm : permissions) { + if (ActivityCompat.checkSelfPermission(context, perm) != PackageManager.PERMISSION_GRANTED) { + return false; + } + } + return true; + } + + /** + * Check whether the given permission has been defined in the AndroidManifest.xml + * + * @since 3.0.0 + * @param permission A permission to check. + * @return True if the permission has been defined in the Manifest, false if not. + */ + public static boolean hasDefinedPermission(Context context, String permission) { + boolean hasPermission = false; + String[] requestedPermissions = PermissionHelper.getManifestPermissions(context); + if (requestedPermissions != null && requestedPermissions.length > 0) { + List requestedPermissionsList = Arrays.asList(requestedPermissions); + ArrayList requestedPermissionsArrayList = new ArrayList<>(requestedPermissionsList); + if (requestedPermissionsArrayList.contains(permission)) { + hasPermission = true; + } + } + return hasPermission; + } + + /** + * Check whether all of the given permissions have been defined in the AndroidManifest.xml + * @param context the app context + * @param permissions a list of permissions + * @return true only if all permissions are defined in the AndroidManifest.xml + */ + public static boolean hasDefinedPermissions(Context context, String[] permissions) { + for (String permission : permissions) { + if (!PermissionHelper.hasDefinedPermission(context, permission)) { + return false; + } + } + + return true; + } + + /** + * Get the permissions defined in AndroidManifest.xml + * + * @since 3.0.0 + * @return The permissions defined in AndroidManifest.xml + */ + public static String[] getManifestPermissions(Context context) { + String[] requestedPermissions = null; + try { + PackageManager pm = context.getPackageManager(); + PackageInfo packageInfo = InternalUtils.getPackageInfo(pm, context.getPackageName(), PackageManager.GET_PERMISSIONS); + + if (packageInfo != null) { + requestedPermissions = packageInfo.requestedPermissions; + } + } catch (Exception ex) {} + return requestedPermissions; + } + + /** + * Given a list of permissions, return a new list with the ones not present in AndroidManifest.xml + * + * @since 3.0.0 + * @param neededPermissions The permissions needed. + * @return The permissions not present in AndroidManifest.xml + */ + public static String[] getUndefinedPermissions(Context context, String[] neededPermissions) { + ArrayList undefinedPermissions = new ArrayList<>(); + String[] requestedPermissions = getManifestPermissions(context); + if (requestedPermissions != null && requestedPermissions.length > 0) { + List requestedPermissionsList = Arrays.asList(requestedPermissions); + ArrayList requestedPermissionsArrayList = new ArrayList<>(requestedPermissionsList); + for (String permission : neededPermissions) { + if (!requestedPermissionsArrayList.contains(permission)) { + undefinedPermissions.add(permission); + } + } + String[] undefinedPermissionArray = new String[undefinedPermissions.size()]; + undefinedPermissionArray = undefinedPermissions.toArray(undefinedPermissionArray); + + return undefinedPermissionArray; + } + return neededPermissions; + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/WebColor.java b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/WebColor.java new file mode 100644 index 0000000..e055021 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/java/com/getcapacitor/util/WebColor.java @@ -0,0 +1,28 @@ +package com.getcapacitor.util; + +import android.graphics.Color; + +public class WebColor { + + /** + * Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. + * @param colorString The hexadecimal color string. The format is an RGB or RGBA hex string. + * @return The corresponding color as an int. + */ + public static int parseColor(String colorString) { + String formattedColor = colorString; + if (colorString.charAt(0) != '#') { + formattedColor = "#" + formattedColor; + } + + if (formattedColor.length() != 7 && formattedColor.length() != 9) { + throw new IllegalArgumentException("The encoded color space is invalid or unknown"); + } else if (formattedColor.length() == 7) { + return Color.parseColor(formattedColor); + } else { + // Convert to Android format #AARRGGBB from #RRGGBBAA + formattedColor = "#" + formattedColor.substring(7) + formattedColor.substring(1, 7); + return Color.parseColor(formattedColor); + } + } +} diff --git a/node_modules/@capacitor/android/capacitor/src/main/res/layout/bridge_layout_main.xml b/node_modules/@capacitor/android/capacitor/src/main/res/layout/bridge_layout_main.xml new file mode 100644 index 0000000..12f0b8f --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/res/layout/bridge_layout_main.xml @@ -0,0 +1,15 @@ + + + + + + diff --git a/node_modules/@capacitor/android/capacitor/src/main/res/layout/fragment_bridge.xml b/node_modules/@capacitor/android/capacitor/src/main/res/layout/fragment_bridge.xml new file mode 100644 index 0000000..b6123ea --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/res/layout/fragment_bridge.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/node_modules/@capacitor/android/capacitor/src/main/res/values/attrs.xml b/node_modules/@capacitor/android/capacitor/src/main/res/values/attrs.xml new file mode 100644 index 0000000..23a1037 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/res/values/attrs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/node_modules/@capacitor/android/capacitor/src/main/res/values/colors.xml b/node_modules/@capacitor/android/capacitor/src/main/res/values/colors.xml new file mode 100644 index 0000000..347d608 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #3F51B5 + #303F9F + #FF4081 + diff --git a/node_modules/@capacitor/android/capacitor/src/main/res/values/strings.xml b/node_modules/@capacitor/android/capacitor/src/main/res/values/strings.xml new file mode 100644 index 0000000..8542005 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/res/values/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/node_modules/@capacitor/android/capacitor/src/main/res/values/styles.xml b/node_modules/@capacitor/android/capacitor/src/main/res/values/styles.xml new file mode 100644 index 0000000..d326892 --- /dev/null +++ b/node_modules/@capacitor/android/capacitor/src/main/res/values/styles.xml @@ -0,0 +1,6 @@ + + + diff --git a/node_modules/@capacitor/android/package.json b/node_modules/@capacitor/android/package.json new file mode 100644 index 0000000..3cc0a08 --- /dev/null +++ b/node_modules/@capacitor/android/package.json @@ -0,0 +1,31 @@ +{ + "name": "@capacitor/android", + "version": "5.7.8", + "description": "Capacitor: Cross-platform apps with JavaScript and the web", + "homepage": "https://capacitorjs.com", + "author": "Ionic Team (https://ionic.io)", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ionic-team/capacitor.git" + }, + "bugs": { + "url": "https://github.com/ionic-team/capacitor/issues" + }, + "files": [ + "capacitor/build.gradle", + "capacitor/lint-baseline.xml", + "capacitor/lint.xml", + "capacitor/proguard-rules.pro", + "capacitor/src/main/" + ], + "scripts": { + "verify": "./gradlew clean lint build test -b capacitor/build.gradle" + }, + "peerDependencies": { + "@capacitor/core": "^5.7.0" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/@capacitor/ios/Capacitor.podspec b/node_modules/@capacitor/ios/Capacitor.podspec new file mode 100644 index 0000000..740b616 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor.podspec @@ -0,0 +1,25 @@ +require 'json' +package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) +prefix = if ENV['NATIVE_PUBLISH'] == 'true' + 'ios/' + else + '' + end + +Pod::Spec.new do |s| + s.name = 'Capacitor' + s.version = package['version'] + s.summary = 'Capacitor for iOS' + s.social_media_url = 'https://twitter.com/capacitorjs' + s.license = 'MIT' + s.homepage = 'https://capacitorjs.com/' + s.ios.deployment_target = '13.0' + s.authors = { 'Ionic Team' => 'hi@ionicframework.com' } + s.source = { git: 'https://github.com/ionic-team/capacitor.git', tag: package['version'] } + s.source_files = "#{prefix}Capacitor/Capacitor/*.{swift,h,m}", "#{prefix}Capacitor/Capacitor/Plugins/*.{swift,h,m}", + "#{prefix}Capacitor/Capacitor/Plugins/**/*.{swift,h,m}" + s.module_map = "#{prefix}Capacitor/Capacitor/Capacitor.modulemap" + s.resources = ["#{prefix}Capacitor/Capacitor/assets/native-bridge.js", "#{prefix}Capacitor/Capacitor/PrivacyInfo.xcprivacy"] + s.dependency 'CapacitorCordova' + s.swift_version = '5.1' +end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/AppUUID.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/AppUUID.swift new file mode 100644 index 0000000..42ea92d --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/AppUUID.swift @@ -0,0 +1,53 @@ +import CommonCrypto +import Foundation + +private func hexString(_ iterator: Array.Iterator) -> String { + return iterator.map { String(format: "%02x", $0) }.joined() +} + +extension Data { + public var sha256: String { + var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) + self.withUnsafeBytes { bytes in + _ = CC_SHA256(bytes.baseAddress, CC_LONG(self.count), &digest) + } + return hexString(digest.makeIterator()) + } +} + +public class AppUUID { + private static let key: String = "CapacitorAppUUID" + + public static func getAppUUID() -> String { + assertAppUUID() + return readUUID() + } + + public static func regenerateAppUUID() { + let uuid = generateUUID() + writeUUID(uuid) + } + + private static func assertAppUUID() { + let uuid = readUUID() + if uuid == "" { + regenerateAppUUID() + } + } + + private static func generateUUID() -> String { + let uuid: String = UUID.init().uuidString + return uuid.data(using: .utf8)!.sha256 + } + + private static func readUUID() -> String { + let defaults = UserDefaults.standard + return defaults.string(forKey: key) ?? "" + } + + private static func writeUUID(_ uuid: String) { + let defaults = UserDefaults.standard + defaults.set(uuid, forKey: key) + } + +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Array+Capacitor.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Array+Capacitor.swift new file mode 100644 index 0000000..e9d7a6f --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Array+Capacitor.swift @@ -0,0 +1,31 @@ +// convenience wrappers to transform Arrays between NSNull and Optional values, for interoperability with Obj-C +extension Array: CapacitorExtension {} +extension CapacitorExtensionTypeWrapper where T == [JSValue] { + public func replacingNullValues() -> [JSValue?] { + return baseType.map({ (value) -> JSValue? in + if value is NSNull { + return nil + } + return value + }) + } + + public func replacingOptionalValues() -> [JSValue] { + return baseType + } +} + +extension CapacitorExtensionTypeWrapper where T == [JSValue?] { + public func replacingNullValues() -> [JSValue?] { + return baseType + } + + public func replacingOptionalValues() -> [JSValue] { + return baseType.map({ (value) -> JSValue in + if let value = value { + return value + } + return NSNull() + }) + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPApplicationDelegateProxy.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPApplicationDelegateProxy.swift new file mode 100644 index 0000000..7f510bc --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPApplicationDelegateProxy.swift @@ -0,0 +1,32 @@ +import Foundation + +@objc(CAPApplicationDelegateProxy) +public class ApplicationDelegateProxy: NSObject, UIApplicationDelegate { + public static let shared = ApplicationDelegateProxy() + + public private(set) var lastURL: URL? + + public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { + NotificationCenter.default.post(name: .capacitorOpenURL, object: [ + "url": url, + "options": options + ]) + NotificationCenter.default.post(name: NSNotification.Name.CDVPluginHandleOpenURL, object: url) + lastURL = url + return true + } + + public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { + // TODO: Support other types, emit to rest of plugins + if userActivity.activityType != NSUserActivityTypeBrowsingWeb || userActivity.webpageURL == nil { + return false + } + + let url = userActivity.webpageURL + lastURL = url + NotificationCenter.default.post(name: .capacitorOpenUniversalLink, object: [ + "url": url + ]) + return true + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridge.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridge.swift new file mode 100644 index 0000000..a7b270f --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridge.swift @@ -0,0 +1,25 @@ +import Foundation + +// the @available compiler directive does not provide an easy way to split apart string literals, so ignore the line length +// swiftlint:disable line_length +@available(*, deprecated, message: "'statusBarTappedNotification' has been moved to Notification.Name.capacitorStatusBarTapped. 'getLastUrl' and application delegate methods have been moved to ApplicationDelegateProxy.") +// swiftlint:enable line_length +@objc public class CAPBridge: NSObject { + @objc public static let statusBarTappedNotification = Notification(name: .capacitorStatusBarTapped) + + public static func getLastUrl() -> URL? { + return ApplicationDelegateProxy.shared.lastURL + } + + public static func handleOpenUrl(_ url: URL, _ options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { + return ApplicationDelegateProxy.shared.application(UIApplication.shared, open: url, options: options) + } + + public static func handleContinueActivity(_ userActivity: NSUserActivity, _ restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { + return ApplicationDelegateProxy.shared.application(UIApplication.shared, continue: userActivity, restorationHandler: restorationHandler) + } + + public static func handleAppBecameActive(_ application: UIApplication) { + // no-op for now + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeDelegate.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeDelegate.swift new file mode 100644 index 0000000..5a24c94 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeDelegate.swift @@ -0,0 +1,6 @@ +import Foundation + +internal protocol CAPBridgeDelegate: AnyObject { + var bridgedWebView: WKWebView? { get } + var bridgedViewController: UIViewController? { get } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeProtocol.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeProtocol.swift new file mode 100644 index 0000000..306756e --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeProtocol.swift @@ -0,0 +1,146 @@ +import Foundation +import WebKit + +@objc public protocol CAPBridgeProtocol: NSObjectProtocol { + // MARK: - Environment Properties + var viewController: UIViewController? { get } + var config: InstanceConfiguration { get } + var webView: WKWebView? { get } + var notificationRouter: NotificationRouter { get } + var isSimEnvironment: Bool { get } + var isDevEnvironment: Bool { get } + var userInterfaceStyle: UIUserInterfaceStyle { get } + var autoRegisterPlugins: Bool { get } + var statusBarVisible: Bool { get set } + var statusBarStyle: UIStatusBarStyle { get set } + var statusBarAnimation: UIStatusBarAnimation { get set } + + // MARK: - Deprecated + @available(*, deprecated, renamed: "webView") + func getWebView() -> WKWebView? + + @available(*, deprecated, renamed: "isSimEnvironment") + func isSimulator() -> Bool + + @available(*, deprecated, renamed: "isDevEnvironment") + func isDevMode() -> Bool + + @available(*, deprecated, renamed: "statusBarVisible") + func getStatusBarVisible() -> Bool + + @available(*, deprecated, renamed: "statusBarStyle") + func getStatusBarStyle() -> UIStatusBarStyle + + @available(*, deprecated, renamed: "userInterfaceStyle") + func getUserInterfaceStyle() -> UIUserInterfaceStyle + + @available(*, deprecated, message: "Moved - equivalent is found on config.localURL") + func getLocalUrl() -> String + + @available(*, deprecated, renamed: "savedCall(withID:)") + func getSavedCall(_ callbackId: String) -> CAPPluginCall? + + @available(*, deprecated, renamed: "releaseCall(withID:)") + func releaseCall(callbackId: String) + + // MARK: - Plugin Access + func plugin(withName: String) -> CAPPlugin? + + // MARK: - Call Management + func saveCall(_ call: CAPPluginCall) + func savedCall(withID: String) -> CAPPluginCall? + func releaseCall(_ call: CAPPluginCall) + func releaseCall(withID: String) + + // MARK: - JavaScript Handling + // `js` is a short name but needs to be preserved for backwards compatibility. + // swiftlint:disable identifier_name + func evalWithPlugin(_ plugin: CAPPlugin, js: String) + func eval(js: String) + // swiftlint:enable identifier_name + + func triggerJSEvent(eventName: String, target: String) + func triggerJSEvent(eventName: String, target: String, data: String) + + func triggerWindowJSEvent(eventName: String) + func triggerWindowJSEvent(eventName: String, data: String) + + func triggerDocumentJSEvent(eventName: String) + func triggerDocumentJSEvent(eventName: String, data: String) + + // MARK: - Paths, Files, Assets + func localURL(fromWebURL webURL: URL?) -> URL? + func portablePath(fromLocalURL localURL: URL?) -> URL? + func setServerBasePath(_ path: String) + + // MARK: - Plugins + func registerPluginType(_ pluginType: CAPPlugin.Type) + func registerPluginInstance(_ pluginInstance: CAPPlugin) + + // MARK: - View Presentation + func showAlertWith(title: String, message: String, buttonTitle: String) + func presentVC(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) + func dismissVC(animated flag: Bool, completion: (() -> Void)?) +} + +/* + Extensions to Obj-C protocols are not exposed to Obj-C code because of limitations in the runtime. + Therefore these methods are implicitly Swift-only. + + The deprecated methods are declared here because they can be defined without colliding with the synthesized Obj-C setters + for the respective properties (e.g. `setStatusBarVisible:` for 'statusBarVisible`). + */ +extension CAPBridgeProtocol { + // variadic parameters cannot be exposed to Obj-C + @available(*, deprecated, message: "Use CAPLog directly") + public func modulePrint(_ plugin: CAPPlugin, _ items: Any...) { + let output = items.map { String(describing: $0) }.joined(separator: " ") + CAPLog.print("⚡️ ", plugin.pluginId, "-", output) + } + + // default arguments are not permitted in protocol declarations + public func alert(_ title: String, _ message: String, _ buttonTitle: String = "OK") { + showAlertWith(title: title, message: message, buttonTitle: buttonTitle) + } + + @available(*, deprecated, renamed: "statusBarVisible") + public func setStatusBarVisible(_ visible: Bool) { + statusBarVisible = visible + } + + @available(*, deprecated, renamed: "statusBarStyle") + public func setStatusBarStyle(_ style: UIStatusBarStyle) { + statusBarStyle = style + } + + @available(*, deprecated, renamed: "statusBarAnimation") + public func setStatusBarAnimation(_ animation: UIStatusBarAnimation) { + statusBarAnimation = animation + } +} + +/* + Error(s) potentially exported by the bridge. + */ +public enum CapacitorBridgeError: Error { + case errorExportingCoreJS +} + +extension CapacitorBridgeError: CustomNSError { + public static var errorDomain: String { "CapacitorBridge" } + public var errorCode: Int { + switch self { + case .errorExportingCoreJS: + return 0 + } + } + public var errorUserInfo: [String: Any] { + return ["info": String(describing: self)] + } +} + +extension CapacitorBridgeError: LocalizedError { + public var errorDescription: String? { + return NSLocalizedString("Unable to export JavaScript bridge code to webview", comment: "Capacitor bridge initialization error") + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController+CDVScreenOrientationDelegate.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController+CDVScreenOrientationDelegate.h new file mode 100644 index 0000000..aeda727 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController+CDVScreenOrientationDelegate.h @@ -0,0 +1,6 @@ +#import + +@interface CAPBridgeViewController (CDVScreenOrientationDelegate) + +@end + diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController+CDVScreenOrientationDelegate.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController+CDVScreenOrientationDelegate.m new file mode 100644 index 0000000..94c169a --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController+CDVScreenOrientationDelegate.m @@ -0,0 +1,5 @@ +#import "CAPBridgeViewController+CDVScreenOrientationDelegate.h" + +@implementation CAPBridgeViewController (CDVScreenOrientationDelegate) + +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController.swift new file mode 100644 index 0000000..56f243e --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgeViewController.swift @@ -0,0 +1,369 @@ +import UIKit +import WebKit +import Cordova + +@objc open class CAPBridgeViewController: UIViewController { + private var capacitorBridge: CapacitorBridge? + public final var bridge: CAPBridgeProtocol? { + return capacitorBridge + } + + public fileprivate(set) var webView: WKWebView? + + public var isStatusBarVisible = true + public var statusBarStyle: UIStatusBarStyle = .default + public var statusBarAnimation: UIStatusBarAnimation = .fade + @objc public var supportedOrientations: [Int] = [] + + public lazy final var isNewBinary: Bool = { + if let curVersionCode = Bundle.main.infoDictionary?["CFBundleVersion"] as? String, + let curVersionName = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { + if let lastVersionCode = UserDefaults.standard.string(forKey: "lastBinaryVersionCode"), + let lastVersionName = UserDefaults.standard.string(forKey: "lastBinaryVersionName") { + return (curVersionCode.isEqual(lastVersionCode) == false || curVersionName.isEqual(lastVersionName) == false) + } + return true + } + return false + }() + + override public final func loadView() { + // load the configuration and set the logging flag + let configDescriptor = instanceDescriptor() + let configuration = InstanceConfiguration(with: configDescriptor, isDebug: CapacitorBridge.isDevEnvironment) + CAPLog.enableLogging = configuration.loggingEnabled + logWarnings(for: configDescriptor) + + if configDescriptor.instanceType == .fixed { + updateBinaryVersion() + } + + setStatusBarDefaults() + setScreenOrientationDefaults() + + // get the web view + let assetHandler = WebViewAssetHandler(router: router()) + assetHandler.setAssetPath(configuration.appLocation.path) + assetHandler.setServerUrl(configuration.serverURL) + let delegationHandler = WebViewDelegationHandler() + prepareWebView(with: configuration, assetHandler: assetHandler, delegationHandler: delegationHandler) + view = webView + // create the bridge + capacitorBridge = CapacitorBridge(with: configuration, + delegate: self, + cordovaConfiguration: configDescriptor.cordovaConfiguration, + assetHandler: assetHandler, + delegationHandler: delegationHandler) + capacitorDidLoad() + } + + override open func viewDidLoad() { + super.viewDidLoad() + self.becomeFirstResponder() + loadWebView() + } + + override open func canPerformUnwindSegueAction(_ action: Selector, from fromViewController: UIViewController, withSender sender: Any) -> Bool { + return false + } + + // MARK: - Initialization + + /** + The InstanceDescriptor that should be used for the Capacitor environment. + + - Returns: `InstanceDescriptor` + + - Note: This is called early in the View Controller's lifecycle. Not all properties will be set at invocation. + */ + open func instanceDescriptor() -> InstanceDescriptor { + let descriptor = InstanceDescriptor.init() + if !isNewBinary && !descriptor.cordovaDeployDisabled { + if let persistedPath = UserDefaults.standard.string(forKey: "serverBasePath"), !persistedPath.isEmpty { + if let libPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first { + descriptor.appLocation = URL(fileURLWithPath: libPath, isDirectory: true) + .appendingPathComponent("NoCloud") + .appendingPathComponent("ionic_built_snapshots") + .appendingPathComponent(URL(fileURLWithPath: persistedPath, isDirectory: true).lastPathComponent) + } + } + } + return descriptor + } + + open func router() -> Router { + return _Router() + } + + /** + The WKWebViewConfiguration to use for the webview. + + - Parameter instanceConfiguration: the configuration that will define the capacitor environment. + + - Returns: `WKWebViewConfiguration` + + It is recommended to call super's implementation and modify the result, rather than creating a new object. + */ + open func webViewConfiguration(for instanceConfiguration: InstanceConfiguration) -> WKWebViewConfiguration { + let webViewConfiguration = WKWebViewConfiguration() + webViewConfiguration.websiteDataStore.httpCookieStore.add(CapacitorWKCookieObserver()) + webViewConfiguration.allowsInlineMediaPlayback = true + webViewConfiguration.suppressesIncrementalRendering = false + webViewConfiguration.allowsAirPlayForMediaPlayback = true + webViewConfiguration.mediaTypesRequiringUserActionForPlayback = [] + if #available(iOS 14.0, *) { + webViewConfiguration.limitsNavigationsToAppBoundDomains = instanceConfiguration.limitsNavigationsToAppBoundDomains + } + if let appendUserAgent = instanceConfiguration.appendedUserAgentString { + if let appName = webViewConfiguration.applicationNameForUserAgent { + webViewConfiguration.applicationNameForUserAgent = "\(appName) \(appendUserAgent)" + } else { + webViewConfiguration.applicationNameForUserAgent = appendUserAgent + } + } + if let preferredContentMode = instanceConfiguration.preferredContentMode { + var mode = WKWebpagePreferences.ContentMode.recommended + if preferredContentMode == "mobile" { + mode = WKWebpagePreferences.ContentMode.mobile + } else if preferredContentMode == "desktop" { + mode = WKWebpagePreferences.ContentMode.desktop + } + webViewConfiguration.defaultWebpagePreferences.preferredContentMode = mode + } + return webViewConfiguration + } + + /** + Returns a WKWebView initialized with the frame and configuration. + + Subclasses can override this method to return a subclass of WKWebView if needed. + */ + open func webView(with frame: CGRect, configuration: WKWebViewConfiguration) -> WKWebView { + return WKWebView(frame: frame, configuration: configuration) + } + + /** + Allows any additional configuration to be performed. The `webView` and `bridge` properties will be set by this point. + + - Note: This is called before the webview has been added to the view hierarchy. Not all operations may be possible at + this time. + */ + open func capacitorDidLoad() { + } + + public final func loadWebView() { + guard let bridge = capacitorBridge else { + return + } + + guard FileManager.default.fileExists(atPath: bridge.config.appStartFileURL.path) else { + fatalLoadError() + } + + let url = bridge.config.appStartServerURL + CAPLog.print("⚡️ Loading app at \(url.absoluteString)...") + bridge.webViewDelegationHandler.willLoadWebview(webView) + _ = webView?.load(URLRequest(url: url)) + } + + // MARK: - System Integration + + open func setStatusBarDefaults() { + if let plist = Bundle.main.infoDictionary { + if let statusBarHidden = plist["UIStatusBarHidden"] as? Bool { + if statusBarHidden { + self.isStatusBarVisible = false + } + } + if let statusBarStyle = plist["UIStatusBarStyle"] as? String { + if statusBarStyle == "UIStatusBarStyleDarkContent" { + self.statusBarStyle = .darkContent + } else if statusBarStyle != "UIStatusBarStyleDefault" { + self.statusBarStyle = .lightContent + } + } + } + } + + open func setScreenOrientationDefaults() { + if let plist = Bundle.main.infoDictionary { + if let orientations = plist["UISupportedInterfaceOrientations"] as? [String] { + for orientation in orientations { + if orientation == "UIInterfaceOrientationPortrait" { + self.supportedOrientations.append(UIInterfaceOrientation.portrait.rawValue) + } + if orientation == "UIInterfaceOrientationPortraitUpsideDown" { + self.supportedOrientations.append(UIInterfaceOrientation.portraitUpsideDown.rawValue) + } + if orientation == "UIInterfaceOrientationLandscapeLeft" { + self.supportedOrientations.append(UIInterfaceOrientation.landscapeLeft.rawValue) + } + if orientation == "UIInterfaceOrientationLandscapeRight" { + self.supportedOrientations.append(UIInterfaceOrientation.landscapeRight.rawValue) + } + } + if self.supportedOrientations.count == 0 { + self.supportedOrientations.append(UIInterfaceOrientation.portrait.rawValue) + } + } + } + } + + override open var prefersStatusBarHidden: Bool { + return !isStatusBarVisible + } + + override open var preferredStatusBarStyle: UIStatusBarStyle { + return statusBarStyle + } + + override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { + return statusBarAnimation + } + + open func setStatusBarVisible(_ isStatusBarVisible: Bool) { + self.isStatusBarVisible = isStatusBarVisible + UIView.animate(withDuration: 0.2, animations: { + self.setNeedsStatusBarAppearanceUpdate() + }) + } + + open func setStatusBarStyle(_ statusBarStyle: UIStatusBarStyle) { + self.statusBarStyle = statusBarStyle + UIView.animate(withDuration: 0.2, animations: { + self.setNeedsStatusBarAppearanceUpdate() + }) + } + + open func setStatusBarAnimation(_ statusBarAnimation: UIStatusBarAnimation) { + self.statusBarAnimation = statusBarAnimation + } + + override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { + var ret = 0 + if self.supportedOrientations.contains(UIInterfaceOrientation.portrait.rawValue) { + ret = ret | (1 << UIInterfaceOrientation.portrait.rawValue) + } + if self.supportedOrientations.contains(UIInterfaceOrientation.portraitUpsideDown.rawValue) { + ret = ret | (1 << UIInterfaceOrientation.portraitUpsideDown.rawValue) + } + if self.supportedOrientations.contains(UIInterfaceOrientation.landscapeRight.rawValue) { + ret = ret | (1 << UIInterfaceOrientation.landscapeRight.rawValue) + } + if self.supportedOrientations.contains(UIInterfaceOrientation.landscapeLeft.rawValue) { + ret = ret | (1 << UIInterfaceOrientation.landscapeLeft.rawValue) + } + return UIInterfaceOrientationMask.init(rawValue: UInt(ret)) + } +} + +// MARK: - Application Path + +extension CAPBridgeViewController { + @objc public func getServerBasePath() -> String { + return bridge?.config.appLocation.path ?? "" + } + + @objc public func setServerBasePath(path: String) { + guard let capBridge = capacitorBridge else { return } + capBridge.setServerBasePath(path) + DispatchQueue.main.async { [weak self] in + _ = self?.webView?.load(URLRequest(url: capBridge.config.serverURL)) + } + } +} + +// MARK: - Private + +extension CAPBridgeViewController { + private func prepareWebView(with configuration: InstanceConfiguration, assetHandler: WebViewAssetHandler, delegationHandler: WebViewDelegationHandler) { + // set the cookie policy + HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always + // setup the web view configuration + let webConfig = webViewConfiguration(for: configuration) + webConfig.setURLSchemeHandler(assetHandler, forURLScheme: configuration.localURL.scheme ?? InstanceDescriptorDefaults.scheme) + webConfig.userContentController = delegationHandler.contentController + // create the web view and set its properties + let aWebView = webView(with: .zero, configuration: webConfig) + aWebView.scrollView.bounces = false + aWebView.scrollView.contentInsetAdjustmentBehavior = configuration.contentInsetAdjustmentBehavior + aWebView.allowsLinkPreview = configuration.allowLinkPreviews + aWebView.scrollView.isScrollEnabled = configuration.scrollingEnabled + if let overrideUserAgent = configuration.overridenUserAgentString { + aWebView.customUserAgent = overrideUserAgent + } + if let backgroundColor = configuration.backgroundColor { + aWebView.backgroundColor = backgroundColor + aWebView.scrollView.backgroundColor = backgroundColor + } else { + // Use the system background colors if background is not set by user + aWebView.backgroundColor = UIColor.systemBackground + aWebView.scrollView.backgroundColor = UIColor.systemBackground + } + aWebView.capacitor.setKeyboardShouldRequireUserInteraction(false) + // set our ivar + webView = aWebView + // set our delegates + aWebView.uiDelegate = delegationHandler + aWebView.navigationDelegate = delegationHandler + } + + private func updateBinaryVersion() { + guard isNewBinary else { + return + } + guard let versionCode = Bundle.main.infoDictionary?["CFBundleVersion"] as? String, + let versionName = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { + return + } + let prefs = UserDefaults.standard + prefs.set(versionCode, forKey: "lastBinaryVersionCode") + prefs.set(versionName, forKey: "lastBinaryVersionName") + prefs.set("", forKey: "serverBasePath") + prefs.synchronize() + } + + private func logWarnings(for descriptor: InstanceDescriptor) { + if descriptor.warnings.contains(.missingAppDir) { + CAPLog.print("⚡️ ERROR: Unable to find application directory at: \"\(descriptor.appLocation.absoluteString)\"!") + } + if descriptor.instanceType == .fixed { + if descriptor.warnings.contains(.missingFile) { + CAPLog.print("Unable to find capacitor.config.json, make sure it exists and run npx cap copy.") + } + if descriptor.warnings.contains(.invalidFile) { + CAPLog.print("Unable to parse capacitor.config.json. Make sure it's valid JSON.") + } + if descriptor.warnings.contains(.missingCordovaFile) { + CAPLog.print("Unable to find config.xml, make sure it exists and run npx cap copy.") + } + if descriptor.warnings.contains(.invalidCordovaFile) { + CAPLog.print("Unable to parse config.xml. Make sure it's valid XML.") + } + } + } + + private func printLoadError() { + let fullStartPath = bridge?.config.appStartFileURL.path ?? "" + + CAPLog.print("⚡️ ERROR: Unable to load \(fullStartPath)") + CAPLog.print("⚡️ This file is the root of your web app and must exist before") + CAPLog.print("⚡️ Capacitor can run. Ensure you've run capacitor copy at least") + CAPLog.print("⚡️ or, if embedding, that this directory exists as a resource directory.") + } + + private func fatalLoadError() -> Never { + printLoadError() + exit(1) + } +} + +extension CAPBridgeViewController: CAPBridgeDelegate { + internal var bridgedWebView: WKWebView? { + return webView + } + + internal var bridgedViewController: UIViewController? { + return self + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedJSTypes.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedJSTypes.h new file mode 100644 index 0000000..516c864 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedJSTypes.h @@ -0,0 +1,18 @@ +// Convenience methods for bridging to/from JavaScript types. Deliberately hidden from +// Swift by omission (to avoid collisions with Swift protocols), use +// `#import ` if working in Objective-C. + +#import +#import + +@protocol BridgedJSValueContainerImplementation +@required +- (NSString * _Nullable)getString:(NSString * _Nonnull)key defaultValue:(NSString * _Nullable)defaultValue; +- (NSDate * _Nullable)getDate:(NSString * _Nonnull)key defaultValue:(NSDate * _Nullable)defaultValue; +- (NSDictionary * _Nullable)getObject:(NSString * _Nonnull)key defaultValue:(NSDictionary * _Nullable)defaultValue; +- (NSNumber * _Nullable)getNumber:(NSString * _Nonnull)key defaultValue:(NSNumber * _Nullable)defaultValue; +- (BOOL)getBool:(NSString * _Nonnull)key defaultValue:(BOOL)defaultValue; +@end + +@interface CAPPluginCall (BridgedJSProtocol) +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedJSTypes.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedJSTypes.m new file mode 100644 index 0000000..fb6da45 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedJSTypes.m @@ -0,0 +1,43 @@ +#import +#import "CAPBridgedJSTypes.h" + +@implementation CAPPluginCall (BridgedJSProtocol) +- (NSString * _Nullable)getString:(NSString * _Nonnull)key defaultValue:(NSString * _Nullable)defaultValue { + id value = [[self dictionaryRepresentation] objectForKey:key]; + if (value != nil && [value isKindOfClass:[NSString class]]) { + return value; + } + return defaultValue; +} + +- (NSDate * _Nullable)getDate:(NSString * _Nonnull)key defaultValue:(NSDate * _Nullable)defaultValue { + id value = [[self dictionaryRepresentation] objectForKey:key]; + if (value != nil && [value isKindOfClass:[NSDate class]]) { + return value; + } + else if (value != nil && [value isKindOfClass:[NSString class]]) { + return [[[self class] jsDateFormatter] dateFromString:value]; + } + return defaultValue; +} + +- (NSDictionary * _Nullable)getObject:(NSString * _Nonnull)key defaultValue:(NSDictionary * _Nullable)defaultValue { + id value = [[self dictionaryRepresentation] objectForKey:key]; + if (value != nil && [value isKindOfClass:[NSDictionary class]]) { + return value; + } + return defaultValue; +} + +- (NSNumber * _Nullable)getNumber:(NSString * _Nonnull)key defaultValue:(NSNumber * _Nullable)defaultValue { + id value = [[self dictionaryRepresentation] objectForKey:key]; + if (value != nil && [value isKindOfClass:[NSNumber class]]) { + return value; + } + return defaultValue; +} + +- (BOOL)getBool:(NSString * _Nonnull)key defaultValue:(BOOL)defaultValue { + return [[self getNumber:key defaultValue:[NSNumber numberWithBool:defaultValue]] boolValue]; +} +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedPlugin+getMethod.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedPlugin+getMethod.swift new file mode 100644 index 0000000..7c470e7 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedPlugin+getMethod.swift @@ -0,0 +1,13 @@ +// +// CAPBridgedPlugin+getMethod.swift +// Capacitor +// +// Created by Steven Sherry on 3/1/23. +// Copyright © 2023 Drifty Co. All rights reserved. +// + +extension CAPBridgedPlugin { + func getMethod(named name: String) -> CAPPluginMethod? { + pluginMethods.first { $0.name == name } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedPlugin.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedPlugin.h new file mode 100644 index 0000000..5a9a3b4 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPBridgedPlugin.h @@ -0,0 +1,43 @@ +#import "CAPPluginMethod.h" + +#if defined(__cplusplus) +#define CAP_EXTERN extern "C" __attribute__((visibility("default"))) +#else +#define CAP_EXTERN extern __attribute__((visibility("default"))) +#endif + +#define CAPPluginReturnNone @"none" +#define CAPPluginReturnCallback @"callback" +#define CAPPluginReturnPromise @"promise" +#define CAPPluginReturnWatch @"watch" +#define CAPPluginReturnSync @"sync" // not used + +@class CAPPluginCall; +@class CAPPlugin; + +@protocol CAPBridgedPlugin +@property (nonnull, readonly) NSString *identifier; +@property (nonnull, readonly) NSString *jsName; +@property (nonnull, readonly) NSArray *pluginMethods; +@end + +#define CAP_PLUGIN_CONFIG(plugin_id, js_name) \ +- (NSString *)identifier { return @#plugin_id; } \ +- (NSString *)jsName { return @js_name; } +#define CAP_PLUGIN_METHOD(method_name, method_return_type) \ +[methods addObject:[[CAPPluginMethod alloc] initWithName:@#method_name returnType:method_return_type]] + +#define CAP_PLUGIN(objc_name, js_name, methods_body) \ +@interface objc_name : NSObject \ +@end \ +@interface objc_name (CAPPluginCategory) \ +@end \ +@implementation objc_name (CAPPluginCategory) \ +- (NSArray *)pluginMethods { \ + NSMutableArray *methods = [NSMutableArray new]; \ + methods_body \ + return methods; \ +} \ +CAP_PLUGIN_CONFIG(objc_name, js_name) \ +@end + diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPFile.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPFile.swift new file mode 100644 index 0000000..f3ab8a3 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPFile.swift @@ -0,0 +1,14 @@ +/** + * CAPFileManager helps map file schemes to physical files, whether they are on + * disk, in a bundle, or in another location. + */ +@objc public class CAPFileManager: NSObject { + @available(*, deprecated, message: "Use portablePath(fromLocalURL:) on the Bridge") + public static func getPortablePath(host: String, uri: URL?) -> String? { + if let uri = uri { + let uriWithoutFile = uri.absoluteString.replacingOccurrences(of: "file://", with: "") + return host + CapacitorBridge.fileStartIdentifier + uriWithoutFile + } + return nil + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.h new file mode 100644 index 0000000..ac6b2bc --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.h @@ -0,0 +1,36 @@ +#ifndef CAPInstanceConfiguration_h +#define CAPInstanceConfiguration_h + +@import UIKit; + +@class CAPInstanceDescriptor; + +NS_SWIFT_NAME(InstanceConfiguration) +@interface CAPInstanceConfiguration: NSObject +@property (nonatomic, readonly, nullable) NSString *appendedUserAgentString; +@property (nonatomic, readonly, nullable) NSString *overridenUserAgentString; +@property (nonatomic, readonly, nullable) UIColor *backgroundColor; +@property (nonatomic, readonly, nonnull) NSArray *allowedNavigationHostnames; +@property (nonatomic, readonly, nonnull) NSURL *localURL; +@property (nonatomic, readonly, nonnull) NSURL *serverURL; +@property (nonatomic, readonly, nullable) NSString *errorPath; +@property (nonatomic, readonly, nonnull) NSDictionary *pluginConfigurations; +@property (nonatomic, readonly) BOOL loggingEnabled; +@property (nonatomic, readonly) BOOL scrollingEnabled; +@property (nonatomic, readonly) BOOL allowLinkPreviews; +@property (nonatomic, readonly) BOOL handleApplicationNotifications; +@property (nonatomic, readonly) BOOL isWebDebuggable; +@property (nonatomic, readonly) BOOL cordovaDeployDisabled; +@property (nonatomic, readonly) UIScrollViewContentInsetAdjustmentBehavior contentInsetAdjustmentBehavior; +@property (nonatomic, readonly, nonnull) NSURL *appLocation; +@property (nonatomic, readonly, nullable) NSString *appStartPath; +@property (nonatomic, readonly) BOOL limitsNavigationsToAppBoundDomains; +@property (nonatomic, readonly, nullable) NSString *preferredContentMode; + +@property (nonatomic, readonly, nonnull) NSDictionary *legacyConfig DEPRECATED_MSG_ATTRIBUTE("Use direct properties instead"); + +- (instancetype _Nonnull)initWithDescriptor:(CAPInstanceDescriptor* _Nonnull)descriptor isDebug:(BOOL)debug NS_SWIFT_NAME(init(with:isDebug:)); +- (instancetype _Nonnull)updatingAppLocation:(NSURL* _Nonnull)location NS_SWIFT_NAME(updatingAppLocation(_:)); +@end + +#endif /* CAPInstanceConfiguration_h */ diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.m new file mode 100644 index 0000000..e5487aa --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.m @@ -0,0 +1,89 @@ +#import "CAPInstanceConfiguration.h" +#import + +@interface CAPInstanceConfiguration (Internal) +- (instancetype)initWithConfiguration:(CAPInstanceConfiguration*)configuration andLocation:(NSURL*)location; +@end + + +@implementation CAPInstanceConfiguration + +- (instancetype)initWithDescriptor:(CAPInstanceDescriptor *)descriptor isDebug:(BOOL)debug { + if (self = [super init]) { + // first, give the descriptor a chance to make itself internally consistent + [descriptor normalize]; + // now copy the simple properties + _appendedUserAgentString = descriptor.appendedUserAgentString; + _overridenUserAgentString = descriptor.overridenUserAgentString; + _backgroundColor = descriptor.backgroundColor; + _allowedNavigationHostnames = descriptor.allowedNavigationHostnames; + switch (descriptor.loggingBehavior) { + case CAPInstanceLoggingBehaviorProduction: + _loggingEnabled = true; + break; + case CAPInstanceLoggingBehaviorDebug: + _loggingEnabled = debug; + break; + default: + _loggingEnabled = false; + break; + } + _scrollingEnabled = descriptor.scrollingEnabled; + _allowLinkPreviews = descriptor.allowLinkPreviews; + _handleApplicationNotifications = descriptor.handleApplicationNotifications; + _contentInsetAdjustmentBehavior = descriptor.contentInsetAdjustmentBehavior; + _appLocation = descriptor.appLocation; + _appStartPath = descriptor.appStartPath; + _limitsNavigationsToAppBoundDomains = descriptor.limitsNavigationsToAppBoundDomains; + _preferredContentMode = descriptor.preferredContentMode; + _pluginConfigurations = descriptor.pluginConfigurations; + _isWebDebuggable = descriptor.isWebDebuggable; + _legacyConfig = descriptor.legacyConfig; + // construct the necessary URLs + _localURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@://%@", descriptor.urlScheme, descriptor.urlHostname]]; + if (descriptor.serverURL != nil) { + _serverURL = [[NSURL alloc] initWithString:(descriptor.serverURL)]; + } + else { + _serverURL = _localURL; + } + _errorPath = descriptor.errorPath; + // extract the one value we care about from the cordova configuration + _cordovaDeployDisabled = [descriptor cordovaDeployDisabled]; + } + return self; +} + +- (instancetype)initWithConfiguration:(CAPInstanceConfiguration*)configuration andLocation:(NSURL*)location { + if (self = [super init]) { + _appendedUserAgentString = [[configuration appendedUserAgentString] copy]; + _overridenUserAgentString = [[configuration overridenUserAgentString] copy]; + _backgroundColor = configuration.backgroundColor; + _allowedNavigationHostnames = [[configuration allowedNavigationHostnames] copy]; + _localURL = [[configuration localURL] copy]; + _serverURL = [[configuration serverURL] copy]; + _errorPath = [[configuration errorPath] copy]; + _pluginConfigurations = [[configuration pluginConfigurations] copy]; + _loggingEnabled = configuration.loggingEnabled; + _scrollingEnabled = configuration.scrollingEnabled; + _allowLinkPreviews = configuration.allowLinkPreviews; + _handleApplicationNotifications = configuration.handleApplicationNotifications; + _isWebDebuggable = configuration.isWebDebuggable; + _cordovaDeployDisabled = configuration.cordovaDeployDisabled; + _contentInsetAdjustmentBehavior = configuration.contentInsetAdjustmentBehavior; + // we don't care about internal usage of deprecated APIs and the framework should build cleanly +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + _legacyConfig = [[configuration legacyConfig] copy]; +#pragma clang diagnostic pop + _appStartPath = configuration.appStartPath; + _appLocation = [location copy]; + } + return self; +} + +- (instancetype)updatingAppLocation:(NSURL*)location { + return [[CAPInstanceConfiguration alloc] initWithConfiguration:self andLocation:location]; +} + +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.swift new file mode 100644 index 0000000..2ae59da --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceConfiguration.swift @@ -0,0 +1,78 @@ +import Foundation + +extension InstanceConfiguration { + @objc var appStartFileURL: URL { + if let path = appStartPath { + return appLocation.appendingPathComponent(path) + } + return appLocation + } + + @objc var appStartServerURL: URL { + if let path = appStartPath { + return serverURL.appendingPathComponent(path) + } + return serverURL + } + + @objc var errorPathURL: URL? { + guard let errorPath = errorPath else { + return nil + } + + return localURL.appendingPathComponent(errorPath) + } + + @available(*, deprecated, message: "Use getPluginConfig") + @objc public func getPluginConfigValue(_ pluginId: String, _ configKey: String) -> Any? { + return (pluginConfigurations as? JSObject)?[keyPath: KeyPath("\(pluginId).\(configKey)")] + } + + @objc public func getPluginConfig(_ pluginId: String) -> PluginConfig { + if let cfg = (pluginConfigurations as? JSObject)?[keyPath: KeyPath("\(pluginId)")] as? JSObject { + return PluginConfig(config: cfg) + } + return PluginConfig(config: JSObject()) + } + + @objc public func shouldAllowNavigation(to host: String) -> Bool { + for hostname in allowedNavigationHostnames { + if doesHost(host, match: hostname) { + return true + } + } + return false + } + + @available(*, deprecated, message: "Use direct property accessors") + @objc public func getValue(_ key: String) -> Any? { + return (legacyConfig as? JSObject)?[keyPath: KeyPath(key)] + } + + @available(*, deprecated, message: "Use direct property accessors") + @objc public func getString(_ key: String) -> String? { + return (legacyConfig as? JSObject)?[keyPath: KeyPath(key)] as? String + } + + // MARK: - Private + + private func doesHost(_ host: String, match pattern: String) -> Bool { + // bail early in the simple case + if pattern == "*" { + return true + } + // break apart the pieces + var hostComponents = host.lowercased().split(separator: ".") + var patternComponents = pattern.lowercased().split(separator: ".") + guard hostComponents.count == patternComponents.count else { + return false + } + // remove any wildcard segments + for wildcard in patternComponents.enumerated().reversed().filter({ $0.element == "*" }) { + hostComponents.remove(at: wildcard.offset) + patternComponents.remove(at: wildcard.offset) + } + // match with what's left + return hostComponents == patternComponents + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.h new file mode 100644 index 0000000..2a1635e --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.h @@ -0,0 +1,156 @@ +#ifndef CAPInstanceDescriptor_h +#define CAPInstanceDescriptor_h + +@import UIKit; +@import Cordova; + +typedef NS_ENUM(NSInteger, CAPInstanceType) { + CAPInstanceTypeFixed NS_SWIFT_NAME(fixed), + CAPInstanceTypeVariable NS_SWIFT_NAME(variable) +} NS_SWIFT_NAME(InstanceType); + +typedef NS_OPTIONS(NSUInteger, CAPInstanceWarning) { + CAPInstanceWarningMissingAppDir NS_SWIFT_NAME(missingAppDir) = 1 << 0, + CAPInstanceWarningMissingFile NS_SWIFT_NAME(missingFile) = 1 << 1, + CAPInstanceWarningInvalidFile NS_SWIFT_NAME(invalidFile) = 1 << 2, + CAPInstanceWarningMissingCordovaFile NS_SWIFT_NAME(missingCordovaFile) = 1 << 3, + CAPInstanceWarningInvalidCordovaFile NS_SWIFT_NAME(invalidCordovaFile) = 1 << 4 +} NS_SWIFT_NAME(InstanceWarning); + +typedef NS_OPTIONS(NSUInteger, CAPInstanceLoggingBehavior) { + CAPInstanceLoggingBehaviorNone NS_SWIFT_NAME(none) = 1 << 0, + CAPInstanceLoggingBehaviorDebug NS_SWIFT_NAME(debug) = 1 << 1, + CAPInstanceLoggingBehaviorProduction NS_SWIFT_NAME(production) = 1 << 2, +} NS_SWIFT_NAME(InstanceLoggingBehavior); + +extern NSString * _Nonnull const CAPInstanceDescriptorDefaultScheme NS_SWIFT_UNAVAILABLE("Use InstanceDescriptorDefaults"); +extern NSString * _Nonnull const CAPInstanceDescriptorDefaultHostname NS_SWIFT_UNAVAILABLE("Use InstanceDescriptorDefaults"); + +NS_SWIFT_NAME(InstanceDescriptor) +@interface CAPInstanceDescriptor : NSObject +/** + @brief A value to append to the @c User-Agent string. Ignored if @c overridenUserAgentString is set. + @discussion Set by @c appendUserAgent in the configuration file. + */ +@property (nonatomic, copy, nullable) NSString *appendedUserAgentString; +/** + @brief A value that will completely replace the @c User-Agent string. Overrides @c appendedUserAgentString. + @discussion Set by @c overrideUserAgent in the configuration file. + */ +@property (nonatomic, copy, nullable) NSString *overridenUserAgentString; +/** + @brief The background color to set on the web view where content is not visible. + @discussion Set by @c backgroundColor in the configuration file. + */ +@property (nonatomic, retain, nullable) UIColor *backgroundColor; +/** + @brief Hostnames to which the web view is allowed to navigate without opening an external browser. + @discussion Set by @c allowNavigation in the configuration file. + */ +@property (nonatomic, copy, nonnull) NSArray *allowedNavigationHostnames; +/** + @brief The scheme that will be used for the server URL. + @discussion Defaults to @c capacitor. Set by @c server.iosScheme in the configuration file. + */ +@property (nonatomic, copy, nullable) NSString *urlScheme; +/** + @brief The path to a local html page to display in case of errors. + @discussion Defaults to nil. + */ +@property (nonatomic, copy, nullable) NSString *errorPath; +/** + @brief The hostname that will be used for the server URL. + @discussion Defaults to @c localhost. Set by @c server.hostname in the configuration file. + */ +@property (nonatomic, copy, nullable) NSString *urlHostname; +/** + @brief The fully formed URL that will be used as the server URL. + @discussion Defaults to nil, in which case the server URL will be constructed from @c urlScheme and @c urlHostname. If set, it will override the other properties. Set by @c server.url in the configuration file. + */ +@property (nonatomic, copy, nullable) NSString *serverURL; +/** + @brief The JSON dictionary that contains the plugin-specific configuration information. + @discussion Set by @c plugins in the configuration file. + */ +@property (nonatomic, retain, nonnull) NSDictionary *pluginConfigurations; +/** + @brief The build configurations under which logging should be enabled. + @discussion Defaults to @c debug. Set by @c loggingBehavior in the configuration file. + */ +@property (nonatomic, assign) CAPInstanceLoggingBehavior loggingBehavior; +/** + @brief Whether or not the web view can scroll. + @discussion Set by @c ios.scrollEnabled in the configuration file. Corresponds to @c isScrollEnabled on WKWebView. + */ +@property (nonatomic, assign) BOOL scrollingEnabled; +/** + @brief Whether or not the web view will preview links. + @discussion Set by @c ios.allowsLinkPreview in the configuration file. Corresponds to @c allowsLinkPreview on WKWebView. + */ +@property (nonatomic, assign) BOOL allowLinkPreviews; +/** + @brief Whether or not the Capacitor runtime will set itself as the @c UNUserNotificationCenter delegate. + @discussion Defaults to @c true. Required to be @c true for notification plugins to work correctly. Set to @c false if your application will handle notifications independently. + */ +@property (nonatomic, assign) BOOL handleApplicationNotifications; +/** + @brief Enables web debugging by setting isInspectable of @c WKWebView to @c true on iOS 16.4 and greater + @discussion Defaults to true in debug mode and false in production + */ +@property (nonatomic, assign) BOOL isWebDebuggable; +/** + @brief How the web view will inset its content + @discussion Set by @c ios.contentInset in the configuration file. Corresponds to @c contentInsetAdjustmentBehavior on WKWebView. + */ +@property (nonatomic, assign) UIScrollViewContentInsetAdjustmentBehavior contentInsetAdjustmentBehavior; +/** + @brief The base file URL from which Capacitor will load resources + @discussion Defaults to @c public/ located at the root of the application bundle. + */ +@property (nonatomic, copy, nonnull) NSURL *appLocation; +/** + @brief The path (relative to @c appLocation) which Capacitor will use for the inital URL at launch. + @discussion Defaults to nil, in which case Capacitor will attempt to load @c index.html. + */ +@property (nonatomic, copy, nullable) NSString *appStartPath; +/** + @brief Whether or not the Capacitor WebView will limit the navigation to @c WKAppBoundDomains listed in the Info.plist. + @discussion Defaults to @c false. Set by @c ios.limitsNavigationsToAppBoundDomains in the configuration file. Required to be @c true for plugins to work if the app includes @c WKAppBoundDomains in the Info.plist. + */ +@property (nonatomic, assign) BOOL limitsNavigationsToAppBoundDomains; +/** + @brief The content mode for the web view to use when it loads and renders web content. + @discussion Defaults to @c recommended. Set by @c ios.preferredContentMode in the configuration file. + */ +@property (nonatomic, copy, nullable) NSString *preferredContentMode; +/** + @brief The parser used to load the cofiguration for Cordova plugins. + */ +@property (nonatomic, copy, nonnull) CDVConfigParser *cordovaConfiguration; +/** + @brief Warnings generated during initialization. + */ +@property (nonatomic, assign) CAPInstanceWarning warnings; +/** + @brief The type of instance. + */ +@property (nonatomic, readonly) CAPInstanceType instanceType; +/** + @brief The JSON dictionary representing the contents of the configuration file. + @warning Deprecated. Do not use. + */ +@property (nonatomic, retain, nonnull) NSDictionary *legacyConfig; +/** + @brief Initialize the descriptor with the default environment. This assumes that the application was built with the help of the Capacitor CLI and that that the web app is located inside the application bundle at @c public/. + */ +- (instancetype _Nonnull)initAsDefault NS_SWIFT_NAME(init()); +/** + @brief Initialize the descriptor for use in other contexts. The app location is the one required parameter. + @param appURL The location of the folder containing the web app. + @param configURL The location of the Capacitor configuration file. + @param cordovaURL The location of the Cordova configuration file. + */ +- (instancetype _Nonnull)initAtLocation:(NSURL* _Nonnull)appURL configuration:(NSURL* _Nullable)configURL cordovaConfiguration:(NSURL* _Nullable)cordovaURL NS_SWIFT_NAME(init(at:configuration:cordovaConfiguration:)); +@end + +#endif /* CAPInstanceDescriptor_h */ diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.m new file mode 100644 index 0000000..b530691 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.m @@ -0,0 +1,54 @@ +#import "CAPInstanceDescriptor.h" +#import + +// Swift extensions marked as @objc and internal are available to the Obj-C runtime but are not available at compile time. +// so we need this declaration to avoid compiler complaints +@interface CAPInstanceDescriptor (InternalSwiftExtension) +- (void)_parseConfigurationAt:(NSURL *)configURL cordovaConfiguration:(NSURL *)cordovaURL; +@end + +NSString* const CAPInstanceDescriptorDefaultScheme = @"capacitor"; +NSString* const CAPInstanceDescriptorDefaultHostname = @"localhost"; + +@implementation CAPInstanceDescriptor +- (instancetype)initAsDefault { + if (self = [super init]) { + _instanceType = CAPInstanceTypeFixed; + [self _setDefaultsWithAppLocation:[[NSBundle mainBundle] URLForResource:@"public" withExtension:nil]]; + [self _parseConfigurationAt:[[NSBundle mainBundle] URLForResource:@"capacitor.config" withExtension:@"json"] cordovaConfiguration:[[NSBundle mainBundle] URLForResource:@"config" withExtension:@"xml"]]; + } + return self; +} + +- (instancetype)initAtLocation:(NSURL*)appURL configuration:(NSURL*)configURL cordovaConfiguration:(NSURL*)cordovaURL { + if (self = [super init]) { + _instanceType = CAPInstanceTypeVariable; + [self _setDefaultsWithAppLocation:appURL]; + [self _parseConfigurationAt:configURL cordovaConfiguration:cordovaURL]; + } + return self; +} + +- (void)_setDefaultsWithAppLocation:(NSURL*)location { + _allowedNavigationHostnames = @[]; + _urlScheme = CAPInstanceDescriptorDefaultScheme; + _urlHostname = CAPInstanceDescriptorDefaultHostname; + _pluginConfigurations = @{}; + _legacyConfig = @{}; + _loggingBehavior = CAPInstanceLoggingBehaviorDebug; + _scrollingEnabled = YES; + _allowLinkPreviews = YES; + _handleApplicationNotifications = YES; + _isWebDebuggable = NO; + _contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; + _appLocation = location; + _limitsNavigationsToAppBoundDomains = FALSE; + _cordovaConfiguration = [[CDVConfigParser alloc] init]; + _warnings = 0; + if (location == nil) { + _warnings |= CAPInstanceWarningMissingAppDir; + // location is nil so assume it was supposed to be the default + _appLocation = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent:@"public"]; + } +} +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.swift new file mode 100644 index 0000000..576eb1a --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstanceDescriptor.swift @@ -0,0 +1,184 @@ +import Foundation + +public enum InstanceDescriptorDefaults { + static let scheme = "capacitor" + static let hostname = "localhost" +} + +private extension InstanceLoggingBehavior { + static func behavior(from: String) -> InstanceLoggingBehavior? { + switch from.lowercased() { + case "none": + return InstanceLoggingBehavior.none + case "debug": + return InstanceLoggingBehavior.debug + case "production": + return InstanceLoggingBehavior.production + default: + return nil + } + } +} + +/** + The purpose of this function is to hide the messy details of parsing the configuration(s) so + the complexity is worth it. And the name starts with an underscore to match the convention of + private APIs in Obj-C (from which it is called). + */ +internal extension InstanceDescriptor { + // swiftlint:disable cyclomatic_complexity + // swiftlint:disable function_body_length + // swiftlint:disable:next identifier_name + @objc func _parseConfiguration(at capacitorURL: URL?, cordovaConfiguration cordovaURL: URL?) { + // sanity check that the app directory is valid + var isDirectory: ObjCBool = ObjCBool(false) + if warnings.contains(.missingAppDir) == false, + (FileManager.default.fileExists(atPath: appLocation.path, isDirectory: &isDirectory) == false || isDirectory.boolValue == false) { + warnings.update(with: .missingAppDir) + } + + // parse the capacitor configuration + var config: JSObject? + if let capacitorURL = capacitorURL, + FileManager.default.fileExists(atPath: capacitorURL.path, isDirectory: &isDirectory), + isDirectory.boolValue == false { + do { + let contents = try Data(contentsOf: capacitorURL) + config = JSTypes.coerceDictionaryToJSObject(try JSONSerialization.jsonObject(with: contents) as? [String: Any]) + } catch { + warnings.update(with: .invalidFile) + } + } else { + warnings.update(with: .missingFile) + } + + // parse the cordova configuration + var configParser: XMLParser? + if let cordovaURL = cordovaURL, + FileManager.default.fileExists(atPath: cordovaURL.path, isDirectory: &isDirectory), + isDirectory.boolValue == false { + configParser = XMLParser(contentsOf: cordovaURL) + } else { + warnings.update(with: .missingCordovaFile) + // we don't want to break up string literals + // swiftlint:disable:next line_length + if let cordovaXML = "".data(using: .utf8) { + configParser = XMLParser(data: cordovaXML) + } + } + configParser?.delegate = cordovaConfiguration + configParser?.parse() + + // extract our configuration values + if let config = config { + // to be removed + legacyConfig = config + + if let agentString = (config[keyPath: "ios.appendUserAgent"] as? String) ?? (config[keyPath: "appendUserAgent"] as? String) { + appendedUserAgentString = agentString + } + if let agentString = (config[keyPath: "ios.overrideUserAgent"] as? String) ?? (config[keyPath: "overrideUserAgent"] as? String) { + overridenUserAgentString = agentString + } + if let colorString = (config[keyPath: "ios.backgroundColor"] as? String) ?? (config[keyPath: "backgroundColor"] as? String), + let color = UIColor.capacitor.color(fromHex: colorString) { + backgroundColor = color + } + if let allowNav = config[keyPath: "server.allowNavigation"] as? [String] { + allowedNavigationHostnames = allowNav + } + if let scheme = (config[keyPath: "server.iosScheme"] as? String)?.lowercased() { + urlScheme = scheme + } + if let host = config[keyPath: "server.hostname"] as? String { + urlHostname = host + } + if let urlString = config[keyPath: "server.url"] as? String { + serverURL = urlString + } + if let errorPathString = (config[keyPath: "server.errorPath"] as? String) { + errorPath = errorPathString + } + if let insetBehavior = config[keyPath: "ios.contentInset"] as? String { + let availableInsets: [String: UIScrollView.ContentInsetAdjustmentBehavior] = ["automatic": .automatic, + "scrollableAxes": .scrollableAxes, + "never": .never, + "always": .always] + if let option = availableInsets[insetBehavior] { + contentInsetAdjustmentBehavior = option + } + } + if let allowPreviews = config[keyPath: "ios.allowsLinkPreview"] as? Bool { + allowLinkPreviews = allowPreviews + } + if let scrollEnabled = config[keyPath: "ios.scrollEnabled"] as? Bool { + scrollingEnabled = scrollEnabled + } + if let pluginConfig = config[keyPath: "plugins"] as? JSObject { + pluginConfigurations = pluginConfig + } + if let value = (config[keyPath: "ios.loggingBehavior"] as? String) ?? (config[keyPath: "loggingBehavior"] as? String) { + if let behavior = InstanceLoggingBehavior.behavior(from: value) { + loggingBehavior = behavior + } + } + if let limitsNavigations = config[keyPath: "ios.limitsNavigationsToAppBoundDomains"] as? Bool { + limitsNavigationsToAppBoundDomains = limitsNavigations + } + if let preferredMode = (config[keyPath: "ios.preferredContentMode"] as? String) { + preferredContentMode = preferredMode + } + if let handleNotifications = config[keyPath: "ios.handleApplicationNotifications"] as? Bool { + handleApplicationNotifications = handleNotifications + } + if let webContentsDebuggingEnabled = config[keyPath: "ios.webContentsDebuggingEnabled"] as? Bool { + isWebDebuggable = webContentsDebuggingEnabled + } else { + #if DEBUG + isWebDebuggable = true + #endif + } + } + } + // swiftlint:enable cyclomatic_complexity + // swiftlint:enable function_body_length +} + +extension InstanceDescriptor { + @objc public var cordovaDeployDisabled: Bool { + return (cordovaConfiguration.settings?["DisableDeploy".lowercased()] as? NSString)?.boolValue ?? false + } + + @objc public func normalize() { + // first, make sure the scheme is valid + var schemeValid = false + if let scheme = urlScheme, WKWebView.handlesURLScheme(scheme) == false, + scheme.range(of: "^[a-z][a-z0-9.+-]*$", options: [.regularExpression, .caseInsensitive], range: nil, locale: nil) != nil { + schemeValid = true + } + if !schemeValid { + // reset to the default + urlScheme = InstanceDescriptorDefaults.scheme + } + // make sure we have a hostname + if urlHostname == nil { + urlHostname = InstanceDescriptorDefaults.hostname + } + // now validate the server.url + var urlValid = false + if let server = serverURL, URL(string: server) != nil { + urlValid = true + } + if !urlValid { + serverURL = nil + } + // reset the path if it's not valid + if let path = appStartPath?.trimmingCharacters(in: .whitespacesAndNewlines), path.isEmpty { + appStartPath = nil + } + // if the plugin configuration was programmatically modified, the necessary type information may have been lost. + // so perform a coercion here to make sure that casting will work as expected + pluginConfigurations = JSTypes.coerceDictionaryToJSObject(pluginConfigurations) ?? [:] + legacyConfig = JSTypes.coerceDictionaryToJSObject(legacyConfig) ?? [:] + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstancePlugin.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstancePlugin.swift new file mode 100644 index 0000000..0a73e43 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPInstancePlugin.swift @@ -0,0 +1,10 @@ +// +// CAPInstancePlugin.swift +// Capacitor +// +// Created by Steven Sherry on 11/21/22. +// Copyright © 2022 Drifty Co. All rights reserved. +// + +/// A CAPPlugin subclass meant to be explicitly initialized by the caller and not the bridge. +@objc open class CAPInstancePlugin: CAPPlugin {} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPLog.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPLog.swift new file mode 100644 index 0000000..fd707e5 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPLog.swift @@ -0,0 +1,11 @@ +public class CAPLog { + public static var enableLogging: Bool = true + + public static func print(_ items: Any..., separator: String = " ", terminator: String = "\n") { + if enableLogging { + for (itemIndex, item) in items.enumerated() { + Swift.print("\(item)".prefix(4068), terminator: itemIndex == items.count - 1 ? terminator : separator) + } + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPNotifications.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPNotifications.swift new file mode 100644 index 0000000..a79cbce --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPNotifications.swift @@ -0,0 +1,65 @@ +/** + Notificaton types for NotificationCenter and NSNotificationCenter + + We want to include `capacitor` in the name(s) to uniquely identify these even though it can make the names long + and the deprecated notifications are only here for backwards compatibility. + */ +// swiftlint:disable identifier_name +extension Notification.Name { + public static let capacitorOpenURL = Notification.Name(rawValue: "CapacitorOpenURLNotification") + public static let capacitorOpenUniversalLink = Notification.Name(rawValue: "CapacitorOpenUniversalLinkNotification") + public static let capacitorContinueActivity = Notification.Name(rawValue: "CapacitorContinueActivityNotification") + public static let capacitorDidRegisterForRemoteNotifications = + Notification.Name(rawValue: "CapacitorDidRegisterForRemoteNotificationsNotification") + public static let capacitorDidFailToRegisterForRemoteNotifications = + Notification.Name(rawValue: "CapacitorDidFailToRegisterForRemoteNotificationsNotification") + public static let capacitorDecidePolicyForNavigationAction = + Notification.Name(rawValue: "CapacitorDecidePolicyForNavigationActionNotification") + public static let capacitorStatusBarTapped = Notification.Name(rawValue: "CapacitorStatusBarTappedNotification") +} + +@objc extension NSNotification { + public static let capacitorOpenURL = Notification.Name.capacitorOpenURL + public static let capacitorOpenUniversalLink = Notification.Name.capacitorOpenUniversalLink + public static let capacitorContinueActivity = Notification.Name.capacitorContinueActivity + public static let capacitorDidRegisterForRemoteNotifications = Notification.Name.capacitorDidRegisterForRemoteNotifications + public static let capacitorDidFailToRegisterForRemoteNotifications = Notification.Name.capacitorDidFailToRegisterForRemoteNotifications + public static let capacitorDecidePolicyForNavigationAction = Notification.Name.capacitorDecidePolicyForNavigationAction + public static let capacitorStatusBarTapped = Notification.Name.capacitorStatusBarTapped +} + +/** + Deprecated, will be removed + */ +@objc public enum CAPNotifications: Int { + @available(*, deprecated, message: "renamed to 'Notification.Name.capacitorOpenURL'") + case URLOpen + @available(*, deprecated, message: "renamed to 'Notification.Name.capacitorOpenUniversalLink'") + case UniversalLinkOpen + @available(*, deprecated, message: "Notification.Name.capacitorContinueActivity'") + case ContinueActivity + @available(*, deprecated, message: "renamed to 'Notification.Name.capacitorDidRegisterForRemoteNotifications'") + case DidRegisterForRemoteNotificationsWithDeviceToken + @available(*, deprecated, message: "renamed to 'Notification.Name.capacitorDidFailToRegisterForRemoteNotifications'") + case DidFailToRegisterForRemoteNotificationsWithError + @available(*, deprecated, message: "renamed to 'Notification.Name.capacitorDecidePolicyForNavigationAction'") + case DecidePolicyForNavigationAction + + public func name() -> String { + switch self { + case .URLOpen: + return Notification.Name.capacitorOpenURL.rawValue + case .UniversalLinkOpen: + return Notification.Name.capacitorOpenUniversalLink.rawValue + case .ContinueActivity: + return Notification.Name.capacitorContinueActivity.rawValue + case .DidRegisterForRemoteNotificationsWithDeviceToken: + return Notification.Name.capacitorDidRegisterForRemoteNotifications.rawValue + case .DidFailToRegisterForRemoteNotificationsWithError: + return Notification.Name.capacitorDidFailToRegisterForRemoteNotifications.rawValue + case .DecidePolicyForNavigationAction: + return Notification.Name.capacitorDecidePolicyForNavigationAction.rawValue + } + } +} +// swiftlint:enable identifier_name diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin+LoadInstance.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin+LoadInstance.swift new file mode 100644 index 0000000..35e3746 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin+LoadInstance.swift @@ -0,0 +1,20 @@ +// +// CAPPlugin+LoadInstance.swift +// Capacitor +// +// Created by Steven Sherry on 11/9/22. +// Copyright © 2022 Drifty Co. All rights reserved. +// + +extension CAPBridgedPlugin where Self: CAPPlugin { + func load(on bridge: CAPBridgeProtocol) { + self.bridge = bridge + webView = bridge.webView + shouldStringifyDatesInCalls = true + retainedEventArguments = [:] + eventListeners = [:] + pluginId = identifier + pluginName = jsName + load() + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin.h new file mode 100644 index 0000000..11bb9bd --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin.h @@ -0,0 +1,55 @@ +#import +#import + +@protocol CAPBridgeProtocol; +@class CAPPluginCall; + +@class PluginConfig; + +@interface CAPPlugin : NSObject + +@property (nonatomic, weak, nullable) WKWebView *webView; +@property (nonatomic, weak, nullable) id bridge; +@property (nonatomic, strong, nonnull) NSString *pluginId; +@property (nonatomic, strong, nonnull) NSString *pluginName; +@property (nonatomic, strong, nullable) NSMutableDictionary*> *eventListeners; +@property (nonatomic, strong, nullable) NSMutableDictionary *> *retainedEventArguments; +@property (nonatomic, assign) BOOL shouldStringifyDatesInCalls; + +- (instancetype _Nonnull) initWithBridge:(id _Nonnull) bridge pluginId:(NSString* _Nonnull) pluginId pluginName:(NSString* _Nonnull) pluginName DEPRECATED_MSG_ATTRIBUTE("This initializer is deprecated and is not suggested for use. Any data set through this init method will be overridden when it is loaded on the bridge."); +- (void)addEventListener:(NSString* _Nonnull)eventName listener:(CAPPluginCall* _Nonnull)listener; +- (void)removeEventListener:(NSString* _Nonnull)eventName listener:(CAPPluginCall* _Nonnull)listener; +- (void)notifyListeners:(NSString* _Nonnull)eventName data:(NSDictionary* _Nullable)data; +- (void)notifyListeners:(NSString* _Nonnull)eventName data:(NSDictionary* _Nullable)data retainUntilConsumed:(BOOL)retain; +- (NSArray* _Nullable)getListeners:(NSString* _Nonnull)eventName; +- (BOOL)hasListeners:(NSString* _Nonnull)eventName; +- (void)addListener:(CAPPluginCall* _Nonnull)call; +- (void)removeListener:(CAPPluginCall* _Nonnull)call; +- (void)removeAllListeners:(CAPPluginCall* _Nonnull)call; +/** + * Default implementation of the capacitor 3.0 permission pattern + */ +- (void)checkPermissions:(CAPPluginCall* _Nonnull)call; +- (void)requestPermissions:(CAPPluginCall* _Nonnull)call; +/** + * Give the plugins a chance to take control when a URL is about to be loaded in the WebView. + * Returning true causes the WebView to abort loading the URL. + * Returning false causes the WebView to continue loading the URL. + * Returning nil will defer to the default Capacitor policy + */ +- (NSNumber* _Nullable)shouldOverrideLoad:(WKNavigationAction* _Nonnull)navigationAction; + +// Called after init if the plugin wants to do +// some loading so the plugin author doesn't +// need to override init() +-(void)load; +-(NSString* _Nonnull)getId; +-(BOOL)getBool:(CAPPluginCall* _Nonnull) call field:(NSString* _Nonnull)field defaultValue:(BOOL)defaultValue DEPRECATED_MSG_ATTRIBUTE("Use accessors on CAPPluginCall instead. See CAPBridgedJSTypes.h for Obj-C implementations."); +-(NSString* _Nullable)getString:(CAPPluginCall* _Nonnull)call field:(NSString* _Nonnull)field defaultValue:(NSString* _Nonnull)defaultValue DEPRECATED_MSG_ATTRIBUTE("Use accessors on CAPPluginCall instead. See CAPBridgedJSTypes.h for Obj-C implementations."); +-(id _Nullable)getConfigValue:(NSString* _Nonnull)key __deprecated_msg("use getConfig() and access config values using the methods available depending on the type."); +-(PluginConfig* _Nonnull)getConfig; +-(void)setCenteredPopover:(UIViewController* _Nonnull) vc; +-(void)setCenteredPopover:(UIViewController* _Nonnull) vc size:(CGSize) size; +-(BOOL)supportsPopover DEPRECATED_MSG_ATTRIBUTE("All iOS 13+ devices support popover"); + +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin.m new file mode 100644 index 0000000..4ce7e5b --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPlugin.m @@ -0,0 +1,175 @@ +#import "CAPPlugin.h" +#import "CAPBridgedJSTypes.h" +#import +#import + +@implementation CAPPlugin + +-(instancetype) initWithBridge:(id)bridge pluginId:(NSString *)pluginId pluginName:(NSString *)pluginName { + self.bridge = bridge; + self.webView = bridge.webView; + self.pluginId = pluginId; + self.pluginName = pluginName; + self.eventListeners = [[NSMutableDictionary alloc] init]; + self.retainedEventArguments = [[NSMutableDictionary alloc] init]; + self.shouldStringifyDatesInCalls = true; + return self; +} + +-(NSString *) getId { + return self.pluginName; +} + +- (BOOL)getBool:(CAPPluginCall *)call field:(NSString *)field defaultValue:(BOOL)defaultValue { + NSNumber* value = [call getNumber:field defaultValue:[NSNumber numberWithBool:defaultValue]]; + return [value boolValue]; +} + +- (NSString *) getString:(CAPPluginCall *)call field:(NSString *)field defaultValue:(NSString *)defaultValue { + return [call getString:field defaultValue:defaultValue]; +} + +-(id)getConfigValue:(NSString *)key __deprecated { + return [self.bridge.config getPluginConfigValue:self.pluginName :key]; +} + +-(PluginConfig*)getConfig { + return [self.bridge.config getPluginConfig:self.pluginName]; +} + +-(void)load {} + +- (void)addEventListener:(NSString *)eventName listener:(CAPPluginCall *)listener { + NSMutableArray *listenersForEvent = [self.eventListeners objectForKey:eventName]; + if(listenersForEvent == nil || [listenersForEvent count] == 0) { + listenersForEvent = [[NSMutableArray alloc] initWithObjects:listener, nil]; + [self.eventListeners setValue:listenersForEvent forKey:eventName]; + + [self sendRetainedArgumentsForEvent:eventName]; + } else { + [listenersForEvent addObject:listener]; + } +} + +- (void)sendRetainedArgumentsForEvent:(NSString *)eventName { + // copy retained args and null source to prevent potential race conditions + NSMutableArray *retained = [self.retainedEventArguments objectForKey:eventName]; + if (retained == nil) { + return; + } + + [self.retainedEventArguments removeObjectForKey:eventName]; + + for(id data in retained) { + [self notifyListeners:eventName data:data]; + } +} + +- (void)removeEventListener:(NSString *)eventName listener:(CAPPluginCall *)listener { + NSMutableArray *listenersForEvent = [self.eventListeners objectForKey:eventName]; + if(!listenersForEvent) { return; } + NSUInteger listenerIndex = [listenersForEvent indexOfObject:listener]; + if(listenerIndex == NSNotFound) { + return; + } + [listenersForEvent removeObjectAtIndex:listenerIndex]; +} + +- (void)notifyListeners:(NSString *)eventName data:(NSDictionary *)data { + [self notifyListeners:eventName data:data retainUntilConsumed:NO]; +} + +- (void)notifyListeners:(NSString *)eventName data:(NSDictionary *)data retainUntilConsumed:(BOOL)retain { + NSArray *listenersForEvent = [self.eventListeners objectForKey:eventName]; + if(listenersForEvent == nil || [listenersForEvent count] == 0) { + if (retain == YES) { + + if ([self.retainedEventArguments objectForKey:eventName] == nil) { + [self.retainedEventArguments setObject:[[NSMutableArray alloc] init] forKey:eventName]; + } + + [[self.retainedEventArguments objectForKey:eventName] addObject:data]; + } + return; + } + + for (int i=0; i < listenersForEvent.count; i++) { + CAPPluginCall *call = listenersForEvent[i]; + if (call != nil) { + CAPPluginCallResult *result = [[CAPPluginCallResult alloc] init:data]; + call.successHandler(result, call); + } + } +} + +- (void)addListener:(CAPPluginCall *)call { + NSString *eventName = [call.options objectForKey:@"eventName"]; + [call setKeepAlive:TRUE]; + [self addEventListener:eventName listener:call]; +} + +- (void)removeListener:(CAPPluginCall *)call { + NSString *eventName = [call.options objectForKey:@"eventName"]; + NSString *callbackId = [call.options objectForKey:@"callbackId"]; + CAPPluginCall *storedCall = [self.bridge savedCallWithID:callbackId]; + [self removeEventListener:eventName listener:storedCall]; + [self.bridge releaseCallWithID:callbackId]; +} + +- (void)removeAllListeners:(CAPPluginCall *)call { + [self.eventListeners removeAllObjects]; + [call resolve]; +} + +- (NSArray*)getListeners:(NSString *)eventName { + NSArray* listeners = [self.eventListeners objectForKey:eventName]; + return listeners; +} + +- (BOOL)hasListeners:(NSString *)eventName { + NSArray* listeners = [self.eventListeners objectForKey:eventName]; + + if (listeners == nil) { + return false; + } + return [listeners count] > 0; +} + +- (void)checkPermissions:(CAPPluginCall *)call { + [call resolve]; +} + +- (void)requestPermissions:(CAPPluginCall *)call { + [call resolve]; +} + +/** + * Configure popover sourceRect, sourceView and permittedArrowDirections to show it centered + */ +-(void)setCenteredPopover:(UIViewController *) vc { + if (self.bridge.viewController != nil) { + vc.popoverPresentationController.sourceRect = CGRectMake(self.bridge.viewController.view.center.x, self.bridge.viewController.view.center.y, 0, 0); + vc.popoverPresentationController.sourceView = self.bridge.viewController.view; + vc.popoverPresentationController.permittedArrowDirections = 0; + } +} + +-(void)setCenteredPopover:(UIViewController* _Nonnull) vc size:(CGSize) size { + if (self.bridge.viewController != nil) { + vc.popoverPresentationController.sourceRect = CGRectMake(self.bridge.viewController.view.center.x, self.bridge.viewController.view.center.y, 0, 0); + vc.preferredContentSize = size; + vc.popoverPresentationController.sourceView = self.bridge.viewController.view; + vc.popoverPresentationController.permittedArrowDirections = 0; + } +} + +-(BOOL)supportsPopover { + return YES; +} + +- (NSNumber*)shouldOverrideLoad:(WKNavigationAction*)navigationAction { + return nil; +} + +@end + diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.h new file mode 100644 index 0000000..46b3e67 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.h @@ -0,0 +1,22 @@ +#import + +@class CAPPluginCall; +@class CAPPluginCallResult; +@class CAPPluginCallError; + +typedef void(^CAPPluginCallSuccessHandler)(CAPPluginCallResult *result, CAPPluginCall* call); +typedef void(^CAPPluginCallErrorHandler)(CAPPluginCallError *error); + +@interface CAPPluginCall : NSObject + +@property (nonatomic, assign) BOOL isSaved DEPRECATED_MSG_ATTRIBUTE("Use 'keepAlive' instead."); +@property (nonatomic, assign) BOOL keepAlive; +@property (nonatomic, strong) NSString *callbackId; +@property (nonatomic, strong) NSDictionary *options; +@property (nonatomic, copy) CAPPluginCallSuccessHandler successHandler; +@property (nonatomic, copy) CAPPluginCallErrorHandler errorHandler; + +- (instancetype)initWithCallbackId:(NSString *)callbackId options:(NSDictionary *)options success:(CAPPluginCallSuccessHandler)success error:(CAPPluginCallErrorHandler)error; + +- (void)save DEPRECATED_MSG_ATTRIBUTE("Use the 'keepAlive' property instead."); +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.m new file mode 100644 index 0000000..543b11c --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.m @@ -0,0 +1,26 @@ +#import +#import "CAPPluginCall.h" + +@implementation CAPPluginCall + +- (instancetype)initWithCallbackId:(NSString *)callbackId options:(NSDictionary *)options success:(CAPPluginCallSuccessHandler) success error:(CAPPluginCallErrorHandler) error { + self.callbackId = callbackId; + self.options = options; + self.successHandler = success; + self.errorHandler = error; + return self; +} + +- (BOOL)isSaved { + return self.keepAlive; +} + +- (void)setIsSaved:(BOOL)saved { + self.keepAlive = saved; +} + +- (void)save { + self.keepAlive = true; +} + +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.swift new file mode 100644 index 0000000..7f9c8af --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginCall.swift @@ -0,0 +1,79 @@ +import Foundation + +@available(*, deprecated, renamed: "PluginCallResultData") +public typealias PluginCallErrorData = [String: Any] +@available(*, deprecated, renamed: "PluginCallResultData") +public typealias PluginResultData = [String: Any] + +/** + * Swift niceties for CAPPluginCall + */ + +extension CAPPluginCall: JSValueContainer { + public var jsObjectRepresentation: JSObject { + return options as? JSObject ?? [:] + } +} + +@objc extension CAPPluginCall: BridgedJSValueContainer { + public var dictionaryRepresentation: NSDictionary { + return options as NSDictionary + } + + public static var jsDateFormatter: ISO8601DateFormatter = { + return ISO8601DateFormatter() + }() +} + +@objc public extension CAPPluginCall { + @available(*, deprecated, message: "Presence of a key should not be considered significant. Use typed accessors to check the value instead.") + func hasOption(_ key: String) -> Bool { + guard let value = options[key] else { + return false + } + return !(value is NSNull) + } + + @available(*, deprecated, renamed: "resolve()") + func success() { + successHandler(CAPPluginCallResult([:]), self) + } + + @available(*, deprecated, renamed: "resolve") + func success(_ data: PluginCallResultData = [:]) { + successHandler(CAPPluginCallResult(data), self) + } + + func resolve() { + successHandler(CAPPluginCallResult(nil), self) + } + + func resolve(_ data: PluginCallResultData = [:]) { + successHandler(CAPPluginCallResult(data), self) + } + + @available(*, deprecated, renamed: "reject") + func error(_ message: String, _ error: Error? = nil, _ data: PluginCallResultData = [:]) { + errorHandler(CAPPluginCallError(message: message, code: nil, error: error, data: data)) + } + + func reject(_ message: String, _ code: String? = nil, _ error: Error? = nil, _ data: PluginCallResultData? = nil) { + errorHandler(CAPPluginCallError(message: message, code: code, error: error, data: data)) + } + + func unimplemented() { + unimplemented("not implemented") + } + + func unimplemented(_ message: String) { + errorHandler(CAPPluginCallError(message: message, code: "UNIMPLEMENTED", error: nil, data: [:])) + } + + func unavailable() { + unavailable("not available") + } + + func unavailable(_ message: String) { + errorHandler(CAPPluginCallError(message: message, code: "UNAVAILABLE", error: nil, data: [:])) + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginMethod.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginMethod.h new file mode 100644 index 0000000..a0a950d --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginMethod.h @@ -0,0 +1,36 @@ +#import "CAPPluginCall.h" +#import "CAPPlugin.h" + +typedef enum { + CAPPluginMethodArgumentNotNullable, + CAPPluginMethodArgumentNullable +} CAPPluginMethodArgumentNullability; + +typedef NSString CAPPluginReturnType; + +/** + * Represents a single argument to a plugin method. + */ +@interface CAPPluginMethodArgument : NSObject + +@property (nonatomic, copy) NSString *name; +@property (nonatomic, assign) CAPPluginMethodArgumentNullability nullability; + +- (instancetype)initWithName:(NSString *)name nullability:(CAPPluginMethodArgumentNullability)nullability type:(NSString *)type; + +@end + +/** + * Represents a method that a plugin supports, with the ability + * to compute selectors and invoke the method. + */ +@interface CAPPluginMethod : NSObject + +@property (nonatomic, assign) SEL selector; +@property (nonatomic, strong) NSString *name; // Raw method name +@property (nonatomic, strong) CAPPluginReturnType *returnType; // Return type of method (i.e. callback/promise/sync) + +- (instancetype)initWithName:(NSString *)name returnType:(CAPPluginReturnType *)returnType; + + +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginMethod.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginMethod.m new file mode 100644 index 0000000..34a30af --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPPluginMethod.m @@ -0,0 +1,36 @@ +#import +#import "CAPPluginMethod.h" + +typedef void(^CAPCallback)(id _arg, NSInteger index); + +@implementation CAPPluginMethodArgument + +- (instancetype)initWithName:(NSString *)name nullability:(CAPPluginMethodArgumentNullability)nullability type:(NSString *)type { + self.name = name; + self.nullability = nullability; + return self; +} + +@end + +@implementation CAPPluginMethod { + // NSInvocation's retainArguments doesn't work with our arguments + // so we have to retain args manually + NSMutableArray *_manualRetainArgs; + // Retain invocation instance + NSInvocation *_invocation; + NSMutableArray *_methodArgumentCallbacks; + CAPPluginCall *_call; + SEL _selector; +} + +-(instancetype)initWithName:(NSString *)name returnType:(CAPPluginReturnType *)returnType { + self.name = name; + self.selector = NSSelectorFromString([name stringByAppendingString:@":"]); + self.returnType = returnType; + return self; +} + + +@end + diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPWebView.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPWebView.swift new file mode 100644 index 0000000..241fbe8 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CAPWebView.swift @@ -0,0 +1,263 @@ +import Foundation +import WebKit +import UIKit + +open class CAPWebView: UIView { + lazy var webView: WKWebView = createWebView( + with: configuration, + assetHandler: assetHandler, + delegationHandler: delegationHandler + ) + + private lazy var capacitorBridge = CapacitorBridge( + with: configuration, + delegate: self, + cordovaConfiguration: configDescriptor.cordovaConfiguration, + assetHandler: assetHandler, + delegationHandler: delegationHandler, + autoRegisterPlugins: autoRegisterPlugins + ) + + public final var bridge: CAPBridgeProtocol { + return capacitorBridge + } + + private lazy var configDescriptor = instanceDescriptor() + private lazy var configuration = InstanceConfiguration(with: configDescriptor, isDebug: CapacitorBridge.isDevEnvironment) + + private lazy var assetHandler: WebViewAssetHandler = { + let handler = WebViewAssetHandler(router: router) + handler.setAssetPath(configuration.appLocation.path) + handler.setServerUrl(configuration.serverURL) + return handler + }() + + private lazy var delegationHandler = WebViewDelegationHandler() + private let autoRegisterPlugins: Bool + + open var router: Router { _Router() } + + public required init?(coder: NSCoder) { + autoRegisterPlugins = true + super.init(coder: coder) + setup() + } + + public init(autoRegisterPlugins: Bool = true) { + self.autoRegisterPlugins = autoRegisterPlugins + super.init(frame: .zero) + setup() + } + + private func setup() { + CAPLog.enableLogging = configuration.loggingEnabled + logWarnings(for: configDescriptor) + + if configDescriptor.instanceType == .fixed { updateBinaryVersion() } + + addSubview(webView) + webView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + webView.topAnchor.constraint(equalTo: topAnchor), + webView.bottomAnchor.constraint(equalTo: bottomAnchor), + webView.leadingAnchor.constraint(equalTo: leadingAnchor), + webView.trailingAnchor.constraint(equalTo: trailingAnchor) + ]) + + guard FileManager.default.fileExists(atPath: bridge.config.appStartFileURL.path) else { fatalLoadError() } + capacitorDidLoad() + + let url = bridge.config.appStartServerURL + CAPLog.print("⚡️ Loading app at \(url.absoluteString)") + capacitorBridge.webViewDelegationHandler.willLoadWebview(webView) + _ = webView.load(URLRequest(url: url)) + } + + public lazy final var isNewBinary: Bool = { + if let curVersionCode = Bundle.main.infoDictionary?["CFBundleVersion"] as? String, + let curVersionName = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { + if let lastVersionCode = UserDefaults.standard.string(forKey: "lastBinaryVersionCode"), + let lastVersionName = UserDefaults.standard.string(forKey: "lastBinaryVersionName") { + return (curVersionCode.isEqual(lastVersionCode) == false || curVersionName.isEqual(lastVersionName) == false) + } + } + return false + }() + + open func instanceDescriptor() -> InstanceDescriptor { + let descriptor = InstanceDescriptor.init() + if !isNewBinary && !descriptor.cordovaDeployDisabled { + if let persistedPath = UserDefaults.standard.string(forKey: "serverBasePath"), !persistedPath.isEmpty { + if let libPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first { + descriptor.appLocation = URL(fileURLWithPath: libPath, isDirectory: true) + .appendingPathComponent("NoCloud") + .appendingPathComponent("ionic_built_snapshots") + .appendingPathComponent(URL(fileURLWithPath: persistedPath, isDirectory: true).lastPathComponent) + } + } + } + return descriptor + } + + /** + Allows any additional configuration to be performed. The `webView` and `bridge` properties will be set by this point. + + - Note: This is called before the webview has been added to the view hierarchy. Not all operations may be possible at + this time. + */ + open func capacitorDidLoad() { + } + + open func loadInitialContext(_ userContentController: WKUserContentController) { + CAPLog.print("in loadInitialContext base") + } + + public func setServerBasePath(path: String) { + let url = URL(fileURLWithPath: path, isDirectory: true) + guard FileManager.default.fileExists(atPath: url.path) else { return } + + capacitorBridge.config = capacitorBridge.config.updatingAppLocation(url) + capacitorBridge.webViewAssetHandler.setAssetPath(url.path) + + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + _ = self.webView.load(URLRequest(url: self.capacitorBridge.config.serverURL)) + } + } +} + +extension CAPWebView { + + public func webViewConfiguration(for instanceConfiguration: InstanceConfiguration) -> WKWebViewConfiguration { + let webViewConfiguration = WKWebViewConfiguration() + webViewConfiguration.websiteDataStore.httpCookieStore.add(CapacitorWKCookieObserver()) + webViewConfiguration.allowsInlineMediaPlayback = true + webViewConfiguration.suppressesIncrementalRendering = false + webViewConfiguration.allowsAirPlayForMediaPlayback = true + webViewConfiguration.mediaTypesRequiringUserActionForPlayback = [] + + if #available(iOS 14.0, *) { + webViewConfiguration.limitsNavigationsToAppBoundDomains = instanceConfiguration.limitsNavigationsToAppBoundDomains + } + + if let appendUserAgent = instanceConfiguration.appendedUserAgentString { + if let appName = webViewConfiguration.applicationNameForUserAgent { + webViewConfiguration.applicationNameForUserAgent = "\(appName) \(appendUserAgent)" + } else { + webViewConfiguration.applicationNameForUserAgent = appendUserAgent + } + } + + if let preferredContentMode = instanceConfiguration.preferredContentMode { + var mode = WKWebpagePreferences.ContentMode.recommended + if preferredContentMode == "mobile" { + mode = WKWebpagePreferences.ContentMode.mobile + } else if preferredContentMode == "desktop" { + mode = WKWebpagePreferences.ContentMode.desktop + } + webViewConfiguration.defaultWebpagePreferences.preferredContentMode = mode + } + + return webViewConfiguration + } + + private func createWebView(with configuration: InstanceConfiguration, assetHandler: WebViewAssetHandler, delegationHandler: WebViewDelegationHandler) -> WKWebView { + // set the cookie policy + HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always + // setup the web view configuration + let webViewConfig = webViewConfiguration(for: configuration) + webViewConfig.setURLSchemeHandler(assetHandler, forURLScheme: configuration.localURL.scheme ?? InstanceDescriptorDefaults.scheme) + webViewConfig.userContentController = delegationHandler.contentController + // create the web view and set its properties + loadInitialContext(webViewConfig.userContentController) + let webView = WKWebView(frame: .zero, configuration: webViewConfig) + webView.scrollView.bounces = false + webView.scrollView.contentInsetAdjustmentBehavior = configuration.contentInsetAdjustmentBehavior + webView.allowsLinkPreview = configuration.allowLinkPreviews + webView.scrollView.isScrollEnabled = configuration.scrollingEnabled + + if let overrideUserAgent = configuration.overridenUserAgentString { + webView.customUserAgent = overrideUserAgent + } + + if let backgroundColor = configuration.backgroundColor { + self.backgroundColor = backgroundColor + webView.backgroundColor = backgroundColor + webView.scrollView.backgroundColor = backgroundColor + } else { + // Use the system background colors if background is not set by user + self.backgroundColor = UIColor.systemBackground + webView.backgroundColor = UIColor.systemBackground + webView.scrollView.backgroundColor = UIColor.systemBackground + } + + // set our delegates + webView.uiDelegate = delegationHandler + webView.navigationDelegate = delegationHandler + return webView + } + + private func logWarnings(for descriptor: InstanceDescriptor) { + if descriptor.warnings.contains(.missingAppDir) { + CAPLog.print("⚡️ ERROR: Unable to find application directory at: \"\(descriptor.appLocation.absoluteString)\"!") + } + if descriptor.instanceType == .fixed { + if descriptor.warnings.contains(.missingFile) { + CAPLog.print("Unable to find capacitor.config.json, make sure it exists and run npx cap copy.") + } + if descriptor.warnings.contains(.invalidFile) { + CAPLog.print("Unable to parse capacitor.config.json. Make sure it's valid JSON.") + } + if descriptor.warnings.contains(.missingCordovaFile) { + CAPLog.print("Unable to find config.xml, make sure it exists and run npx cap copy.") + } + if descriptor.warnings.contains(.invalidCordovaFile) { + CAPLog.print("Unable to parse config.xml. Make sure it's valid XML.") + } + } + } + + private func updateBinaryVersion() { + guard isNewBinary else { + return + } + guard let versionCode = Bundle.main.infoDictionary?["CFBundleVersion"] as? String, + let versionName = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { + return + } + let prefs = UserDefaults.standard + prefs.set(versionCode, forKey: "lastBinaryVersionCode") + prefs.set(versionName, forKey: "lastBinaryVersionName") + prefs.set("", forKey: "serverBasePath") + prefs.synchronize() + } + + private func fatalLoadError() -> Never { + printLoadError() + exit(1) + } + + private func printLoadError() { + let fullStartPath = capacitorBridge.config.appStartFileURL.path + + CAPLog.print("⚡️ ERROR: Unable to load \(fullStartPath)") + CAPLog.print("⚡️ This file is the root of your web app and must exist before") + CAPLog.print("⚡️ Capacitor can run. Ensure you've run capacitor copy at least") + CAPLog.print("⚡️ or, if embedding, that this directory exists as a resource directory.") + } +} + +extension CAPWebView: CAPBridgeDelegate { + internal var bridgedWebView: WKWebView? { + return webView + } + + internal var bridgedViewController: UIViewController? { + // search for the parent view controller + var object = self.next + while !(object is UIViewController) && object != nil { + object = object?.next + } + return object as? UIViewController + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Capacitor.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/Capacitor.h new file mode 100644 index 0000000..11401ac --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Capacitor.h @@ -0,0 +1,16 @@ +#import + +//! Project version number for bridge. +FOUNDATION_EXPORT double CapacitorVersionNumber; + +//! Project version string for bridge. +FOUNDATION_EXPORT const unsigned char CapacitorVersionString[]; + +#import +#import +#import +#import +#import +#import +#import + diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Capacitor.modulemap b/node_modules/@capacitor/ios/Capacitor/Capacitor/Capacitor.modulemap new file mode 100644 index 0000000..b39eb8e --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Capacitor.modulemap @@ -0,0 +1,8 @@ +framework module Capacitor { + umbrella header "Capacitor.h" + exclude header "CAPBridgedJSTypes.h" + exclude header "CAPBridgeViewController+CDVScreenOrientationDelegate.h" + + export * + module * { export * } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CapacitorBridge.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CapacitorBridge.swift new file mode 100644 index 0000000..a6ef6c7 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CapacitorBridge.swift @@ -0,0 +1,724 @@ +import Foundation +import Dispatch +import WebKit +import Cordova + +internal typealias CapacitorPlugin = CAPPlugin & CAPBridgedPlugin + +/** + An internal class adopting a public protocol means that we have a lot of `public` methods + but that is by design not a mistake. And since the bridge is the center of the whole project + its size/complexity is unavoidable. + + Quiet these warnings for the whole file. + */ +// swiftlint:disable lower_acl_than_parent +// swiftlint:disable file_length +// swiftlint:disable type_body_length +internal class CapacitorBridge: NSObject, CAPBridgeProtocol { + + // this decision is needed before the bridge is instantiated, + // so we need a class property to avoid duplication + internal static var isDevEnvironment: Bool { + #if DEBUG + return true + #else + return false + #endif + } + + // MARK: - CAPBridgeProtocol: Properties + + public var webView: WKWebView? { + return bridgeDelegate?.bridgedWebView + } + + public let autoRegisterPlugins: Bool + + public var notificationRouter: NotificationRouter + + public var isSimEnvironment: Bool { + #if targetEnvironment(simulator) + return true + #else + return false + #endif + } + + public var isDevEnvironment: Bool { + return CapacitorBridge.isDevEnvironment + } + + public var userInterfaceStyle: UIUserInterfaceStyle { + return viewController?.traitCollection.userInterfaceStyle ?? .unspecified + } + + public var statusBarVisible: Bool { + get { + return !(viewController?.prefersStatusBarHidden ?? true) + } + set { + DispatchQueue.main.async { [weak self] in + (self?.viewController as? CAPBridgeViewController)?.setStatusBarVisible(newValue) + } + } + } + + public var statusBarStyle: UIStatusBarStyle { + get { + return viewController?.preferredStatusBarStyle ?? .default + } + set { + DispatchQueue.main.async { [weak self] in + (self?.viewController as? CAPBridgeViewController)?.setStatusBarStyle(newValue) + } + } + } + + public var statusBarAnimation: UIStatusBarAnimation { + get { + return (viewController as? CAPBridgeViewController)?.statusBarAnimation ?? .slide + } + set { + DispatchQueue.main.async { [weak self] in + (self?.viewController as? CAPBridgeViewController)?.setStatusBarAnimation(newValue) + } + } + } + + var tmpWindow: UIWindow? + static let tmpVCAppeared = Notification(name: Notification.Name(rawValue: "tmpViewControllerAppeared")) + public static let capacitorSite = "https://capacitorjs.com/" + public static let fileStartIdentifier = "/_capacitor_file_" + public static let httpInterceptorStartIdentifier = "/_capacitor_http_interceptor_" + @available(*, deprecated, message: "`httpsInterceptorStartIdentifier` is no longer required. All proxied requests are handled via `httpInterceptorStartIdentifier` instead") + public static let httpsInterceptorStartIdentifier = "/_capacitor_https_interceptor_" + public static let httpInterceptorUrlParam = "u" + public static let defaultScheme = "capacitor" + + var webViewAssetHandler: WebViewAssetHandler + var webViewDelegationHandler: WebViewDelegationHandler + weak var bridgeDelegate: CAPBridgeDelegate? + @objc public var viewController: UIViewController? { + return bridgeDelegate?.bridgedViewController + } + + var lastPlugin: CAPPlugin? + + @objc public internal(set) var config: InstanceConfiguration + // Map of all loaded and instantiated plugins by pluginId -> instance + var plugins = [String: CapacitorPlugin]() + // Manager for getting Cordova plugins + var cordovaPluginManager: CDVPluginManager? + // Calls we are storing to resolve later + var storedCalls = [String: CAPPluginCall]() + // Whether to inject the Cordova files + private var injectCordovaFiles = false + private var cordovaParser: CDVConfigParser? + + // Background dispatch queue for plugin calls + var dispatchQueue = DispatchQueue(label: "bridge") + // Array of block based observers + var observers: [NSObjectProtocol] = [] + + // MARK: - CAPBridgeProtocol: Deprecated + + public func getWebView() -> WKWebView? { + return webView + } + + public func isSimulator() -> Bool { + return isSimEnvironment + } + + public func isDevMode() -> Bool { + return isDevEnvironment + } + + public func getStatusBarVisible() -> Bool { + return statusBarVisible + } + + @nonobjc public func setStatusBarVisible(_ visible: Bool) { + statusBarVisible = visible + } + + public func getStatusBarStyle() -> UIStatusBarStyle { + return statusBarStyle + } + @nonobjc public func setStatusBarStyle(_ style: UIStatusBarStyle) { + statusBarStyle = style + } + + public func getUserInterfaceStyle() -> UIUserInterfaceStyle { + return userInterfaceStyle + } + + public func getLocalUrl() -> String { + return config.localURL.absoluteString + } + + @nonobjc public func setStatusBarAnimation(_ animation: UIStatusBarAnimation) { + statusBarAnimation = animation + } + + public func setServerBasePath(_ path: String) { + let url = URL(fileURLWithPath: path, isDirectory: true) + guard FileManager.default.fileExists(atPath: url.path) else { return } + config = config.updatingAppLocation(url) + webViewAssetHandler.setAssetPath(url.path) + } + + // MARK: - Static Methods + + /** + Print a hopefully informative error message to the log when something + particularly dreadful happens. + */ + static func fatalError(_ error: Error, _ originalError: Error) { + CAPLog.print("⚡️ ❌ Capacitor: FATAL ERROR") + CAPLog.print("⚡️ ❌ Error was: ", originalError.localizedDescription) + switch error { + case CapacitorBridgeError.errorExportingCoreJS: + CAPLog.print("⚡️ ❌ Unable to export required Bridge JavaScript. Bridge will not function.") + CAPLog.print("⚡️ ❌ You should run \"npx capacitor copy\" to ensure the Bridge JS is added to your project.") + if let wke = originalError as? WKError { + CAPLog.print("⚡️ ❌ ", wke.userInfo) + } + default: + CAPLog.print("⚡️ ❌ Unknown error") + } + + CAPLog.print("⚡️ ❌ Please verify your installation or file an issue") + } + + // MARK: - Initialization + + init(with configuration: InstanceConfiguration, delegate bridgeDelegate: CAPBridgeDelegate, cordovaConfiguration: CDVConfigParser, assetHandler: WebViewAssetHandler, delegationHandler: WebViewDelegationHandler, autoRegisterPlugins: Bool = true) { + self.bridgeDelegate = bridgeDelegate + self.webViewAssetHandler = assetHandler + self.webViewDelegationHandler = delegationHandler + self.config = configuration + self.cordovaParser = cordovaConfiguration + self.notificationRouter = NotificationRouter() + self.notificationRouter.handleApplicationNotifications = configuration.handleApplicationNotifications + self.autoRegisterPlugins = autoRegisterPlugins + super.init() + + self.webViewDelegationHandler.bridge = self + + exportCoreJS(localUrl: configuration.localURL.absoluteString) + registerPlugins() + setupCordovaCompatibility() + observers.append(NotificationCenter.default.addObserver(forName: type(of: self).tmpVCAppeared.name, object: .none, queue: .none) { [weak self] _ in + self?.tmpWindow = nil + }) + + self.setupWebDebugging(configuration: configuration) + } + + deinit { + // the message handler needs to removed to avoid any retain cycles + webViewDelegationHandler.cleanUp() + for observer in observers { + NotificationCenter.default.removeObserver(observer) + } + } + + // MARK: - Plugins + /** + Export core JavaScript to the webview + */ + func exportCoreJS(localUrl: String) { + do { + try JSExport.exportCapacitorGlobalJS(userContentController: webViewDelegationHandler.contentController, + isDebug: isDevEnvironment, + loggingEnabled: config.loggingEnabled, + localUrl: localUrl) + try JSExport.exportBridgeJS(userContentController: webViewDelegationHandler.contentController) + } catch { + type(of: self).fatalError(error, error) + } + } + + /** + Set up our Cordova compat by loading all known Cordova plugins and injecting their JS. + */ + func setupCordovaCompatibility() { + if injectCordovaFiles { + exportCordovaJS() + registerCordovaPlugins() + } else { + observers.append(NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: OperationQueue.main) { [weak self] (_) in + self?.triggerDocumentJSEvent(eventName: "resume") + }) + observers.append(NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: OperationQueue.main) { [weak self] (_) in + self?.triggerDocumentJSEvent(eventName: "pause") + }) + } + } + + /** + Export the core Cordova JS runtime + */ + func exportCordovaJS() { + do { + try JSExport.exportCordovaJS(userContentController: webViewDelegationHandler.contentController) + } catch { + type(of: self).fatalError(error, error) + } + } + + /** + Reset the state of the bridge between navigations to avoid + sending data back to the page from a previous page. + */ + func reset() { + storedCalls = [String: CAPPluginCall]() + } + + /** + Register all plugins that have been declared + */ + func registerPlugins() { + if autoRegisterPlugins { + let classCount = objc_getClassList(nil, 0) + let classes = UnsafeMutablePointer.allocate(capacity: Int(classCount)) + + let releasingClasses = AutoreleasingUnsafeMutablePointer(classes) + let numClasses: Int32 = objc_getClassList(releasingClasses, classCount) + + for classIndex in 0.. CapacitorPlugin? { + guard let plugin = type.init() as? CapacitorPlugin else { + CAPLog.print("⚡️ Unable to load plugin \(type.classForCoder()). No such module found.") + return nil + } + plugin.load(on: self) + plugins[plugin.jsName] = plugin + return plugin + } + + // MARK: - CAPBridgeProtocol: Plugin Access + + @objc public func plugin(withName: String) -> CAPPlugin? { + return self.plugins[withName] + } + + // MARK: - CAPBridgeProtocol: Call Management + + @objc public func saveCall(_ call: CAPPluginCall) { + storedCalls[call.callbackId] = call + } + + @objc public func savedCall(withID: String) -> CAPPluginCall? { + return storedCalls[withID] + } + + @objc public func releaseCall(_ call: CAPPluginCall) { + releaseCall(withID: call.callbackId) + } + + @objc public func releaseCall(withID: String) { + storedCalls.removeValue(forKey: withID) + } + + // MARK: - Deprecated Versions + + @objc public func getSavedCall(_ callbackId: String) -> CAPPluginCall? { + return savedCall(withID: callbackId) + } + + @objc public func releaseCall(callbackId: String) { + releaseCall(withID: callbackId) + } + + // MARK: - Internal + + func getDispatchQueue() -> DispatchQueue { + return self.dispatchQueue + } + + func registerCordovaPlugins() { + guard let cordovaParser = cordovaParser else { + return + } + cordovaPluginManager = CDVPluginManager.init(parser: cordovaParser, viewController: self.viewController, webView: self.getWebView()) + if cordovaParser.startupPluginNames.count > 0 { + for pluginName in cordovaParser.startupPluginNames { + _ = cordovaPluginManager?.getCommandInstance(pluginName as? String) + } + } + do { + try JSExport.exportCordovaPluginsJS(userContentController: webViewDelegationHandler.contentController) + } catch { + type(of: self).fatalError(error, error) + } + } + + func reload() { + self.getWebView()?.reload() + } + + func docLink(_ url: String) -> String { + return "\(type(of: self).capacitorSite)docs/\(url)" + } + + private func setupWebDebugging(configuration: InstanceConfiguration) { + let isWebDebuggable = configuration.isWebDebuggable + if isWebDebuggable, #unavailable(iOS 16.4) { + CAPLog.print("⚡️ Warning: isWebDebuggable only functions as intended on iOS 16.4 and above.") + } + + self.webView?.setInspectableIfRequired(isWebDebuggable) + } + + /** + Handle a call from JavaScript. First, find the corresponding plugin, construct a selector, + and perform that selector on the plugin instance. + + Quiet the length warning because we don't want to refactor the function at this time. + */ + // swiftlint:disable:next function_body_length + func handleJSCall(call: JSCall) { + let load = { + NSClassFromString(call.pluginId) + .flatMap { $0 as? CAPPlugin.Type } + .flatMap(self.loadPlugin(type:)) + } + + guard let plugin = plugins[call.pluginId] ?? load() else { + CAPLog.print("⚡️ Error loading plugin \(call.pluginId) for call. Check that the pluginId is correct") + return + } + + let selector: Selector + if call.method == "addListener" || call.method == "removeListener" { + selector = NSSelectorFromString(call.method + ":") + } else { + guard let method = plugin.getMethod(named: call.method) else { + CAPLog.print("⚡️ Error calling method \(call.method) on plugin \(call.pluginId): No method found.") + CAPLog.print("⚡️ Ensure plugin method exists and uses @objc in its declaration, and has been defined") + return + } + + selector = method.selector + } + + if !plugin.responds(to: selector) { + // we don't want to break up string literals + // swiftlint:disable line_length + CAPLog.print("⚡️ Error: Plugin \(plugin.getId()) does not respond to method call \"\(call.method)\" using selector \"\(selector)\".") + CAPLog.print("⚡️ Ensure plugin method exists, uses @objc in its declaration, and arguments match selector without callbacks in CAP_PLUGIN_METHOD.") + CAPLog.print("⚡️ Learn more: \(docLink(DocLinks.CAPPluginMethodSelector.rawValue))") + // swiftlint:enable line_length + return + } + + // Create a plugin call object and handle the success/error callbacks + dispatchQueue.async { [weak self] in + // let startTime = CFAbsoluteTimeGetCurrent() + + let pluginCall = CAPPluginCall(callbackId: call.callbackId, + options: JSTypes.coerceDictionaryToJSObject(call.options, + formattingDatesAsStrings: plugin.shouldStringifyDatesInCalls) ?? [:], + success: {(result: CAPPluginCallResult?, pluginCall: CAPPluginCall?) -> Void in + if let result = result { + self?.toJs(result: JSResult(call: call, callResult: result), save: pluginCall?.keepAlive ?? false) + } else { + self?.toJs(result: JSResult(call: call, result: .dictionary([:])), save: pluginCall?.keepAlive ?? false) + } + }, error: {(error: CAPPluginCallError?) -> Void in + if let error = error { + self?.toJsError(error: JSResultError(call: call, callError: error)) + } else { + self?.toJsError(error: JSResultError(call: call, + errorMessage: "", + errorDescription: "", + errorCode: nil, + result: .dictionary([:]))) + } + }) + + if let pluginCall = pluginCall { + plugin.perform(selector, with: pluginCall) + if pluginCall.keepAlive { + self?.saveCall(pluginCall) + } + } + + // let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime + // CAPLog.print("Native call took", timeElapsed) + } + } + + /** + Handle a Cordova call from JavaScript. First, find the corresponding plugin, + construct a selector, and perform that selector on the plugin instance. + */ + func handleCordovaJSCall(call: JSCall) { + // Create a selector to send to the plugin + + if let plugin = self.cordovaPluginManager?.getCommandInstance(call.pluginId.lowercased()) { + let selector = NSSelectorFromString("\(call.method):") + if !plugin.responds(to: selector) { + CAPLog.print("Error: Plugin \(plugin.className ?? "") does not respond to method call \(selector).") + CAPLog.print("Ensure plugin method exists and uses @objc in its declaration") + return + } + + let arguments: [Any] = call.options["options"] as? [Any] ?? [] + let pluginCall = CDVInvokedUrlCommand(arguments: arguments, + callbackId: call.callbackId, + className: plugin.className, + methodName: call.method) + plugin.perform(selector, with: pluginCall) + + } else { + CAPLog.print("Error: Cordova Plugin mapping not found") + return + } + } + + /** + Send a successful result to the JavaScript layer. + */ + func toJs(result: JSResultProtocol, save: Bool) { + let resultJson = result.jsonPayload() + CAPLog.print("⚡️ TO JS", resultJson.prefix(256)) + + DispatchQueue.main.async { + self.webView?.evaluateJavaScript(""" + window.Capacitor.fromNative({ + callbackId: '\(result.callbackID)', + pluginId: '\(result.pluginID)', + methodName: '\(result.methodName)', + save: \(save), + success: true, + data: \(resultJson) + }) + """) { (_, error) in + if let error = error { + CAPLog.print(error) + } + } + } + } + + /** + Send an error result to the JavaScript layer. + */ + func toJsError(error: JSResultProtocol) { + DispatchQueue.main.async { + self.webView?.evaluateJavaScript("window.Capacitor.fromNative({ callbackId: '\(error.callbackID)', pluginId: '\(error.pluginID)', methodName: '\(error.methodName)', success: false, error: \(error.jsonPayload())})") { (_, error) in + if let error = error { + CAPLog.print(error) + } + } + } + } + + // MARK: - CAPBridgeProtocol: JavaScript Handling + + /** + Eval JS for a specific plugin. + + `js` is a short name but needs to be preserved for backwards compatibility. + */ + // swiftlint:disable:next identifier_name + @objc public func evalWithPlugin(_ plugin: CAPPlugin, js: String) { + let wrappedJs = """ + window.Capacitor.withPlugin('\(plugin.getId())', function(plugin) { + if(!plugin) { console.error('Unable to execute JS in plugin, no such plugin found for id \(plugin.getId())'); } + \(js) + }); + """ + + DispatchQueue.main.async { + self.getWebView()?.evaluateJavaScript(wrappedJs, completionHandler: { (_, error) in + if let error = error { + CAPLog.print("⚡️ JS Eval error", error.localizedDescription) + } + }) + } + } + + /** + Eval JS in the web view + + `js` is a short name but needs to be preserved for backwards compatibility. + */ + // swiftlint:disable:next identifier_name + @objc public func eval(js: String) { + DispatchQueue.main.async { + self.getWebView()?.evaluateJavaScript(js, completionHandler: { (_, error) in + if let error = error { + CAPLog.print("⚡️ JS Eval error", error.localizedDescription) + } + }) + } + } + + @objc public func triggerJSEvent(eventName: String, target: String) { + self.eval(js: "window.Capacitor.triggerEvent('\(eventName)', '\(target)')") + } + + @objc public func triggerJSEvent(eventName: String, target: String, data: String) { + self.eval(js: "window.Capacitor.triggerEvent('\(eventName)', '\(target)', \(data))") + } + + @objc public func triggerWindowJSEvent(eventName: String) { + self.triggerJSEvent(eventName: eventName, target: "window") + } + + @objc public func triggerWindowJSEvent(eventName: String, data: String) { + self.triggerJSEvent(eventName: eventName, target: "window", data: data) + } + + @objc public func triggerDocumentJSEvent(eventName: String) { + self.triggerJSEvent(eventName: eventName, target: "document") + } + + @objc public func triggerDocumentJSEvent(eventName: String, data: String) { + self.triggerJSEvent(eventName: eventName, target: "document", data: data) + } + + public func logToJs(_ message: String, _ level: String = "log") { + DispatchQueue.main.async { + self.getWebView()?.evaluateJavaScript("window.Capacitor.logJs('\(message)', '\(level)')") { (result, error) in + if error != nil, let result = result { + CAPLog.print(result) + } + } + } + } + + // MARK: - CAPBridgeProtocol: Paths, Files, Assets + + /** + Translate a URL from the web view into a file URL for native iOS. + + The web view may be handling several different types of URLs: + - res:// (shortcut scheme to web assets) + - file:// (fully qualified URL to file on the local device) + - base64:// (to be implemented) + - [web view scheme]:// (already converted once to load in the web view, to be implemented) + */ + public func localURL(fromWebURL webURL: URL?) -> URL? { + guard let inputURL = webURL else { + return nil + } + + let url: URL + + switch inputURL.scheme { + case "res": + url = config.appLocation.appendingPathComponent(inputURL.path) + case "file": + url = inputURL + default: + return nil + } + + return url + } + + /** + Translate a file URL for native iOS into a URL to load in the web view. + */ + public func portablePath(fromLocalURL localURL: URL?) -> URL? { + guard let inputURL = localURL else { + return nil + } + + return self.config.localURL.appendingPathComponent(CapacitorBridge.fileStartIdentifier).appendingPathComponent(inputURL.path) + } + + // MARK: - CAPBridgeProtocol: View Presentation + + @objc public func showAlertWith(title: String, message: String, buttonTitle: String) { + let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) + alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertAction.Style.default, handler: nil)) + self.viewController?.present(alert, animated: true, completion: nil) + } + + @objc public func presentVC(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { + if viewControllerToPresent.modalPresentationStyle == .popover { + self.viewController?.present(viewControllerToPresent, animated: flag, completion: completion) + } else { + self.tmpWindow = UIWindow.init(frame: UIScreen.main.bounds) + self.tmpWindow?.rootViewController = TmpViewController.init() + self.tmpWindow?.makeKeyAndVisible() + self.tmpWindow?.rootViewController?.present(viewControllerToPresent, animated: flag, completion: completion) + } + } + + @objc public func dismissVC(animated flag: Bool, completion: (() -> Void)? = nil) { + if self.tmpWindow == nil { + self.viewController?.dismiss(animated: flag, completion: completion) + } else { + self.tmpWindow?.rootViewController?.dismiss(animated: flag, completion: completion) + self.tmpWindow = nil + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/CapacitorExtension.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/CapacitorExtension.swift new file mode 100644 index 0000000..0951099 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/CapacitorExtension.swift @@ -0,0 +1,24 @@ +import Foundation + +public protocol CapacitorExtension { + associatedtype CapacitorType + var capacitor: CapacitorType { get } + static var capacitor: CapacitorType.Type { get } +} + +public extension CapacitorExtension { + var capacitor: CapacitorExtensionTypeWrapper { + return CapacitorExtensionTypeWrapper(self) + } + + static var capacitor: CapacitorExtensionTypeWrapper.Type { + return CapacitorExtensionTypeWrapper.self + } +} + +public struct CapacitorExtensionTypeWrapper { + var baseType: T + init(_ baseType: T) { + self.baseType = baseType + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Data+Capacitor.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Data+Capacitor.swift new file mode 100644 index 0000000..1105c58 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Data+Capacitor.swift @@ -0,0 +1,22 @@ +extension Data: CapacitorExtension {} +public extension CapacitorExtensionTypeWrapper where T == Data { + + static func data(base64EncodedOrDataUrl: String) -> Data? { + if isBase64DataUrl(base64EncodedOrDataUrl) { + if let url = URL(string: base64EncodedOrDataUrl) { + do { + return try T(contentsOf: url) + } catch { + return nil + } + } + return nil + } else { + return T(base64Encoded: base64EncodedOrDataUrl) + } + } + + private static func isBase64DataUrl(_ base64EncodedOrDataUrl: String) -> Bool { + return base64EncodedOrDataUrl.starts(with: "data:") && base64EncodedOrDataUrl.contains("base64,") + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/DocLinks.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/DocLinks.swift new file mode 100644 index 0000000..99b1f4e --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/DocLinks.swift @@ -0,0 +1,8 @@ +import Foundation + +enum DocLinks: String { + case CAPPluginMethodSelector = "plugins/ios/#defining-methods" + case NSPhotoLibraryAddUsageDescription = "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW73" + case NSPhotoLibraryUsageDescription = "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW17" + case NSCameraUsageDescription = "https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW24" +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Info.plist b/node_modules/@capacitor/ios/Capacitor/Capacitor/Info.plist new file mode 100644 index 0000000..1007fd9 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/JS.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/JS.swift new file mode 100644 index 0000000..46972c4 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/JS.swift @@ -0,0 +1,122 @@ +import Foundation + +public class JSDate { + @available(*, deprecated, message: "No longer needed. Dates will be mapped to strings during serialization.") + static func toString(_ date: Date) -> String { + let formatter = ISO8601DateFormatter() + return formatter.string(from: date) + } +} + +@available(*, deprecated, renamed: "PluginCallResultData") +public typealias JSResultBody = [String: Any] + +/** + * A call originating from JavaScript land + */ +internal struct JSCall { + let options: [String: Any] + let pluginId: String + let method: String + let callbackId: String +} + +internal protocol JSResultProtocol { + var call: JSCall { get } + var callbackID: String { get } + var pluginID: String { get } + var methodName: String { get } + func jsonPayload() -> String +} + +internal extension JSResultProtocol { + var callbackID: String { + return call.callbackId + } + + var pluginID: String { + return call.pluginId + } + + var methodName: String { + return call.method + } +} + +private enum SerializationResult: String { + case undefined = "undefined" + case empty = "{}" +} + +/** + * A result of processing a JSCall, contains + * a reference to the original call and the new result. + */ + +internal struct JSResult: JSResultProtocol { + let call: JSCall + let result: PluginCallResult? + + func jsonPayload() -> String { + guard let result = result else { + return SerializationResult.undefined.rawValue + } + do { + if let payload = try result.jsonRepresentation() { + return payload + } + } catch PluginCallResult.SerializationError.invalidObject { + CAPLog.print("[Capacitor Plugin Error] - \(call.pluginId) - \(call.method) - Unable to serialize plugin response as JSON." + + "Ensure that all data passed to success callback from module method is JSON serializable!") + } catch { + CAPLog.print("Unable to serialize plugin response as JSON: \(error.localizedDescription)") + } + return SerializationResult.empty.rawValue + } +} + +internal extension JSResult { + init(call: JSCall, callResult: CAPPluginCallResult) { + self.call = call + self.result = callResult.resultData + } +} + +internal struct JSResultError: JSResultProtocol { + let call: JSCall + let errorMessage: String + let errorDescription: String + let errorCode: String? + let result: PluginCallResult + + func jsonPayload() -> String { + var errorDictionary: [String: Any] = [ + "message": self.errorMessage, + "errorMessage": self.errorMessage + ] + errorDictionary["code"] = self.errorCode + + do { + if let payload = try result.jsonRepresentation(includingFields: errorDictionary) { + CAPLog.print("ERROR MESSAGE: ", payload.prefix(512)) + return payload + } + } catch PluginCallResult.SerializationError.invalidObject { + CAPLog.print("[Capacitor Plugin Error] - \(call.pluginId) - \(call.method) - Unable to serialize plugin response as JSON." + + "Ensure that all data passed to success callback from module method is JSON serializable!") + } catch { + CAPLog.print("Unable to serialize plugin response as JSON: \(error.localizedDescription)") + } + return SerializationResult.empty.rawValue + } +} + +internal extension JSResultError { + init(call: JSCall, callError: CAPPluginCallError) { + self.call = call + errorMessage = callError.message + errorDescription = callError.error?.localizedDescription ?? "" + errorCode = callError.code + result = callError.resultData ?? .dictionary([:]) + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/JSExport.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/JSExport.swift new file mode 100644 index 0000000..2802baa --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/JSExport.swift @@ -0,0 +1,201 @@ +internal struct PluginHeaderMethod: Codable { + let name: String + let rtype: String? +} + +internal struct PluginHeader: Codable { + let name: String + let methods: [PluginHeaderMethod] +} + +/** + JSExport handles defining JS APIs that map to registered plugins and are responsible for proxying calls to our bridge. + */ +internal class JSExport { + static let catchallOptionsParameter = "_options" + static let callbackParameter = "_callback" + + static func exportCapacitorGlobalJS(userContentController: WKUserContentController, isDebug: Bool, loggingEnabled: Bool, localUrl: String) throws { + let data = "window.Capacitor = { DEBUG: \(isDebug), isLoggingEnabled: \(loggingEnabled), Plugins: {} }; window.WEBVIEW_SERVER_URL = '\(localUrl)';" + let userScript = WKUserScript(source: data, injectionTime: .atDocumentStart, forMainFrameOnly: true) + userContentController.addUserScript(userScript) + } + + static func exportBridgeJS(userContentController: WKUserContentController) throws { + let capBundle = Bundle(for: Self.self) + guard let jsUrl = capBundle.url(forResource: "native-bridge", withExtension: "js") else { + CAPLog.print("ERROR: Required native-bridge.js file in Capacitor not found. Bridge will not function!") + throw CapacitorBridgeError.errorExportingCoreJS + } + do { + try self.injectFile(fileURL: jsUrl, userContentController: userContentController) + } catch { + CAPLog.print("ERROR: Unable to read required native-bridge.js file from the Capacitor framework. Bridge will not function!") + throw CapacitorBridgeError.errorExportingCoreJS + } + } + + static func exportCordovaJS(userContentController: WKUserContentController) throws { + guard let cordovaUrl = Bundle.main.url(forResource: "public/cordova", withExtension: "js") else { + CAPLog.print("ERROR: Required cordova.js file not found. Cordova plugins will not function!") + throw CapacitorBridgeError.errorExportingCoreJS + } + guard let cordovaPluginsUrl = Bundle.main.url(forResource: "public/cordova_plugins", withExtension: "js") else { + CAPLog.print("ERROR: Required cordova_plugins.js file not found. Cordova plugins will not function!") + throw CapacitorBridgeError.errorExportingCoreJS + } + do { + try self.injectFile(fileURL: cordovaUrl, userContentController: userContentController) + try self.injectFile(fileURL: cordovaPluginsUrl, userContentController: userContentController) + } catch { + CAPLog.print("ERROR: Unable to read required cordova files. Cordova plugins will not function!") + throw CapacitorBridgeError.errorExportingCoreJS + } + } + + /** + Export the JS required to implement the given plugin. + */ + static func exportJS(for plugin: CapacitorPlugin, in userContentController: WKUserContentController) { + var lines = [String]() + + lines.append(""" + (function(w) { + var a = (w.Capacitor = w.Capacitor || {}); + var p = (a.Plugins = a.Plugins || {}); + var t = (p['\(plugin.jsName)'] = {}); + t.addListener = function(eventName, callback) { + return w.Capacitor.addListener('\(plugin.jsName)', eventName, callback); + } + """) + + for method in plugin.pluginMethods { + lines.append(generateMethod(pluginClassName: plugin.jsName, method: method)) + } + + lines.append(""" + })(window); + """) + if let data = try? JSONEncoder().encode(createPluginHeader(for: plugin)), + let header = String(data: data, encoding: .utf8) { + lines.append(""" + (function(w) { + var a = (w.Capacitor = w.Capacitor || {}); + var h = (a.PluginHeaders = a.PluginHeaders || []); + h.push(\(header)); + })(window); + """) + } + let js = lines.joined(separator: "\n") + let userScript = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: true) + userContentController.addUserScript(userScript) + } + + private static func createPluginHeader(for plugin: CapacitorPlugin) -> PluginHeader? { + let methods = [ + PluginHeaderMethod(name: "addListener", rtype: nil), + PluginHeaderMethod(name: "removeListener", rtype: nil), + PluginHeaderMethod(name: "removeAllListeners", rtype: "promise"), + PluginHeaderMethod(name: "checkPermissions", rtype: "promise"), + PluginHeaderMethod(name: "requestPermissions", rtype: "promise") + ] + + return PluginHeader( + name: plugin.jsName, + methods: methods + plugin.pluginMethods.map(createPluginHeaderMethod) + ) + + } + + private static func createPluginHeaderMethod(method: CAPPluginMethod) -> PluginHeaderMethod { + var rtype = method.returnType + if rtype == "none" { + rtype = nil + } + return PluginHeaderMethod(name: method.name, rtype: rtype) + } + + private static func generateMethod(pluginClassName: String, method: CAPPluginMethod) -> String { + let methodName = method.name! + let returnType = method.returnType! + var paramList = [String]() + + // add the catch-all + // options argument which takes a full object and converts each + // key/value pair into an option for plugin call. + paramList.append(catchallOptionsParameter) + + // Automatically add the _callback param if returning data through a callback + if returnType == CAPPluginReturnCallback { + paramList.append(callbackParameter) + } + + // Create a param string of the form "param1, param2, param3" + let paramString = paramList.joined(separator: ", ") + + // Generate the argument object that will be sent on each call + let argObjectString = catchallOptionsParameter + + var lines = [String]() + + // Create the function declaration + lines.append("t['\(method.name!)'] = function(\(paramString)) {") + + // Create the call to Capacitor ... + if returnType == CAPPluginReturnNone { + // ...using none + lines.append(""" + return w.Capacitor.nativeCallback('\(pluginClassName)', '\(methodName)', \(argObjectString)); + """) + } else if returnType == CAPPluginReturnPromise { + + // ...using a promise + lines.append(""" + return w.Capacitor.nativePromise('\(pluginClassName)', '\(methodName)', \(argObjectString)); + """) + } else if returnType == CAPPluginReturnCallback { + // ...using a callback + lines.append(""" + return w.Capacitor.nativeCallback('\(pluginClassName)', '\(methodName)', \(argObjectString), \(callbackParameter)); + """) + } else { + CAPLog.print("Error: plugin method return type \(returnType) is not supported!") + } + + // Close the function + lines.append("}") + return lines.joined(separator: "\n") + } + + static func exportCordovaPluginsJS(userContentController: WKUserContentController) throws { + if let pluginsJSFolder = Bundle.main.url(forResource: "public/plugins", withExtension: nil) { + self.injectFilesForFolder(folder: pluginsJSFolder, userContentController: userContentController) + } + } + + static func injectFilesForFolder(folder: URL, userContentController: WKUserContentController) { + let fileManager = FileManager.default + do { + let fileURLs = try fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil, options: []) + for fileURL in fileURLs { + if fileURL.hasDirectoryPath { + injectFilesForFolder(folder: fileURL, userContentController: userContentController) + } else { + try self.injectFile(fileURL: fileURL, userContentController: userContentController) + } + } + } catch { + CAPLog.print("Error while enumerating files") + } + } + + static func injectFile(fileURL: URL, userContentController: WKUserContentController) throws { + do { + let data = try String(contentsOf: fileURL, encoding: .utf8) + let userScript = WKUserScript(source: data, injectionTime: .atDocumentStart, forMainFrameOnly: true) + userContentController.addUserScript(userScript) + } catch { + CAPLog.print("Unable to inject js file") + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/JSTypes.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/JSTypes.swift new file mode 100644 index 0000000..7d4ce14 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/JSTypes.swift @@ -0,0 +1,243 @@ +import Foundation + +// declare our empty protocol, and conformance, for typing +public protocol JSValue {} +extension String: JSValue {} +extension Bool: JSValue {} +extension Int: JSValue {} +extension Float: JSValue {} +extension Double: JSValue {} +extension NSNumber: JSValue {} +extension NSNull: JSValue {} +extension Array: JSValue {} +extension Date: JSValue {} +extension Dictionary: JSValue where Key == String, Value == JSValue {} + +// convenience aliases +public typealias JSObject = [String: JSValue] +public typealias JSArray = [JSValue] + +// string types +public protocol JSStringContainer { + func getString(_ key: String, _ defaultValue: String) -> String + func getString(_ key: String) -> String? +} + +extension JSStringContainer { + public func getString(_ key: String, _ defaultValue: String) -> String { + return getString(key) ?? defaultValue + } +} + +// boolean types +public protocol JSBoolContainer { + func getBool(_ key: String, _ defaultValue: Bool) -> Bool + func getBool(_ key: String) -> Bool? +} + +extension JSBoolContainer { + public func getBool(_ key: String, _ defaultValue: Bool) -> Bool { + return getBool(key) ?? defaultValue + } +} + +// integer types +public protocol JSIntContainer { + func getInt(_ key: String, _ defaultValue: Int) -> Int + func getInt(_ key: String) -> Int? +} + +extension JSIntContainer { + public func getInt(_ key: String, _ defaultValue: Int) -> Int { + return getInt(key) ?? defaultValue + } +} + +// float types +public protocol JSFloatContainer { + func getFloat(_ key: String, _ defaultValue: Float) -> Float + func getFloat(_ key: String) -> Float? +} + +extension JSFloatContainer { + public func getFloat(_ key: String, _ defaultValue: Float) -> Float { + return getFloat(key) ?? defaultValue + } +} + +// double types +public protocol JSDoubleContainer { + func getDouble(_ key: String, _ defaultValue: Double) -> Double + func getDouble(_ key: String) -> Double? +} + +extension JSDoubleContainer { + public func getDouble(_ key: String, _ defaultValue: Double) -> Double { + return getDouble(key) ?? defaultValue + } +} + +// date types +public protocol JSDateContainer { + func getDate(_ key: String, _ defaultValue: Date) -> Date + func getDate(_ key: String) -> Date? +} + +extension JSDateContainer { + public func getDate(_ key: String, _ defaultValue: Date) -> Date { + return getDate(key) ?? defaultValue + } +} + +// array types +public protocol JSArrayContainer { + func getArray(_ key: String, _ defaultValue: JSArray) -> JSArray + func getArray(_ key: String, _ ofType: T.Type) -> [T]? + func getArray(_ key: String) -> JSArray? +} + +extension JSArrayContainer { + public func getArray(_ key: String, _ defaultValue: JSArray) -> JSArray { + return getArray(key) ?? defaultValue + } + + public func getArray(_ key: String, _ ofType: T.Type) -> [T]? { + return getArray(key) as? [T] + } +} + +// dictionary types +public protocol JSObjectContainer { + func getObject(_ key: String, _ defaultValue: JSObject) -> JSObject + func getObject(_ key: String) -> JSObject? +} + +extension JSObjectContainer { + public func getObject(_ key: String, _ defaultValue: JSObject) -> JSObject { + return getObject(key) ?? defaultValue + } +} + +public protocol JSValueContainer: JSStringContainer, JSBoolContainer, JSIntContainer, JSFloatContainer, + JSDoubleContainer, JSDateContainer, JSArrayContainer, JSObjectContainer { + static var jsDateFormatter: ISO8601DateFormatter { get } + var jsObjectRepresentation: JSObject { get } +} + +extension JSValueContainer { + public func getValue(_ key: String) -> JSValue? { + return jsObjectRepresentation[key] + } + + @available(*, message: "All values returned conform to JSValue, use getValue(_:) instead.", renamed: "getValue(_:)") + public func getAny(_ key: String) -> Any? { + return getValue(key) + } + + public func getString(_ key: String) -> String? { + return jsObjectRepresentation[key] as? String + } + + public func getBool(_ key: String) -> Bool? { + return jsObjectRepresentation[key] as? Bool + } + + public func getInt(_ key: String) -> Int? { + return jsObjectRepresentation[key] as? Int + } + + public func getFloat(_ key: String) -> Float? { + if let floatValue = jsObjectRepresentation[key] as? Float { + return floatValue + } else if let doubleValue = jsObjectRepresentation[key] as? Double { + return Float(doubleValue) + } + return nil + } + + public func getDouble(_ key: String) -> Double? { + return jsObjectRepresentation[key] as? Double + } + + public func getDate(_ key: String) -> Date? { + if let isoString = jsObjectRepresentation[key] as? String { + return Self.jsDateFormatter.date(from: isoString) + } + return jsObjectRepresentation[key] as? Date + } + + public func getArray(_ key: String) -> JSArray? { + return jsObjectRepresentation[key] as? JSArray + } + + public func getObject(_ key: String) -> JSObject? { + return jsObjectRepresentation[key] as? JSObject + } +} + +@objc protocol BridgedJSValueContainer: NSObjectProtocol { + static var jsDateFormatter: ISO8601DateFormatter { get } + var dictionaryRepresentation: NSDictionary { get } +} + +/* + Simply casting objects from foundation class clusters (such as __NSArrayM) + doesn't work with the JSValue protocol and will always fail. So we need to + recursively and explicitly convert each value in the dictionary. + */ +public enum JSTypes {} +extension JSTypes { + public static func coerceDictionaryToJSObject(_ dictionary: NSDictionary?, formattingDatesAsStrings: Bool = false) -> JSObject? { + return coerceToJSValue(dictionary, formattingDates: formattingDatesAsStrings) as? JSObject + } + + public static func coerceDictionaryToJSObject(_ dictionary: [AnyHashable: Any]?, formattingDatesAsStrings: Bool = false) -> JSObject? { + return coerceToJSValue(dictionary, formattingDates: formattingDatesAsStrings) as? JSObject + } + + public static func coerceArrayToJSArray(_ array: [Any]?, formattingDatesAsStrings: Bool = false) -> JSArray? { + return array?.compactMap { coerceToJSValue($0, formattingDates: formattingDatesAsStrings) } + } +} + +private let dateStringFormatter = ISO8601DateFormatter() + +// We need a large switch statement because we have a lot of types. +// swiftlint:disable:next cyclomatic_complexity +private func coerceToJSValue(_ value: Any?, formattingDates: Bool) -> JSValue? { + guard let value = value else { + return nil + } + switch value { + case let stringValue as String: + return stringValue + case let numberValue as NSNumber: + return numberValue + case let boolValue as Bool: + return boolValue + case let intValue as Int: + return intValue + case let floatValue as Float: + return floatValue + case let doubleValue as Double: + return doubleValue + case let dateValue as Date: + if formattingDates { + return dateStringFormatter.string(from: dateValue) + } + return dateValue + case let nullValue as NSNull: + return nullValue + case let arrayValue as NSArray: + return arrayValue.compactMap { coerceToJSValue($0, formattingDates: formattingDates) } + case let dictionaryValue as NSDictionary: + let keys = dictionaryValue.allKeys.compactMap { $0 as? String } + var result: JSObject = [:] + for key in keys { + result[key] = coerceToJSValue(dictionaryValue[key], formattingDates: formattingDates) + } + return result + default: + return nil + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/KeyPath.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/KeyPath.swift new file mode 100644 index 0000000..e3f4733 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/KeyPath.swift @@ -0,0 +1,60 @@ +import Foundation + +public struct KeyPath { + var segments: [String] + var isEmpty: Bool { return segments.isEmpty } + var path: String { + return segments.joined(separator: ".") + } + + // initializers + init(_ string: String) { + self.segments = string.components(separatedBy: ".") + } + + init(segments: [String]) { + self.segments = segments + } + + // returns a tuple of the first segment and the remaining key path. result is nil if the key path has no segments. + func headAndRemainder() -> (head: String, remainder: KeyPath)? { + guard !isEmpty else { + return nil + } + var paths = segments + let head = paths.removeFirst() + return (head, KeyPath(segments: paths)) + } +} + +extension KeyPath: ExpressibleByStringLiteral { + public init(stringLiteral value: String) { + self.init(value) + } + + public init(unicodeScalarLiteral value: String) { + self.init(value) + } + + public init(extendedGraphemeClusterLiteral value: String) { + self.init(value) + } +} + +extension JSObject { + public subscript(keyPath keyPath: KeyPath) -> JSValue? { + switch keyPath.headAndRemainder() { + case nil: // path is empty + return nil + case let (head, remainder)? where remainder.isEmpty: // reached the end of the path + return self[head] + case let (head, remainder)?: // we have at least one level to traverse + switch self[head] { + case let childObject as JSObject: // iterate down the next level + return childObject[keyPath: remainder] + default: // not an object, can't go any deeper + return nil + } + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/NotificationHandlerProtocol.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/NotificationHandlerProtocol.swift new file mode 100644 index 0000000..2b559bd --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/NotificationHandlerProtocol.swift @@ -0,0 +1,6 @@ +import Foundation + +@objc(CAPNotificationHandlerProtocol) public protocol NotificationHandlerProtocol { + func willPresent(notification: UNNotification) -> UNNotificationPresentationOptions + func didReceive(response: UNNotificationResponse) +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/NotificationRouter.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/NotificationRouter.swift new file mode 100644 index 0000000..99fcbb2 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/NotificationRouter.swift @@ -0,0 +1,60 @@ +import Foundation + +@objc(CAPNotificationRouter) public class NotificationRouter: NSObject, UNUserNotificationCenterDelegate { + var handleApplicationNotifications: Bool { + get { + return UNUserNotificationCenter.current().delegate === self + } + set { + let center = UNUserNotificationCenter.current() + + if newValue { + center.delegate = self + } else if center.delegate === self { + center.delegate = nil + } + } + } + + public weak var pushNotificationHandler: NotificationHandlerProtocol? { + didSet { + if pushNotificationHandler != nil, oldValue != nil { + CAPLog.print("Push notification handler overriding previous instance: \(String(describing: type(of: oldValue)))") + } + } + } + + public weak var localNotificationHandler: NotificationHandlerProtocol? { + didSet { + if localNotificationHandler != nil, oldValue != nil { + CAPLog.print("Local notification handler overriding previous instance: \(String(describing: type(of: oldValue)))") + } + } + } + + public func userNotificationCenter(_ center: UNUserNotificationCenter, + willPresent notification: UNNotification, + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + let presentationOptions: UNNotificationPresentationOptions? + + if notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true { + presentationOptions = pushNotificationHandler?.willPresent(notification: notification) + } else { + presentationOptions = localNotificationHandler?.willPresent(notification: notification) + } + + completionHandler(presentationOptions ?? []) + } + + public func userNotificationCenter(_ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void) { + if response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true { + pushNotificationHandler?.didReceive(response: response) + } else { + localNotificationHandler?.didReceive(response: response) + } + + completionHandler() + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/PluginCallResult.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/PluginCallResult.swift new file mode 100644 index 0000000..a426bbc --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/PluginCallResult.swift @@ -0,0 +1,106 @@ +import Foundation + +public typealias PluginCallResultData = [String: Any] + +public enum PluginCallResult { + case dictionary(PluginCallResultData) + + enum SerializationError: Error { + case invalidObject + } + + func jsonRepresentation(includingFields: PluginCallResultData? = nil) throws -> String? { + switch self { + case .dictionary(var dictionary): + if let fields = includingFields { + dictionary.merge(fields) { (current, _) in current } + } + dictionary = prepare(dictionary: dictionary) + guard JSONSerialization.isValidJSONObject(dictionary) else { + throw SerializationError.invalidObject + } + let data = try JSONSerialization.data(withJSONObject: dictionary, options: []) + return String(data: data, encoding: .utf8) + } + } + + private static let formatter = ISO8601DateFormatter() + + private func prepare(dictionary: PluginCallResultData) -> PluginCallResultData { + return dictionary.mapValues { (value) -> Any in + if let date = value as? Date { + return PluginCallResult.formatter.string(from: date) + } else if let aDictionary = value as? PluginCallResultData { + return prepare(dictionary: aDictionary) + } else if let anArray = value as? [Any] { + return prepare(array: anArray) + } + return value + } + } + + private func prepare(array: [Any]) -> [Any] { + return array.map { (value) -> Any in + if let date = value as? Date { + return PluginCallResult.formatter.string(from: date) + } else if let aDictionary = value as? PluginCallResultData { + return prepare(dictionary: aDictionary) + } else if let anArray = value as? [Any] { + return prepare(array: anArray) + } + return value + } + } +} + +@objc public class CAPPluginCallResult: NSObject { + public let resultData: PluginCallResult? + + @objc public var data: PluginCallResultData? { + guard let result = resultData else { + return nil + } + switch result { + case .dictionary(let data): + return data + } + } + + @objc(init:) + public init(_ data: PluginCallResultData?) { + if let data = data { + resultData = .dictionary(data) + } else { + resultData = nil + } + } +} + +@objc public class CAPPluginCallError: NSObject { + @objc public let message: String + @objc public let code: String? + @objc public let error: Error? + public let resultData: PluginCallResult? + + @objc public var data: PluginCallResultData? { + guard let result = resultData else { + return nil + } + switch result { + case .dictionary(let data): + return data + } + } + + @objc(init:code:error:data:) + public init(message: String, code: String?, error: Error?, data: PluginCallResultData?) { + self.message = message + self.code = code + self.error = error + if let data = data { + resultData = .dictionary(["data": data]) + } else { + resultData = nil + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/PluginConfig.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/PluginConfig.swift new file mode 100644 index 0000000..f2461e1 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/PluginConfig.swift @@ -0,0 +1,56 @@ +import Foundation + +@objc public class PluginConfig: NSObject { + + // The object containing the plugin config values + private var config: JSObject + + init(config: JSObject) { + self.config = config + } + + @objc public func getString(_ configKey: String, _ defaultValue: String? = nil) -> String? { + if let val = (self.config)[keyPath: KeyPath(configKey)] as? String { + return val + } + return defaultValue + } + + @objc public func getBoolean(_ configKey: String, _ defaultValue: Bool) -> Bool { + if let val = (self.config)[keyPath: KeyPath(configKey)] as? Bool { + return val + } + return defaultValue + } + + @objc public func getInt(_ configKey: String, _ defaultValue: Int) -> Int { + if let val = (self.config)[keyPath: KeyPath(configKey)] as? Int { + return val + } + return defaultValue + } + + public func getArray(_ configKey: String, _ defaultValue: JSArray? = nil) -> JSArray? { + if let val = (self.config)[keyPath: KeyPath(configKey)] as? JSArray { + return val + } + return defaultValue + } + + public func getObject(_ configKey: String) -> JSObject? { + return (self.config)[keyPath: KeyPath(configKey)] as? JSObject + } + + @objc public func isEmpty() -> Bool { + return self.config.isEmpty + } + + /** + * Gets the JSObject containing the config of the the provided plugin ID. + * + * @return The config for that plugin + */ + public func getConfigJSON() -> JSObject { + return self.config + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorCookieManager.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorCookieManager.swift new file mode 100644 index 0000000..782c245 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorCookieManager.swift @@ -0,0 +1,141 @@ +import Foundation + +public class CapacitorWKCookieObserver: NSObject, WKHTTPCookieStoreObserver { + // Sync WKWebView Cookies to HTTPCookieStorage + public func cookiesDidChange(in cookieStore: WKHTTPCookieStore) { + DispatchQueue.main.async { + cookieStore.getAllCookies { cookies in + cookies.forEach { cookie in + HTTPCookieStorage.shared.setCookie(cookie) + } + } + } + } +} + +public class CapacitorCookieManager { + var config: InstanceConfiguration? + + init(_ capConfig: InstanceConfiguration?) { + self.config = capConfig + } + + public func getServerUrl() -> URL? { + return self.config?.serverURL ?? self.config?.localURL + } + + private func isUrlSanitized(_ urlString: String) -> Bool { + return urlString.isEmpty || urlString == getServerUrl()?.absoluteString || urlString.hasPrefix("http://") || urlString.hasPrefix("https://") + } + + public func getServerUrl(_ urlString: String?) -> URL? { + guard let urlString = urlString else { + return getServerUrl() + } + + if urlString.isEmpty { + return getServerUrl() + } + + let validUrlString = (isUrlSanitized(urlString)) ? urlString : "http://\(urlString)" + + guard let url = URL(string: validUrlString) else { + return getServerUrl() + } + + return url + } + + public func encode(_ value: String) -> String { + return value.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)! + } + + public func decode(_ value: String) -> String { + return value.removingPercentEncoding! + } + + public func setCookie(_ domain: String, _ action: String) { + let url = getServerUrl(domain)! + let jar = HTTPCookieStorage.shared + let field = ["Set-Cookie": action] + let cookies = HTTPCookie.cookies(withResponseHeaderFields: field, for: url) + jar.setCookies(cookies, for: url, mainDocumentURL: nil) + syncCookiesToWebView() + } + + public func setCookie(_ url: URL, _ key: String, _ value: String, _ expires: String?, _ path: String?) { + let jar = HTTPCookieStorage.shared + let field = ["Set-Cookie": "\(key)=\(value); expires=\(expires ?? ""); path=\(path ?? "/")"] + let cookies = HTTPCookie.cookies(withResponseHeaderFields: field, for: url) + jar.setCookies(cookies, for: url, mainDocumentURL: nil) + syncCookiesToWebView() + } + + public func getCookiesAsMap(_ url: URL) -> [String: String] { + syncCookiesToWebView() + var cookiesMap: [String: String] = [:] + let jar = HTTPCookieStorage.shared + if let cookies = jar.cookies(for: url) { + for cookie in cookies { + if !cookie.isHTTPOnly { + cookiesMap[cookie.name] = cookie.value + } + } + } + return cookiesMap + } + + public func getCookies() -> String { + syncCookiesToWebView() + let jar = HTTPCookieStorage.shared + guard let url = self.getServerUrl() else { return "" } + guard let cookies = jar.cookies(for: url) else { return "" } + let filteredCookies = cookies.filter { !$0.isHTTPOnly } + return filteredCookies.map({"\($0.name)=\($0.value)"}).joined(separator: "; ") + } + + public func deleteCookie(_ url: URL, _ key: String) { + let jar = HTTPCookieStorage.shared + if let cookie = jar.cookies(for: url)?.first(where: { (cookie) -> Bool in + return cookie.name == key + }) { + jar.deleteCookie(cookie) + DispatchQueue.main.async { + WKWebsiteDataStore.default().httpCookieStore.delete(cookie) + } + } + } + + public func clearCookies(_ url: URL) { + let jar = HTTPCookieStorage.shared + jar.cookies(for: url)?.forEach({ (cookie) in + jar.deleteCookie(cookie) + DispatchQueue.main.async { + WKWebsiteDataStore.default().httpCookieStore.delete(cookie) + } + }) + } + + public func clearAllCookies() { + let jar = HTTPCookieStorage.shared + jar.cookies?.forEach({ (cookie) in + jar.deleteCookie(cookie) + DispatchQueue.main.async { + WKWebsiteDataStore.default().httpCookieStore.delete(cookie) + } + }) + } + + public func syncCookiesToWebView() { + if let cookies = HTTPCookieStorage.shared.cookies { + for cookie in cookies { + DispatchQueue.main.async { + WKWebsiteDataStore.default() + .httpCookieStore + .setCookie(cookie, completionHandler: nil) + } + + } + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorCookies.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorCookies.swift new file mode 100644 index 0000000..fa01c0c --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorCookies.swift @@ -0,0 +1,47 @@ +import Foundation + +@objc(CAPCookiesPlugin) +public class CAPCookiesPlugin: CAPPlugin { + var cookieManager: CapacitorCookieManager? + + @objc override public func load() { + cookieManager = CapacitorCookieManager(bridge?.config) + } + + @objc func getCookies(_ call: CAPPluginCall) { + guard let url = cookieManager!.getServerUrl(call.getString("url")) else { return call.reject("Invalid URL / Server URL")} + call.resolve(cookieManager!.getCookiesAsMap(url)) + } + + @objc func setCookie(_ call: CAPPluginCall) { + guard let key = call.getString("key") else { return call.reject("Must provide key") } + guard let value = call.getString("value") else { return call.reject("Must provide value") } + + guard let url = cookieManager!.getServerUrl(call.getString("url")) else { return call.reject("Invalid domain") } + + let expires = call.getString("expires", "") + let path = call.getString("path", "") + cookieManager!.setCookie(url, key, cookieManager!.encode(value), expires, path) + call.resolve() + } + + @objc func deleteCookie(_ call: CAPPluginCall) { + guard let key = call.getString("key") else { return call.reject("Must provide key") } + guard let url = cookieManager!.getServerUrl(call.getString("url")) else { return call.reject("Invalid URL / Server URL")} + cookieManager!.deleteCookie(url, key) + call.resolve() + } + + @objc func clearCookies(_ call: CAPPluginCall) { + let url = cookieManager!.getServerUrl(call.getString("url")) + if url != nil { + cookieManager!.clearCookies(url!) + call.resolve() + } + } + + @objc func clearAllCookies(_ call: CAPPluginCall) { + cookieManager!.clearAllCookies() + call.resolve() + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorHttp.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorHttp.swift new file mode 100644 index 0000000..c100a73 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorHttp.swift @@ -0,0 +1,46 @@ +import Foundation + +@objc(CAPHttpPlugin) +public class CAPHttpPlugin: CAPPlugin { + @objc func http(_ call: CAPPluginCall, _ httpMethod: String?) { + do { + if let clazz = NSClassFromString("SSLPinningHttpRequestHandlerClass") { + // swiftlint:disable force_cast + (clazz as! NSObject.Type).perform(#selector(self.request(_:)), with: [ + "call": call, + "httpMethod": httpMethod as Any, + "config": self.bridge?.config as Any + ]) + // swiftlint:enable force_cast + } else { + try HttpRequestHandler.request(call, httpMethod, self.bridge?.config) + } + } catch let error { + call.reject(error.localizedDescription) + } + } + + @objc func request(_ call: CAPPluginCall) { + http(call, nil) + } + + @objc func get(_ call: CAPPluginCall) { + http(call, "GET") + } + + @objc func post(_ call: CAPPluginCall) { + http(call, "POST") + } + + @objc func put(_ call: CAPPluginCall) { + http(call, "PUT") + } + + @objc func patch(_ call: CAPPluginCall) { + http(call, "PATCH") + } + + @objc func delete(_ call: CAPPluginCall) { + http(call, "DELETE") + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorUrlRequest.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorUrlRequest.swift new file mode 100644 index 0000000..51331e3 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/CapacitorUrlRequest.swift @@ -0,0 +1,219 @@ +import Foundation + +open class CapacitorUrlRequest: NSObject, URLSessionTaskDelegate { + public var request: URLRequest + public var headers: [String: String] + + public enum CapacitorUrlRequestError: Error { + case serializationError(String?) + } + + public init(_ url: URL, method: String) { + request = URLRequest(url: url) + request.httpMethod = method + headers = [:] + if let lang = Locale.autoupdatingCurrent.languageCode { + if let country = Locale.autoupdatingCurrent.regionCode { + headers["Accept-Language"] = "\(lang)-\(country),\(lang);q=0.5" + } else { + headers["Accept-Language"] = "\(lang);q=0.5" + } + request.addValue(headers["Accept-Language"]!, forHTTPHeaderField: "Accept-Language") + } + } + + public func getRequestDataAsJson(_ data: JSValue) throws -> Data? { + // We need to check if the JSON is valid before attempting to serialize, as JSONSerialization.data will not throw an exception that can be caught, and will cause the application to crash if it fails. + if JSONSerialization.isValidJSONObject(data) { + return try JSONSerialization.data(withJSONObject: data) + } else { + throw CapacitorUrlRequest.CapacitorUrlRequestError.serializationError("[ data ] argument for request of content-type [ application/json ] must be serializable to JSON") + } + } + + public func getRequestDataAsFormUrlEncoded(_ data: JSValue) throws -> Data? { + guard var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false) else { return nil } + components.queryItems = [] + + guard let obj = data as? JSObject else { + // Throw, other data types explicitly not supported + throw CapacitorUrlRequestError.serializationError("[ data ] argument for request with content-type [ multipart/form-data ] may only be a plain javascript object") + } + + obj.keys.forEach { (key: String) in + components.queryItems?.append(URLQueryItem(name: key, value: "\(obj[key] ?? "")")) + } + + if components.query != nil { + return Data(components.query!.utf8) + } + + return nil + } + + public func getRequestDataAsMultipartFormData(_ data: JSValue) throws -> Data { + guard let obj = data as? JSObject else { + // Throw, other data types explicitly not supported. + throw CapacitorUrlRequestError.serializationError("[ data ] argument for request with content-type [ application/x-www-form-urlencoded ] may only be a plain javascript object") + } + + let strings: [String: String] = obj.compactMapValues { any in + any as? String + } + + var data = Data() + let boundary = UUID().uuidString + let contentType = "multipart/form-data; boundary=\(boundary)" + request.setValue(contentType, forHTTPHeaderField: "Content-Type") + headers["Content-Type"] = contentType + + strings.forEach { key, value in + data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) + data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!) + data.append(value.data(using: .utf8)!) + } + data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) + + return data + } + + public func getRequestDataAsString(_ data: JSValue) throws -> Data { + guard let stringData = data as? String else { + throw CapacitorUrlRequestError.serializationError("[ data ] argument could not be parsed as string") + } + return Data(stringData.utf8) + } + + public func getRequestHeader(_ index: String) -> Any? { + var normalized = [:] as [String: Any] + self.headers.keys.forEach { (key: String) in + normalized[key.lowercased()] = self.headers[key] + } + + return normalized[index.lowercased()] + } + + func getRequestDataFromFormData(_ data: JSValue) throws -> Data? { + guard let list = data as? JSArray else { + // Throw, other data types explicitly not supported. + throw CapacitorUrlRequestError.serializationError("Data must be an array for FormData") + } + + var data = Data() + + // Update the contentType with the new boundary + let boundary = UUID().uuidString + let contentType = "multipart/form-data; boundary=\(boundary)" + request.setValue(contentType, forHTTPHeaderField: "Content-Type") + headers["Content-Type"] = contentType + + for entry in list { + guard let item = entry as? [String: String] else { + throw CapacitorUrlRequestError.serializationError("Data must be an array for FormData") + } + + let type = item["type"] + let key = item["key"] + let value = item["value"]! + + if type == "base64File" { + let fileName = item["fileName"] + let fileContentType = item["contentType"] + + data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) + data.append("Content-Disposition: form-data; name=\"\(key!)\"; filename=\"\(fileName!)\"\r\n".data(using: .utf8)!) + data.append("Content-Type: \(fileContentType!)\r\n".data(using: .utf8)!) + data.append("Content-Transfer-Encoding: binary\r\n".data(using: .utf8)!) + data.append("\r\n".data(using: .utf8)!) + + data.append(Data(base64Encoded: value)!) + + data.append("\r\n".data(using: .utf8)!) + } else if type == "string" { + data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) + data.append("Content-Disposition: form-data; name=\"\(key!)\"\r\n".data(using: .utf8)!) + data.append("\r\n".data(using: .utf8)!) + data.append(value.data(using: .utf8)!) + data.append("\r\n".data(using: .utf8)!) + } + + } + + data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) + + return data + } + + public func getRequestData(_ body: JSValue, _ contentType: String, _ dataType: String? = nil) throws -> Data? { + if dataType == "file" { + guard let stringData = body as? String else { + throw CapacitorUrlRequestError.serializationError("[ data ] argument could not be parsed as string") + } + return Data(base64Encoded: stringData) + } else if dataType == "formData" { + return try getRequestDataFromFormData(body) + } + + // If data can be parsed directly as a string, return that without processing. + if let strVal = try? getRequestDataAsString(body) { + return strVal + } else if contentType.contains("application/json") { + return try getRequestDataAsJson(body) + } else if contentType.contains("application/x-www-form-urlencoded") { + return try getRequestDataAsFormUrlEncoded(body) + } else if contentType.contains("multipart/form-data") { + return try getRequestDataAsMultipartFormData(body) + } else { + throw CapacitorUrlRequestError.serializationError("[ data ] argument could not be parsed for content type [ \(contentType) ]") + } + } + + @available(*, deprecated, message: "Use newer function with passed headers of type [String: Any]") + public func setRequestHeaders(_ headers: [String: String]) { + headers.keys.forEach { (key: String) in + let value = headers[key] + request.addValue(value!, forHTTPHeaderField: key) + self.headers[key] = value + } + } + + public func setRequestHeaders(_ headers: [String: Any]) { + headers.keys.forEach { (key: String) in + let value = headers[key] + request.setValue("\(value!)", forHTTPHeaderField: key) + self.headers[key] = "\(value!)" + } + } + + public func setRequestBody(_ body: JSValue, _ dataType: String? = nil) throws { + let contentType = self.getRequestHeader("Content-Type") as? String + + if contentType != nil { + request.httpBody = try getRequestData(body, contentType!, dataType) + } + } + + public func setContentType(_ data: String?) { + request.setValue(data, forHTTPHeaderField: "Content-Type") + } + + public func setTimeout(_ timeout: TimeInterval) { + request.timeoutInterval = timeout + } + + public func getUrlRequest() -> URLRequest { + return request + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { + completionHandler(nil) + } + + open func getUrlSession(_ call: CAPPluginCall) -> URLSession { + let disableRedirects = call.getBool("disableRedirects") ?? false + if !disableRedirects { + return URLSession.shared + } + return URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/Console.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/Console.swift new file mode 100644 index 0000000..0bd2ecb --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/Console.swift @@ -0,0 +1,11 @@ +import Foundation + +@objc(CAPConsolePlugin) +public class CAPConsolePlugin: CAPPlugin { + + @objc public func log(_ call: CAPPluginCall) { + let message = call.getString("message") ?? "" + let level = call.getString("level") ?? "log" + CAPLog.print("⚡️ [\(level)] - \(message)") + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/DefaultPlugins.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/DefaultPlugins.m new file mode 100644 index 0000000..55c06d1 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/DefaultPlugins.m @@ -0,0 +1,31 @@ +#import + +#import "CAPBridgedPlugin.h" + +CAP_PLUGIN(CAPCookiesPlugin, "CapacitorCookies", + CAP_PLUGIN_METHOD(getCookies, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(setCookie, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(deleteCookie, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(clearCookies, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(clearAllCookies, CAPPluginReturnPromise); +) + +CAP_PLUGIN(CAPHttpPlugin, "CapacitorHttp", + CAP_PLUGIN_METHOD(request, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(get, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(post, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(put, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(patch, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(delete, CAPPluginReturnPromise); +) + +CAP_PLUGIN(CAPConsolePlugin, "Console", + CAP_PLUGIN_METHOD(log, CAPPluginReturnNone); +) + +CAP_PLUGIN(CAPWebViewPlugin, "WebView", + CAP_PLUGIN_METHOD(setServerAssetPath, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(setServerBasePath, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(getServerBasePath, CAPPluginReturnPromise); + CAP_PLUGIN_METHOD(persistServerBasePath, CAPPluginReturnPromise); +) diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/HttpRequestHandler.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/HttpRequestHandler.swift new file mode 100644 index 0000000..ea990d3 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/HttpRequestHandler.swift @@ -0,0 +1,203 @@ +import Foundation + +/// See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType +public enum ResponseType: String { + case arrayBuffer = "arraybuffer" + case blob = "blob" + case document = "document" + case json = "json" + case text = "text" + + public static let `default`: ResponseType = .text + + public init(string: String?) { + guard let string = string else { + self = .default + return + } + + guard let responseType = ResponseType(rawValue: string.lowercased()) else { + self = .default + return + } + + self = responseType + } +} + +/// Helper that safely parses JSON Data. Otherwise returns an error (without throwing) +/// - Parameters: +/// - data: The JSON Data to parse +/// - Returns: The parsed value or an error +func tryParseJson(_ data: Data) -> Any { + do { + return try JSONSerialization.jsonObject(with: data, options: [.mutableContainers, .fragmentsAllowed]) + } catch { + return error.localizedDescription + } +} + +open class HttpRequestHandler { + open class CapacitorHttpRequestBuilder { + public var url: URL? + public var method: String? + public var params: [String: String]? + open var request: CapacitorUrlRequest? + + public init() { } + + /// Set the URL of the HttpRequest + /// - Throws: an error of URLError if the urlString cannot be parsed + /// - Parameters: + /// - urlString: The URL value to parse + /// - Returns: self to continue chaining functions + public func setUrl(_ urlString: String) throws -> CapacitorHttpRequestBuilder { + guard let url = URL(string: urlString) else { + throw URLError(.badURL) + } + self.url = url + return self + } + + public func setMethod(_ method: String) -> CapacitorHttpRequestBuilder { + self.method = method + return self + } + + public func setUrlParams(_ params: [String: Any]) -> CapacitorHttpRequestBuilder { + if params.count != 0 { + // swiftlint:disable force_cast + var cmps = URLComponents(url: url!, resolvingAgainstBaseURL: true) + if cmps?.queryItems == nil { + cmps?.queryItems = [] + } + + var urlSafeParams: [URLQueryItem] = [] + for (key, value) in params { + if let arr = value as? [String] { + arr.forEach { str in + urlSafeParams.append(URLQueryItem(name: key, value: str)) + } + } else { + urlSafeParams.append(URLQueryItem(name: key, value: (value as! String))) + } + } + + cmps!.queryItems?.append(contentsOf: urlSafeParams) + url = cmps!.url! + } + return self + } + + open func openConnection() -> CapacitorHttpRequestBuilder { + request = CapacitorUrlRequest(url!, method: method!) + return self + } + + public func build() -> CapacitorUrlRequest { + return request! + } + } + + public static func setCookiesFromResponse(_ response: HTTPURLResponse, _ config: InstanceConfiguration?) { + let headers = response.allHeaderFields + if let cookies = headers["Set-Cookie"] as? String { + for cookie in cookies.components(separatedBy: ",") { + let domainComponents = cookie.lowercased().components(separatedBy: "domain=") + if domainComponents.count > 1 { + CapacitorCookieManager(config).setCookie( + domainComponents[1].components(separatedBy: ";")[0], + cookie + ) + } else { + CapacitorCookieManager(config).setCookie("", cookie) + } + } + } + CapacitorCookieManager(config).syncCookiesToWebView() + } + + public static func buildResponse(_ data: Data?, _ response: HTTPURLResponse, responseType: ResponseType = .default) -> [String: Any] { + var output = [:] as [String: Any] + + output["status"] = response.statusCode + output["headers"] = response.allHeaderFields + output["url"] = response.url?.absoluteString + + guard let data = data else { + output["data"] = "" + return output + } + + let contentType = (response.allHeaderFields["Content-Type"] as? String ?? "application/default").lowercased() + + if contentType.contains("application/json") || responseType == .json { + output["data"] = tryParseJson(data) + } else if responseType == .arrayBuffer || responseType == .blob { + output["data"] = data.base64EncodedString() + } else if responseType == .document || responseType == .text || responseType == .default { + output["data"] = String(data: data, encoding: .utf8) + } + + return output + } + + public static func request(_ call: CAPPluginCall, _ httpMethod: String?, _ config: InstanceConfiguration?) throws { + guard var urlString = call.getString("url") else { throw URLError(.badURL) } + let method = httpMethod ?? call.getString("method", "GET") + + let headers = (call.getObject("headers") ?? [:]) as [String: Any] + let params = (call.getObject("params") ?? [:]) as [String: Any] + let responseType = call.getString("responseType") ?? "text" + let connectTimeout = call.getDouble("connectTimeout") + let readTimeout = call.getDouble("readTimeout") + let dataType = call.getString("dataType") ?? "any" + + if urlString == urlString.removingPercentEncoding { + guard let encodedUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { throw URLError(.badURL) } + urlString = encodedUrlString + } + + let request = try CapacitorHttpRequestBuilder() + .setUrl(urlString) + .setMethod(method) + .setUrlParams(params) + .openConnection() + .build() + + request.setRequestHeaders(headers) + + // Timeouts in iOS are in seconds. So read the value in millis and divide by 1000 + let timeout = (connectTimeout ?? readTimeout ?? 600000.0) / 1000.0 + request.setTimeout(timeout) + + if let data = call.options["data"] as? JSValue { + do { + try request.setRequestBody(data, dataType) + } catch { + // Explicitly reject if the http request body was not set successfully, + // so as to not send a known malformed request, and to provide the developer with additional context. + call.reject(error.localizedDescription, (error as NSError).domain, error, nil) + return + } + } + + let urlRequest = request.getUrlRequest() + let urlSession = request.getUrlSession(call) + let task = urlSession.dataTask(with: urlRequest) { (data, response, error) in + urlSession.invalidateAndCancel() + + if let error = error { + call.reject(error.localizedDescription, (error as NSError).domain, error, nil) + return + } + + setCookiesFromResponse(response as! HTTPURLResponse, config) + + let type = ResponseType(rawValue: responseType) ?? .default + call.resolve(self.buildResponse(data, response as! HTTPURLResponse, responseType: type)) + } + + task.resume() + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/WebView.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/WebView.swift new file mode 100644 index 0000000..3ad1da9 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Plugins/WebView.swift @@ -0,0 +1,37 @@ +import Foundation + +@objc(CAPWebViewPlugin) +public class CAPWebViewPlugin: CAPPlugin { + + @objc func setServerAssetPath(_ call: CAPPluginCall) { + if let path = call.getString("path"), let viewController = bridge?.viewController as? CAPBridgeViewController { + viewController.setServerBasePath(path: Bundle.main.url(forResource: path, withExtension: nil)?.path ?? path) + call.resolve() + } + } + + @objc func setServerBasePath(_ call: CAPPluginCall) { + if let path = call.getString("path"), let viewController = bridge?.viewController as? CAPBridgeViewController { + viewController.setServerBasePath(path: path) + call.resolve() + } + } + + @objc func getServerBasePath(_ call: CAPPluginCall) { + if let viewController = bridge?.viewController as? CAPBridgeViewController { + let path = viewController.getServerBasePath() + call.resolve([ + "path": path + ]) + } + } + + @objc func persistServerBasePath(_ call: CAPPluginCall) { + if let viewController = bridge?.viewController as? CAPBridgeViewController { + let path = viewController.getServerBasePath() + let defaults = UserDefaults.standard + defaults.set(path, forKey: "serverBasePath") + call.resolve() + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/PrivacyInfo.xcprivacy b/node_modules/@capacitor/ios/Capacitor/Capacitor/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..7d994bc --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/PrivacyInfo.xcprivacy @@ -0,0 +1,23 @@ + + + + + NSPrivacyCollectedDataTypes + + NSPrivacyTrackingDomains + + NSPrivacyTracking + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/Router.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/Router.swift new file mode 100644 index 0000000..c5e9ebb --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/Router.swift @@ -0,0 +1,29 @@ +// +// Router.swift +// Capacitor +// +// Created by Steven Sherry on 3/29/22. +// Copyright © 2022 Drifty Co. All rights reserved. +// + +import Foundation + +public protocol Router { + func route(for path: String) -> String + var basePath: String { get set } +} + +// swiftlint:disable:next type_name +internal struct _Router: Router { + var basePath: String = "" + func route(for path: String) -> String { + let pathUrl = URL(fileURLWithPath: path) + + // If there's no path extension it also means the path is empty or a SPA route + if pathUrl.pathExtension.isEmpty { + return basePath + "/index.html" + } + + return basePath + path + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/TmpViewController.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/TmpViewController.swift new file mode 100644 index 0000000..3511d18 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/TmpViewController.swift @@ -0,0 +1,8 @@ +import UIKit + +internal class TmpViewController: UIViewController { + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + NotificationCenter.default.post(CapacitorBridge.tmpVCAppeared) + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/UIColor.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/UIColor.swift new file mode 100644 index 0000000..b33bd3d --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/UIColor.swift @@ -0,0 +1,55 @@ +extension UIColor: CapacitorExtension {} +public extension CapacitorExtensionTypeWrapper where T: UIColor { + // disable linting for the short variable names, since that's the point of the method + // swiftlint:disable:next identifier_name + static func color(r: Int, g: Int, b: Int, a: Int = 0xFF) -> UIColor { + return T( + red: CGFloat(r) / 255.0, + green: CGFloat(g) / 255.0, + blue: CGFloat(b) / 255.0, + alpha: CGFloat(a) / 255.0 + ) + } + + static func color(argb: UInt32) -> UIColor { + return T( + red: CGFloat((argb >> 16) & 0xFF), + green: CGFloat((argb >> 8) & 0xFF), + blue: CGFloat(argb & 0xFF), + alpha: CGFloat((argb >> 24) & 0xFF) + ) + } + + static func color(fromHex: String) -> UIColor? { + let hexString = fromHex.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences( + of: "#", + with: "" + ) + + var argb: UInt64 = 0 + + var red: CGFloat = 0.0 + var green: CGFloat = 0.0 + var blue: CGFloat = 0.0 + var alpha: CGFloat = 1.0 + + guard Scanner(string: hexString).scanHexInt64(&argb) else { return nil } + + if hexString.count == 6 { + red = CGFloat((argb & 0xFF0000) >> 16) / 255.0 + green = CGFloat((argb & 0x00FF00) >> 8) / 255.0 + blue = CGFloat(argb & 0x0000FF) / 255.0 + + } else if hexString.count == 8 { + red = CGFloat((argb & 0xFF00_0000) >> 24) / 255.0 + green = CGFloat((argb & 0x00FF0000) >> 16) / 255.0 + blue = CGFloat((argb & 0x0000FF00) >> 8) / 255.0 + alpha = CGFloat(argb & 0x000000FF) / 255.0 + + } else { + return nil + } + + return T(red: red, green: green, blue: blue, alpha: alpha) + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/UIStatusBarManager+CAPHandleTapAction.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/UIStatusBarManager+CAPHandleTapAction.m new file mode 100644 index 0000000..44272a3 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/UIStatusBarManager+CAPHandleTapAction.m @@ -0,0 +1,37 @@ +#import +#import +#import + +@implementation UIStatusBarManager (CAPHandleTapAction) + ++ (void)load { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class class = [self class]; + SEL originalSelector = NSSelectorFromString(@"handleTapAction:"); + SEL swizzledSelector = @selector(nofity_handleTapAction:); + + Method originalMethod = class_getInstanceMethod(class, originalSelector); + Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); + + BOOL didAddMethod = class_addMethod(class, + originalSelector, + method_getImplementation(swizzledMethod), + method_getTypeEncoding(swizzledMethod)); + if (didAddMethod) { + class_replaceMethod(class, + swizzledSelector, + method_getImplementation(originalMethod), + method_getTypeEncoding(originalMethod)); + } else { + method_exchangeImplementations(originalMethod, swizzledMethod); + } + }); +} + +-(void)nofity_handleTapAction:(id)arg1 { + [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:NSNotification.capacitorStatusBarTapped object:nil]]; + [self nofity_handleTapAction:arg1]; +} + +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.h b/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.h new file mode 100644 index 0000000..c4f7d54 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.h @@ -0,0 +1,11 @@ +@import UIKit; +@import WebKit; + +#ifndef WKWebView_Capacitor_h +#define WKWebView_Capacitor_h + +@interface WKWebView (CapacitorInspectablity) +- (void)setInspectableIfRequired: (BOOL)shouldInspect; +@end + +#endif /* WKWebView_Capacitor_h */ diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.m b/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.m new file mode 100644 index 0000000..3ac58e0 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.m @@ -0,0 +1,28 @@ +#import +#import + +// Swift extensions marked as @objc and internal are available to the runtime but won't be found at compile time +// so we need this declaration to avoid compiler complaints. +@interface WKWebView (InternalSwiftExtension) ++ (void)_swizzleKeyboardMethods; +@end + +// +load is the safest place to swizzle methods but that won't work from a swift extension so we need this wrapper. +@implementation WKWebView (CapacitorAutoFocus) ++ (void)load { + [self _swizzleKeyboardMethods]; +} +@end + +// TODO: Remove this after Xcode 14.3 is required +@implementation WKWebView (CapacitorInspectablity) + +- (void)setInspectableIfRequired: (BOOL)shouldInspect { + #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 160400 + if (@available(iOS 16.4, *)) { + self.inspectable = shouldInspect; + } + #endif +} + +@end diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.swift new file mode 100644 index 0000000..ec8bc17 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/WKWebView+Capacitor.swift @@ -0,0 +1,114 @@ +import Foundation +import WebKit + +extension WKWebView: CapacitorExtension {} +public extension CapacitorExtensionTypeWrapper where T == WKWebView { + var keyboardShouldRequireUserInteraction: Bool? { + return (self.baseType.associatedKeyboardFlagValue as? NSNumber)?.boolValue + } + + // the readonly nature of the wrapper extension means we can't use a computed property with a setter + func setKeyboardShouldRequireUserInteraction(_ flag: Bool? = nil) { + if let flag = flag { + self.baseType.associatedKeyboardFlagValue = NSNumber(value: flag) + } else { + self.baseType.associatedKeyboardFlagValue = nil + } + } +} + +private var associatedKeyboardFlagHandle: UInt8 = 0 + +internal extension WKWebView { + // Our lazy property can't be represented in Obj-C so we need this simple wrapper. + // swiftlint:disable identifier_name + @objc static func _swizzleKeyboardMethods() { + _ = oneTimeOnlySwizzle + } + + typealias FourArgClosureType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Any?) -> Void + typealias FiveArgClosureType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void + + // dispatch_once isn't available in Swift, but lazy properties use the same mechanism under the hood so + // we can safely assume that this block of code will only execute once. + static let oneTimeOnlySwizzle: () = { + let frameworkName = "WK" + let className = "ContentView" + guard let targetClass = NSClassFromString(frameworkName + className) else { + return + } + + let containingWebView = { (object: Any?) -> WKWebView? in + var view = object as? UIView + while view != nil { + if let webview = view as? WKWebView { + return webview + } + view = view?.superview + } + return nil + } + + let swizzleFourArgClosure = { (method: Method, selector: Selector) in + let originalImp: IMP = method_getImplementation(method) + let original: FourArgClosureType = unsafeBitCast(originalImp, to: FourArgClosureType.self) + let block: @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3) in + if let webview = containingWebView(me), let flag = webview.capacitor.keyboardShouldRequireUserInteraction { + original(me, selector, arg0, !flag, arg2, arg3) + } else { + original(me, selector, arg0, arg1, arg2, arg3) + } + } + let imp: IMP = imp_implementationWithBlock(block) + method_setImplementation(method, imp) + } + + let swizzleFiveArgClosure = { (method: Method, selector: Selector) in + let originalImp: IMP = method_getImplementation(method) + let original: FiveArgClosureType = unsafeBitCast(originalImp, to: FiveArgClosureType.self) + let block: @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3, arg4) in + if let webview = containingWebView(me), let flag = webview.capacitor.keyboardShouldRequireUserInteraction { + original(me, selector, arg0, !flag, arg2, arg3, arg4) + } else { + original(me, selector, arg0, arg1, arg2, arg3, arg4) + } + } + let imp: IMP = imp_implementationWithBlock(block) + method_setImplementation(method, imp) + } + + // older + let selectorMkI: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:") + // iOS 11.3 + let selectorMkII: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:") + // iOS 12.2 + let selectorMkIII: Selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:") + // iOS 13 + let selectorMkIV: Selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:") + + if let method = class_getInstanceMethod(targetClass, selectorMkI) { + swizzleFourArgClosure(method, selectorMkI) + } + + if let method = class_getInstanceMethod(targetClass, selectorMkII) { + swizzleFiveArgClosure(method, selectorMkII) + } + + if let method = class_getInstanceMethod(targetClass, selectorMkIII) { + swizzleFiveArgClosure(method, selectorMkIII) + } + + if let method = class_getInstanceMethod(targetClass, selectorMkIV) { + swizzleFiveArgClosure(method, selectorMkIV) + } + }() + + var associatedKeyboardFlagValue: Any? { + get { + return objc_getAssociatedObject(self, &associatedKeyboardFlagHandle) + } + set { + objc_setAssociatedObject(self, &associatedKeyboardFlagHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/WebViewAssetHandler.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/WebViewAssetHandler.swift new file mode 100644 index 0000000..4dbaeb9 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/WebViewAssetHandler.swift @@ -0,0 +1,551 @@ +import Foundation +import MobileCoreServices + +@objc(CAPWebViewAssetHandler) +// swiftlint:disable type_body_length +internal class WebViewAssetHandler: NSObject, WKURLSchemeHandler { + private var router: Router + private var serverUrl: URL? + + init(router: Router) { + self.router = router + super.init() + } + + func setAssetPath(_ assetPath: String) { + router.basePath = assetPath + } + + func setServerUrl(_ serverUrl: URL?) { + self.serverUrl = serverUrl + } + + private func isUsingLiveReload(_ localUrl: URL) -> Bool { + return self.serverUrl != nil && self.serverUrl?.scheme != localUrl.scheme + } + + func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) { + let startPath: String + let url = urlSchemeTask.request.url! + let stringToLoad = url.path + let localUrl = URL.init(string: url.absoluteString)! + + if url.path.starts(with: CapacitorBridge.httpInterceptorStartIdentifier) { + handleCapacitorHttpRequest(urlSchemeTask, localUrl, false) + return + } + + if stringToLoad.starts(with: CapacitorBridge.fileStartIdentifier) { + startPath = stringToLoad.replacingOccurrences(of: CapacitorBridge.fileStartIdentifier, with: "") + } else { + startPath = router.route(for: stringToLoad) + } + + let fileUrl = URL.init(fileURLWithPath: startPath) + + do { + var data = Data() + let mimeType = mimeTypeForExtension(pathExtension: url.pathExtension) + var headers = [ + "Content-Type": mimeType, + "Cache-Control": "no-cache" + ] + + // if using live reload, then set CORS headers + if isUsingLiveReload(localUrl) { + headers["Access-Control-Allow-Origin"] = self.serverUrl?.absoluteString + headers["Access-Control-Allow-Methods"] = "GET, HEAD, OPTIONS, TRACE" + } + + if let rangeString = urlSchemeTask.request.value(forHTTPHeaderField: "Range"), + let totalSize = try fileUrl.resourceValues(forKeys: [.fileSizeKey]).fileSize, + isMediaExtension(pathExtension: url.pathExtension) { + let fileHandle = try FileHandle(forReadingFrom: fileUrl) + let parts = rangeString.components(separatedBy: "=") + let streamParts = parts[1].components(separatedBy: "-") + let fromRange = Int(streamParts[0]) ?? 0 + var toRange = totalSize - 1 + if streamParts.count > 1 { + toRange = Int(streamParts[1]) ?? toRange + } + let rangeLength = toRange - fromRange + 1 + try fileHandle.seek(toOffset: UInt64(fromRange)) + data = fileHandle.readData(ofLength: rangeLength) + headers["Accept-Ranges"] = "bytes" + headers["Content-Range"] = "bytes \(fromRange)-\(toRange)/\(totalSize)" + headers["Content-Length"] = String(data.count) + let response = HTTPURLResponse(url: localUrl, statusCode: 206, httpVersion: nil, headerFields: headers) + urlSchemeTask.didReceive(response!) + try fileHandle.close() + } else { + if !stringToLoad.contains("cordova.js") { + if isMediaExtension(pathExtension: url.pathExtension) { + data = try Data(contentsOf: fileUrl, options: Data.ReadingOptions.mappedIfSafe) + } else { + data = try Data(contentsOf: fileUrl) + } + } + let urlResponse = URLResponse(url: localUrl, mimeType: mimeType, expectedContentLength: data.count, textEncodingName: nil) + let httpResponse = HTTPURLResponse(url: localUrl, statusCode: 200, httpVersion: nil, headerFields: headers) + if isMediaExtension(pathExtension: url.pathExtension) { + urlSchemeTask.didReceive(urlResponse) + } else { + urlSchemeTask.didReceive(httpResponse!) + } + } + urlSchemeTask.didReceive(data) + } catch let error as NSError { + urlSchemeTask.didFailWithError(error) + return + } + urlSchemeTask.didFinish() + } + + func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) { + urlSchemeTask.stopped = true + } + + func mimeTypeForExtension(pathExtension: String) -> String { + if !pathExtension.isEmpty { + if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() { + if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { + return mimetype as String + } + } + // TODO: Remove in the future if Apple fixes the issue + if let mimeType = mimeTypes[pathExtension] { + return mimeType + } + return "application/octet-stream" + } + return "text/html" + } + + func isMediaExtension(pathExtension: String) -> Bool { + let mediaExtensions = ["m4v", "mov", "mp4", + "aac", "ac3", "aiff", "au", "flac", "m4a", "mp3", "wav"] + if mediaExtensions.contains(pathExtension.lowercased()) { + return true + } + return false + } + + func handleCapacitorHttpRequest(_ urlSchemeTask: WKURLSchemeTask, _ localUrl: URL, _ isHttpsRequest: Bool) { + var urlRequest = urlSchemeTask.request + guard let url = urlRequest.url else { return } + + let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) + if let targetUrl = urlComponents?.queryItems?.first(where: { $0.name == CapacitorBridge.httpInterceptorUrlParam })?.value, + !targetUrl.isEmpty { + urlRequest.url = URL(string: targetUrl) + } + + let urlSession = URLSession.shared + let task = urlSession.dataTask(with: urlRequest) { (data, response, error) in + DispatchQueue.main.async { + guard !urlSchemeTask.stopped else { return } + if let error = error { + urlSchemeTask.didFailWithError(error) + return + } + + if let response = response as? HTTPURLResponse { + let existingHeaders = response.allHeaderFields + var newHeaders: [AnyHashable: Any] = [:] + + // if using live reload, then set CORS headers + if self.isUsingLiveReload(url) { + newHeaders = [ + "Access-Control-Allow-Origin": self.serverUrl?.absoluteString ?? "", + "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS, TRACE" + ] + } + + if let mergedHeaders = existingHeaders.merging(newHeaders, uniquingKeysWith: { (_, newHeaders) in newHeaders }) as? [String: String] { + + if let responseUrl = response.url { + if let modifiedResponse = HTTPURLResponse( + url: responseUrl, + statusCode: response.statusCode, + httpVersion: nil, + headerFields: mergedHeaders + ) { + urlSchemeTask.didReceive(modifiedResponse) + } + } + + if let data = data { + urlSchemeTask.didReceive(data) + } + } + } + urlSchemeTask.didFinish() + return + } + } + + task.resume() + } + + let mimeTypes = [ + "aaf": "application/octet-stream", + "aca": "application/octet-stream", + "accdb": "application/msaccess", + "accde": "application/msaccess", + "accdt": "application/msaccess", + "acx": "application/internet-property-stream", + "afm": "application/octet-stream", + "ai": "application/postscript", + "aif": "audio/x-aiff", + "aifc": "audio/aiff", + "aiff": "audio/aiff", + "application": "application/x-ms-application", + "art": "image/x-jg", + "asd": "application/octet-stream", + "asf": "video/x-ms-asf", + "asi": "application/octet-stream", + "asm": "text/plain", + "asr": "video/x-ms-asf", + "asx": "video/x-ms-asf", + "atom": "application/atom+xml", + "au": "audio/basic", + "avi": "video/x-msvideo", + "axs": "application/olescript", + "bas": "text/plain", + "bcpio": "application/x-bcpio", + "bin": "application/octet-stream", + "bmp": "image/bmp", + "c": "text/plain", + "cab": "application/octet-stream", + "calx": "application/vnd.ms-office.calx", + "cat": "application/vnd.ms-pki.seccat", + "cdf": "application/x-cdf", + "chm": "application/octet-stream", + "class": "application/x-java-applet", + "clp": "application/x-msclip", + "cmx": "image/x-cmx", + "cnf": "text/plain", + "cod": "image/cis-cod", + "cpio": "application/x-cpio", + "cpp": "text/plain", + "crd": "application/x-mscardfile", + "crl": "application/pkix-crl", + "crt": "application/x-x509-ca-cert", + "csh": "application/x-csh", + "css": "text/css", + "csv": "application/octet-stream", + "cur": "application/octet-stream", + "dcr": "application/x-director", + "deploy": "application/octet-stream", + "der": "application/x-x509-ca-cert", + "dib": "image/bmp", + "dir": "application/x-director", + "disco": "text/xml", + "dll": "application/x-msdownload", + "dll.config": "text/xml", + "dlm": "text/dlm", + "doc": "application/msword", + "docm": "application/vnd.ms-word.document.macroEnabled.12", + "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "dot": "application/msword", + "dotm": "application/vnd.ms-word.template.macroEnabled.12", + "dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", + "dsp": "application/octet-stream", + "dtd": "text/xml", + "dvi": "application/x-dvi", + "dwf": "drawing/x-dwf", + "dwp": "application/octet-stream", + "dxr": "application/x-director", + "eml": "message/rfc822", + "emz": "application/octet-stream", + "eot": "application/octet-stream", + "eps": "application/postscript", + "etx": "text/x-setext", + "evy": "application/envoy", + "exe": "application/octet-stream", + "exe.config": "text/xml", + "fdf": "application/vnd.fdf", + "fif": "application/fractals", + "fla": "application/octet-stream", + "flr": "x-world/x-vrml", + "flv": "video/x-flv", + "gif": "image/gif", + "gtar": "application/x-gtar", + "gz": "application/x-gzip", + "h": "text/plain", + "hdf": "application/x-hdf", + "hdml": "text/x-hdml", + "hhc": "application/x-oleobject", + "hhk": "application/octet-stream", + "hhp": "application/octet-stream", + "hlp": "application/winhlp", + "hqx": "application/mac-binhex40", + "hta": "application/hta", + "htc": "text/x-component", + "htm": "text/html", + "html": "text/html", + "htt": "text/webviewhtml", + "hxt": "text/html", + "ico": "image/x-icon", + "ics": "application/octet-stream", + "ief": "image/ief", + "iii": "application/x-iphone", + "inf": "application/octet-stream", + "ins": "application/x-internet-signup", + "isp": "application/x-internet-signup", + "IVF": "video/x-ivf", + "jar": "application/java-archive", + "java": "application/octet-stream", + "jck": "application/liquidmotion", + "jcz": "application/liquidmotion", + "jfif": "image/pjpeg", + "jpb": "application/octet-stream", + "jpe": "image/jpeg", + "jpeg": "image/jpeg", + "jpg": "image/jpeg", + "js": "application/x-javascript", + "jsx": "text/jscript", + "latex": "application/x-latex", + "lit": "application/x-ms-reader", + "lpk": "application/octet-stream", + "lsf": "video/x-la-asf", + "lsx": "video/x-la-asf", + "lzh": "application/octet-stream", + "m13": "application/x-msmediaview", + "m14": "application/x-msmediaview", + "m1v": "video/mpeg", + "m3u": "audio/x-mpegurl", + "man": "application/x-troff-man", + "manifest": "application/x-ms-manifest", + "map": "text/plain", + "mdb": "application/x-msaccess", + "mdp": "application/octet-stream", + "me": "application/x-troff-me", + "mht": "message/rfc822", + "mhtml": "message/rfc822", + "mid": "audio/mid", + "midi": "audio/mid", + "mix": "application/octet-stream", + "mmf": "application/x-smaf", + "mno": "text/xml", + "mny": "application/x-msmoney", + "mov": "video/quicktime", + "movie": "video/x-sgi-movie", + "mp2": "video/mpeg", + "mp3": "audio/mpeg", + "mpa": "video/mpeg", + "mpe": "video/mpeg", + "mpeg": "video/mpeg", + "mpg": "video/mpeg", + "mpp": "application/vnd.ms-project", + "mpv2": "video/mpeg", + "ms": "application/x-troff-ms", + "msi": "application/octet-stream", + "mso": "application/octet-stream", + "mvb": "application/x-msmediaview", + "mvc": "application/x-miva-compiled", + "nc": "application/x-netcdf", + "nsc": "video/x-ms-asf", + "nws": "message/rfc822", + "ocx": "application/octet-stream", + "oda": "application/oda", + "odc": "text/x-ms-odc", + "ods": "application/oleobject", + "one": "application/onenote", + "onea": "application/onenote", + "onetoc": "application/onenote", + "onetoc2": "application/onenote", + "onetmp": "application/onenote", + "onepkg": "application/onenote", + "osdx": "application/opensearchdescription+xml", + "p10": "application/pkcs10", + "p12": "application/x-pkcs12", + "p7b": "application/x-pkcs7-certificates", + "p7c": "application/pkcs7-mime", + "p7m": "application/pkcs7-mime", + "p7r": "application/x-pkcs7-certreqresp", + "p7s": "application/pkcs7-signature", + "pbm": "image/x-portable-bitmap", + "pcx": "application/octet-stream", + "pcz": "application/octet-stream", + "pdf": "application/pdf", + "pfb": "application/octet-stream", + "pfm": "application/octet-stream", + "pfx": "application/x-pkcs12", + "pgm": "image/x-portable-graymap", + "pko": "application/vnd.ms-pki.pko", + "pma": "application/x-perfmon", + "pmc": "application/x-perfmon", + "pml": "application/x-perfmon", + "pmr": "application/x-perfmon", + "pmw": "application/x-perfmon", + "png": "image/png", + "pnm": "image/x-portable-anymap", + "pnz": "image/png", + "pot": "application/vnd.ms-powerpoint", + "potm": "application/vnd.ms-powerpoint.template.macroEnabled.12", + "potx": "application/vnd.openxmlformats-officedocument.presentationml.template", + "ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12", + "ppm": "image/x-portable-pixmap", + "pps": "application/vnd.ms-powerpoint", + "ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", + "ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", + "ppt": "application/vnd.ms-powerpoint", + "pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12", + "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "prf": "application/pics-rules", + "prm": "application/octet-stream", + "prx": "application/octet-stream", + "ps": "application/postscript", + "psd": "application/octet-stream", + "psm": "application/octet-stream", + "psp": "application/octet-stream", + "pub": "application/x-mspublisher", + "qt": "video/quicktime", + "qtl": "application/x-quicktimeplayer", + "qxd": "application/octet-stream", + "ra": "audio/x-pn-realaudio", + "ram": "audio/x-pn-realaudio", + "rar": "application/octet-stream", + "ras": "image/x-cmu-raster", + "rf": "image/vnd.rn-realflash", + "rgb": "image/x-rgb", + "rm": "application/vnd.rn-realmedia", + "rmi": "audio/mid", + "roff": "application/x-troff", + "rpm": "audio/x-pn-realaudio-plugin", + "rtf": "application/rtf", + "rtx": "text/richtext", + "scd": "application/x-msschedule", + "sct": "text/scriptlet", + "sea": "application/octet-stream", + "setpay": "application/set-payment-initiation", + "setreg": "application/set-registration-initiation", + "sgml": "text/sgml", + "sh": "application/x-sh", + "shar": "application/x-shar", + "sit": "application/x-stuffit", + "sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12", + "sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", + "smd": "audio/x-smd", + "smi": "application/octet-stream", + "smx": "audio/x-smd", + "smz": "audio/x-smd", + "snd": "audio/basic", + "snp": "application/octet-stream", + "spc": "application/x-pkcs7-certificates", + "spl": "application/futuresplash", + "src": "application/x-wais-source", + "ssm": "application/streamingmedia", + "sst": "application/vnd.ms-pki.certstore", + "stl": "application/vnd.ms-pki.stl", + "sv4cpio": "application/x-sv4cpio", + "sv4crc": "application/x-sv4crc", + "svg": "image/svg+xml", + "swf": "application/x-shockwave-flash", + "t": "application/x-troff", + "tar": "application/x-tar", + "tcl": "application/x-tcl", + "tex": "application/x-tex", + "texi": "application/x-texinfo", + "texinfo": "application/x-texinfo", + "tgz": "application/x-compressed", + "thmx": "application/vnd.ms-officetheme", + "thn": "application/octet-stream", + "tif": "image/tiff", + "tiff": "image/tiff", + "toc": "application/octet-stream", + "tr": "application/x-troff", + "trm": "application/x-msterminal", + "tsv": "text/tab-separated-values", + "ttf": "application/octet-stream", + "txt": "text/plain", + "u32": "application/octet-stream", + "uls": "text/iuls", + "ustar": "application/x-ustar", + "vbs": "text/vbscript", + "vcf": "text/x-vcard", + "vcs": "text/plain", + "vdx": "application/vnd.ms-visio.viewer", + "vml": "text/xml", + "vsd": "application/vnd.visio", + "vss": "application/vnd.visio", + "vst": "application/vnd.visio", + "vsto": "application/x-ms-vsto", + "vsw": "application/vnd.visio", + "vsx": "application/vnd.visio", + "vtx": "application/vnd.visio", + "wasm": "application/wasm", + "wav": "audio/wav", + "wax": "audio/x-ms-wax", + "wbmp": "image/vnd.wap.wbmp", + "wcm": "application/vnd.ms-works", + "wdb": "application/vnd.ms-works", + "wks": "application/vnd.ms-works", + "wm": "video/x-ms-wm", + "wma": "audio/x-ms-wma", + "wmd": "application/x-ms-wmd", + "wmf": "application/x-msmetafile", + "wml": "text/vnd.wap.wml", + "wmlc": "application/vnd.wap.wmlc", + "wmls": "text/vnd.wap.wmlscript", + "wmlsc": "application/vnd.wap.wmlscriptc", + "wmp": "video/x-ms-wmp", + "wmv": "video/x-ms-wmv", + "wmx": "video/x-ms-wmx", + "wmz": "application/x-ms-wmz", + "wps": "application/vnd.ms-works", + "wri": "application/x-mswrite", + "wrl": "x-world/x-vrml", + "wrz": "x-world/x-vrml", + "wsdl": "text/xml", + "wvx": "video/x-ms-wvx", + "x": "application/directx", + "xaf": "x-world/x-vrml", + "xaml": "application/xaml+xml", + "xap": "application/x-silverlight-app", + "xbap": "application/x-ms-xbap", + "xbm": "image/x-xbitmap", + "xdr": "text/plain", + "xht": "application/xhtml+xml", + "xhtml": "application/xhtml+xml", + "xla": "application/vnd.ms-excel", + "xlam": "application/vnd.ms-excel.addin.macroEnabled.12", + "xlc": "application/vnd.ms-excel", + "xlm": "application/vnd.ms-excel", + "xls": "application/vnd.ms-excel", + "xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12", + "xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "xlt": "application/vnd.ms-excel", + "xltm": "application/vnd.ms-excel.template.macroEnabled.12", + "xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", + "xlw": "application/vnd.ms-excel", + "xml": "text/xml", + "xof": "x-world/x-vrml", + "xpm": "image/x-xpixmap", + "xps": "application/vnd.ms-xpsdocument", + "xsd": "text/xml", + "xsf": "text/xml", + "xsl": "text/xml", + "xslt": "text/xml", + "xsn": "application/octet-stream", + "xtp": "application/octet-stream", + "xwd": "image/x-xwindowdump", + "z": "application/x-compress", + "zip": "application/x-zip-compressed" + ] +} + +private var stoppedKey = malloc(1) + +private extension WKURLSchemeTask { + var stopped: Bool { + get { + return objc_getAssociatedObject(self, &stoppedKey) as? Bool ?? false + } + set { + objc_setAssociatedObject(self, &stoppedKey, newValue, .OBJC_ASSOCIATION_ASSIGN) + } + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/WebViewDelegationHandler.swift b/node_modules/@capacitor/ios/Capacitor/Capacitor/WebViewDelegationHandler.swift new file mode 100644 index 0000000..adaf883 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/WebViewDelegationHandler.swift @@ -0,0 +1,334 @@ +import Foundation +import WebKit + +// adopting a public protocol in an internal class is by design +// swiftlint:disable lower_acl_than_parent +@objc(CAPWebViewDelegationHandler) +internal class WebViewDelegationHandler: NSObject, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler { + weak var bridge: CapacitorBridge? + fileprivate(set) var contentController = WKUserContentController() + enum WebViewLoadingState { + case unloaded + case initialLoad(isOpaque: Bool) + case subsequentLoad + } + fileprivate(set) var webViewLoadingState = WebViewLoadingState.unloaded + + private let handlerName = "bridge" + + init(bridge: CapacitorBridge? = nil) { + super.init() + self.bridge = bridge + contentController.add(self, name: handlerName) + } + + func cleanUp() { + contentController.removeScriptMessageHandler(forName: handlerName) + } + + func willLoadWebview(_ webView: WKWebView?) { + // Set the webview to be not opaque on the inital load. This prevents + // the webview from showing a white background, which is its default + // loading display, as that can appear as a screen flash. The opacity + // might have been set by something else, like a plugin, so we want + // to save the current value so it can be reset on success or failure. + if let webView = webView, case .unloaded = webViewLoadingState { + webViewLoadingState = .initialLoad(isOpaque: webView.isOpaque) + webView.isOpaque = false + } + } + + // MARK: - WKNavigationDelegate + + // The force unwrap is part of the protocol declaration, so we should keep it. + // swiftlint:disable:next implicitly_unwrapped_optional + public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { + // Reset the bridge on each navigation + bridge?.reset() + } + + @available(iOS 15, *) + func webView( + _ webView: WKWebView, + requestMediaCapturePermissionFor origin: WKSecurityOrigin, + initiatedByFrame frame: WKFrameInfo, + type: WKMediaCaptureType, + decisionHandler: @escaping (WKPermissionDecision) -> Void + ) { + decisionHandler(.grant) + } + + @available(iOS 15, *) + func webView(_ webView: WKWebView, + requestDeviceOrientationAndMotionPermissionFor origin: WKSecurityOrigin, + initiatedByFrame frame: WKFrameInfo, + decisionHandler: @escaping (WKPermissionDecision) -> Void) { + decisionHandler(.grant) + } + + public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { + // post a notification for any listeners + NotificationCenter.default.post(name: .capacitorDecidePolicyForNavigationAction, object: navigationAction) + + // sanity check, these shouldn't ever be nil in practice + guard let bridge = bridge, let navURL = navigationAction.request.url else { + decisionHandler(.allow) + return + } + + // first, give plugins the chance to handle the decision + for pluginObject in bridge.plugins { + let plugin = pluginObject.value + let selector = NSSelectorFromString("shouldOverrideLoad:") + if plugin.responds(to: selector) { + let shouldOverrideLoad = plugin.shouldOverrideLoad(navigationAction) + if shouldOverrideLoad != nil { + if shouldOverrideLoad == true { + decisionHandler(.cancel) + return + } else if shouldOverrideLoad == false { + decisionHandler(.allow) + return + } + } + } + } + + // next, check if this is covered by the allowedNavigation configuration + if let host = navURL.host, bridge.config.shouldAllowNavigation(to: host) { + decisionHandler(.allow) + return + } + + // otherwise, is this a new window or a main frame navigation but to an outside source + let toplevelNavigation = (navigationAction.targetFrame == nil || navigationAction.targetFrame?.isMainFrame == true) + + // Check if the url being navigated to is configured as an application url (whether local or remote) + let isApplicationNavigation = navURL.absoluteString.starts(with: bridge.config.serverURL.absoluteString) || + navURL.absoluteString.starts(with: bridge.config.localURL.absoluteString) + + if !isApplicationNavigation, toplevelNavigation { + // disallow and let the system handle it + if UIApplication.shared.applicationState == .active { + UIApplication.shared.open(navURL, options: [:], completionHandler: nil) + } + decisionHandler(.cancel) + return + } + + // fallthrough to allowing it + decisionHandler(.allow) + } + + // The force unwrap is part of the protocol declaration, so we should keep it. + // swiftlint:disable:next implicitly_unwrapped_optional + public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + if case .initialLoad(let isOpaque) = webViewLoadingState { + webView.isOpaque = isOpaque + webViewLoadingState = .subsequentLoad + } + CAPLog.print("⚡️ WebView loaded") + } + + // The force unwrap is part of the protocol declaration, so we should keep it. + // swiftlint:disable:next implicitly_unwrapped_optional + public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { + if case .initialLoad(let isOpaque) = webViewLoadingState { + webView.isOpaque = isOpaque + webViewLoadingState = .subsequentLoad + } + + if let errorURL = bridge?.config.errorPathURL { + webView.load(URLRequest(url: errorURL)) + } + + CAPLog.print("⚡️ WebView failed to load") + CAPLog.print("⚡️ Error: " + error.localizedDescription) + } + + // The force unwrap is part of the protocol declaration, so we should keep it. + // swiftlint:disable:next implicitly_unwrapped_optional + public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { + if let errorURL = bridge?.config.errorPathURL { + webView.load(URLRequest(url: errorURL)) + } + + CAPLog.print("⚡️ WebView failed provisional navigation") + CAPLog.print("⚡️ Error: " + error.localizedDescription) + } + + public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { + webView.reload() + } + + // MARK: - WKScriptMessageHandler + + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + guard let bridge = bridge else { + return + } + + let body = message.body + if let dict = body as? [String: Any] { + let type = dict["type"] as? String ?? "" + + if type == "js.error" { + if let error = dict["error"] as? [String: Any] { + logJSError(error) + } + } else if type == "message" { + let pluginId = dict["pluginId"] as? String ?? "" + let method = dict["methodName"] as? String ?? "" + let callbackId = dict["callbackId"] as? String ?? "" + + let options = dict["options"] as? [String: Any] ?? [:] + + if pluginId != "Console" { + CAPLog.print("⚡️ To Native -> ", pluginId, method, callbackId) + } + + bridge.handleJSCall(call: JSCall(options: options, pluginId: pluginId, method: method, callbackId: callbackId)) + } else if type == "cordova" { + let pluginId = dict["service"] as? String ?? "" + let method = dict["action"] as? String ?? "" + let callbackId = dict["callbackId"] as? String ?? "" + + let args = dict["actionArgs"] as? Array ?? [] + let options = ["options": args] + + CAPLog.print("To Native Cordova -> ", pluginId, method, callbackId, options) + + bridge.handleCordovaJSCall(call: JSCall(options: options, pluginId: pluginId, method: method, callbackId: callbackId)) + } + } + } + + // MARK: - WKUIDelegate + + public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { + guard var viewController = bridge?.viewController else { + completionHandler() + return + } + + if let presentedVC = viewController.presentedViewController, !presentedVC.isBeingDismissed { + viewController = presentedVC + } + + let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) + + alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) in + completionHandler() + })) + + viewController.present(alertController, animated: true, completion: nil) + } + + public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { + guard let viewController = bridge?.viewController else { + return + } + + let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) + + alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (_) in + completionHandler(false) + })) + + alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) in + completionHandler(true) + })) + + viewController.present(alertController, animated: true, completion: nil) + } + + public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { + + // Check if this is synchronous cookie or http call + do { + if let dataFromString = prompt.data(using: .utf8, allowLossyConversion: false) { + if let payload = try JSONSerialization.jsonObject(with: dataFromString, options: .fragmentsAllowed) as? [String: AnyObject] { + let type = payload["type"] as? String + + if type == "CapacitorCookies.get" { + completionHandler(CapacitorCookieManager(bridge!.config).getCookies()) + // Don't present prompt + return + } else if type == "CapacitorCookies.set" { + // swiftlint:disable force_cast + let action = payload["action"] as! String + let domain = payload["domain"] as! String + CapacitorCookieManager(bridge!.config).setCookie(domain, action) + completionHandler("") + // swiftlint:enable force_cast + // Don't present prompt + return + } else if type == "CapacitorCookies.isEnabled" { + let pluginConfig = bridge!.config.getPluginConfig("CapacitorCookies") + completionHandler(String(pluginConfig.getBoolean("enabled", false))) + // Don't present prompt + return + } else if type == "CapacitorHttp" { + let pluginConfig = bridge!.config.getPluginConfig("CapacitorHttp") + completionHandler(String(pluginConfig.getBoolean("enabled", false))) + // Don't present prompt + return + } + } + } + } catch { + // Continue with regular prompt + } + + guard let viewController = bridge?.viewController else { + return + } + + let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .alert) + + alertController.addTextField { (textField) in + textField.text = defaultText + } + + alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (_) in + completionHandler(nil) + })) + + alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) in + if let text = alertController.textFields?.first?.text { + completionHandler(text) + } else { + completionHandler(defaultText) + } + })) + + viewController.present(alertController, animated: true, completion: nil) + } + + public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { + if let url = navigationAction.request.url { + UIApplication.shared.open(url, options: [:], completionHandler: nil) + } + return nil + } + + // MARK: - Private + + private func logJSError(_ error: [String: Any]) { + let message = error["message"] ?? "No message" + let url = error["url"] as? String ?? "" + let line = error["line"] ?? "" + let col = error["col"] ?? "" + var filename = "" + if let filenameIndex = url.range(of: "/", options: .backwards)?.lowerBound { + let index = url.index(after: filenameIndex) + filename = String(url[index...]) + } + + CAPLog.print("\n⚡️ ------ STARTUP JS ERROR ------\n") + CAPLog.print("⚡️ \(message)") + CAPLog.print("⚡️ URL: \(url)") + CAPLog.print("⚡️ \(filename):\(line):\(col)") + CAPLog.print("\n⚡️ See above for help with debugging blank-screen issues") + } +} diff --git a/node_modules/@capacitor/ios/Capacitor/Capacitor/assets/native-bridge.js b/node_modules/@capacitor/ios/Capacitor/Capacitor/assets/native-bridge.js new file mode 100644 index 0000000..44ca340 --- /dev/null +++ b/node_modules/@capacitor/ios/Capacitor/Capacitor/assets/native-bridge.js @@ -0,0 +1,1043 @@ + +/*! Capacitor: https://capacitorjs.com/ - MIT License */ +/* Generated File. Do not edit. */ + +var nativeBridge = (function (exports) { + 'use strict'; + + var ExceptionCode; + (function (ExceptionCode) { + /** + * API is not implemented. + * + * This usually means the API can't be used because it is not implemented for + * the current platform. + */ + ExceptionCode["Unimplemented"] = "UNIMPLEMENTED"; + /** + * API is not available. + * + * This means the API can't be used right now because: + * - it is currently missing a prerequisite, such as network connectivity + * - it requires a particular platform or browser version + */ + ExceptionCode["Unavailable"] = "UNAVAILABLE"; + })(ExceptionCode || (ExceptionCode = {})); + class CapacitorException extends Error { + constructor(message, code, data) { + super(message); + this.message = message; + this.code = code; + this.data = data; + } + } + + // For removing exports for iOS/Android, keep let for reassignment + // eslint-disable-next-line + let dummy = {}; + const readFileAsBase64 = (file) => new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + const data = reader.result; + resolve(btoa(data)); + }; + reader.onerror = reject; + reader.readAsBinaryString(file); + }); + const convertFormData = async (formData) => { + const newFormData = []; + for (const pair of formData.entries()) { + const [key, value] = pair; + if (value instanceof File) { + const base64File = await readFileAsBase64(value); + newFormData.push({ + key, + value: base64File, + type: 'base64File', + contentType: value.type, + fileName: value.name, + }); + } + else { + newFormData.push({ key, value, type: 'string' }); + } + } + return newFormData; + }; + const convertBody = async (body, contentType) => { + if (body instanceof ReadableStream || body instanceof Uint8Array) { + let encodedData; + if (body instanceof ReadableStream) { + const reader = body.getReader(); + const chunks = []; + while (true) { + const { done, value } = await reader.read(); + if (done) + break; + chunks.push(value); + } + const concatenated = new Uint8Array(chunks.reduce((acc, chunk) => acc + chunk.length, 0)); + let position = 0; + for (const chunk of chunks) { + concatenated.set(chunk, position); + position += chunk.length; + } + encodedData = concatenated; + } + else { + encodedData = body; + } + let data = new TextDecoder().decode(encodedData); + let type; + if (contentType === 'application/json') { + try { + data = JSON.parse(data); + } + catch (ignored) { + // ignore + } + type = 'json'; + } + else if (contentType === 'multipart/form-data') { + type = 'formData'; + } + else if (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('image')) { + type = 'image'; + } + else if (contentType === 'application/octet-stream') { + type = 'binary'; + } + else { + type = 'text'; + } + return { + data, + type, + headers: { 'Content-Type': contentType || 'application/octet-stream' }, + }; + } + else if (body instanceof URLSearchParams) { + return { + data: body.toString(), + type: 'text', + }; + } + else if (body instanceof FormData) { + const formData = await convertFormData(body); + const boundary = `${Date.now()}`; + return { + data: formData, + type: 'formData', + headers: { + 'Content-Type': `multipart/form-data; boundary=--${boundary}`, + }, + }; + } + else if (body instanceof File) { + const fileData = await readFileAsBase64(body); + return { + data: fileData, + type: 'file', + headers: { 'Content-Type': body.type }, + }; + } + return { data: body, type: 'json' }; + }; + const CAPACITOR_HTTP_INTERCEPTOR = '/_capacitor_http_interceptor_'; + const CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM = 'u'; + // TODO: export as Cap function + const isRelativeOrProxyUrl = (url) => !url || + !(url.startsWith('http:') || url.startsWith('https:')) || + url.indexOf(CAPACITOR_HTTP_INTERCEPTOR) > -1; + // TODO: export as Cap function + const createProxyUrl = (url, win) => { + var _a, _b; + if (isRelativeOrProxyUrl(url)) + return url; + const bridgeUrl = new URL((_b = (_a = win.Capacitor) === null || _a === void 0 ? void 0 : _a.getServerUrl()) !== null && _b !== void 0 ? _b : ''); + bridgeUrl.pathname = CAPACITOR_HTTP_INTERCEPTOR; + bridgeUrl.searchParams.append(CAPACITOR_HTTP_INTERCEPTOR_URL_PARAM, url); + return bridgeUrl.toString(); + }; + const initBridge = (w) => { + const getPlatformId = (win) => { + var _a, _b; + if (win === null || win === void 0 ? void 0 : win.androidBridge) { + return 'android'; + } + else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) { + return 'ios'; + } + else { + return 'web'; + } + }; + const convertFileSrcServerUrl = (webviewServerUrl, filePath) => { + if (typeof filePath === 'string') { + if (filePath.startsWith('/')) { + return webviewServerUrl + '/_capacitor_file_' + filePath; + } + else if (filePath.startsWith('file://')) { + return (webviewServerUrl + filePath.replace('file://', '/_capacitor_file_')); + } + else if (filePath.startsWith('content://')) { + return (webviewServerUrl + + filePath.replace('content:/', '/_capacitor_content_')); + } + } + return filePath; + }; + const initEvents = (win, cap) => { + cap.addListener = (pluginName, eventName, callback) => { + const callbackId = cap.nativeCallback(pluginName, 'addListener', { + eventName: eventName, + }, callback); + return { + remove: async () => { + var _a; + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.debug('Removing listener', pluginName, eventName); + cap.removeListener(pluginName, callbackId, eventName, callback); + }, + }; + }; + cap.removeListener = (pluginName, callbackId, eventName, callback) => { + cap.nativeCallback(pluginName, 'removeListener', { + callbackId: callbackId, + eventName: eventName, + }, callback); + }; + cap.createEvent = (eventName, eventData) => { + const doc = win.document; + if (doc) { + const ev = doc.createEvent('Events'); + ev.initEvent(eventName, false, false); + if (eventData && typeof eventData === 'object') { + for (const i in eventData) { + // eslint-disable-next-line no-prototype-builtins + if (eventData.hasOwnProperty(i)) { + ev[i] = eventData[i]; + } + } + } + return ev; + } + return null; + }; + cap.triggerEvent = (eventName, target, eventData) => { + const doc = win.document; + const cordova = win.cordova; + eventData = eventData || {}; + const ev = cap.createEvent(eventName, eventData); + if (ev) { + if (target === 'document') { + if (cordova === null || cordova === void 0 ? void 0 : cordova.fireDocumentEvent) { + cordova.fireDocumentEvent(eventName, eventData); + return true; + } + else if (doc === null || doc === void 0 ? void 0 : doc.dispatchEvent) { + return doc.dispatchEvent(ev); + } + } + else if (target === 'window' && win.dispatchEvent) { + return win.dispatchEvent(ev); + } + else if (doc === null || doc === void 0 ? void 0 : doc.querySelector) { + const targetEl = doc.querySelector(target); + if (targetEl) { + return targetEl.dispatchEvent(ev); + } + } + } + return false; + }; + win.Capacitor = cap; + }; + const initLegacyHandlers = (win, cap) => { + // define cordova if it's not there already + win.cordova = win.cordova || {}; + const doc = win.document; + const nav = win.navigator; + if (nav) { + nav.app = nav.app || {}; + nav.app.exitApp = () => { + var _a; + if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) { + win.console.warn('App plugin not installed'); + } + else { + cap.nativeCallback('App', 'exitApp', {}); + } + }; + } + if (doc) { + const docAddEventListener = doc.addEventListener; + doc.addEventListener = (...args) => { + var _a; + const eventName = args[0]; + const handler = args[1]; + if (eventName === 'deviceready' && handler) { + Promise.resolve().then(handler); + } + else if (eventName === 'backbutton' && cap.Plugins.App) { + // Add a dummy listener so Capacitor doesn't do the default + // back button action + if (!((_a = cap.Plugins) === null || _a === void 0 ? void 0 : _a.App)) { + win.console.warn('App plugin not installed'); + } + else { + cap.Plugins.App.addListener('backButton', () => { + // ignore + }); + } + } + return docAddEventListener.apply(doc, args); + }; + } + // deprecated in v3, remove from v4 + cap.platform = cap.getPlatform(); + cap.isNative = cap.isNativePlatform(); + win.Capacitor = cap; + }; + const initVendor = (win, cap) => { + const Ionic = (win.Ionic = win.Ionic || {}); + const IonicWebView = (Ionic.WebView = Ionic.WebView || {}); + const Plugins = cap.Plugins; + IonicWebView.getServerBasePath = (callback) => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.getServerBasePath().then((result) => { + callback(result.path); + }); + }; + IonicWebView.setServerAssetPath = (path) => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.setServerAssetPath({ path }); + }; + IonicWebView.setServerBasePath = (path) => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.setServerBasePath({ path }); + }; + IonicWebView.persistServerBasePath = () => { + var _a; + (_a = Plugins === null || Plugins === void 0 ? void 0 : Plugins.WebView) === null || _a === void 0 ? void 0 : _a.persistServerBasePath(); + }; + IonicWebView.convertFileSrc = (url) => cap.convertFileSrc(url); + win.Capacitor = cap; + win.Ionic.WebView = IonicWebView; + }; + const initLogger = (win, cap) => { + const BRIDGED_CONSOLE_METHODS = [ + 'debug', + 'error', + 'info', + 'log', + 'trace', + 'warn', + ]; + const createLogFromNative = (c) => (result) => { + if (isFullConsole(c)) { + const success = result.success === true; + const tagStyles = success + ? 'font-style: italic; font-weight: lighter; color: gray' + : 'font-style: italic; font-weight: lighter; color: red'; + c.groupCollapsed('%cresult %c' + + result.pluginId + + '.' + + result.methodName + + ' (#' + + result.callbackId + + ')', tagStyles, 'font-style: italic; font-weight: bold; color: #444'); + if (result.success === false) { + c.error(result.error); + } + else { + c.dir(result.data); + } + c.groupEnd(); + } + else { + if (result.success === false) { + c.error('LOG FROM NATIVE', result.error); + } + else { + c.log('LOG FROM NATIVE', result.data); + } + } + }; + const createLogToNative = (c) => (call) => { + if (isFullConsole(c)) { + c.groupCollapsed('%cnative %c' + + call.pluginId + + '.' + + call.methodName + + ' (#' + + call.callbackId + + ')', 'font-weight: lighter; color: gray', 'font-weight: bold; color: #000'); + c.dir(call); + c.groupEnd(); + } + else { + c.log('LOG TO NATIVE: ', call); + } + }; + const isFullConsole = (c) => { + if (!c) { + return false; + } + return (typeof c.groupCollapsed === 'function' || + typeof c.groupEnd === 'function' || + typeof c.dir === 'function'); + }; + const serializeConsoleMessage = (msg) => { + try { + if (typeof msg === 'object') { + msg = JSON.stringify(msg); + } + return String(msg); + } + catch (e) { + return ''; + } + }; + const platform = getPlatformId(win); + if (platform == 'android' || platform == 'ios') { + // patch document.cookie on Android/iOS + win.CapacitorCookiesDescriptor = + Object.getOwnPropertyDescriptor(Document.prototype, 'cookie') || + Object.getOwnPropertyDescriptor(HTMLDocument.prototype, 'cookie'); + let doPatchCookies = false; + // check if capacitor cookies is disabled before patching + if (platform === 'ios') { + // Use prompt to synchronously get capacitor cookies config. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorCookies.isEnabled', + }; + const isCookiesEnabled = prompt(JSON.stringify(payload)); + if (isCookiesEnabled === 'true') { + doPatchCookies = true; + } + } + else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { + const isCookiesEnabled = win.CapacitorCookiesAndroidInterface.isEnabled(); + if (isCookiesEnabled === true) { + doPatchCookies = true; + } + } + if (doPatchCookies) { + Object.defineProperty(document, 'cookie', { + get: function () { + var _a, _b, _c; + if (platform === 'ios') { + // Use prompt to synchronously get cookies. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorCookies.get', + }; + const res = prompt(JSON.stringify(payload)); + return res; + } + else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { + // return original document.cookie since Android does not support filtering of `httpOnly` cookies + return (_c = (_b = (_a = win.CapacitorCookiesDescriptor) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(document)) !== null && _c !== void 0 ? _c : ''; + } + }, + set: function (val) { + const cookiePairs = val.split(';'); + const domainSection = val.toLowerCase().split('domain=')[1]; + const domain = cookiePairs.length > 1 && + domainSection != null && + domainSection.length > 0 + ? domainSection.split(';')[0].trim() + : ''; + if (platform === 'ios') { + // Use prompt to synchronously set cookies. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorCookies.set', + action: val, + domain, + }; + prompt(JSON.stringify(payload)); + } + else if (typeof win.CapacitorCookiesAndroidInterface !== 'undefined') { + win.CapacitorCookiesAndroidInterface.setCookie(domain, val); + } + }, + }); + } + // patch fetch / XHR on Android/iOS + // store original fetch & XHR functions + win.CapacitorWebFetch = window.fetch; + win.CapacitorWebXMLHttpRequest = { + abort: window.XMLHttpRequest.prototype.abort, + constructor: window.XMLHttpRequest.prototype.constructor, + fullObject: window.XMLHttpRequest, + getAllResponseHeaders: window.XMLHttpRequest.prototype.getAllResponseHeaders, + getResponseHeader: window.XMLHttpRequest.prototype.getResponseHeader, + open: window.XMLHttpRequest.prototype.open, + prototype: window.XMLHttpRequest.prototype, + send: window.XMLHttpRequest.prototype.send, + setRequestHeader: window.XMLHttpRequest.prototype.setRequestHeader, + }; + let doPatchHttp = false; + // check if capacitor http is disabled before patching + if (platform === 'ios') { + // Use prompt to synchronously get capacitor http config. + // https://stackoverflow.com/questions/29249132/wkwebview-complex-communication-between-javascript-native-code/49474323#49474323 + const payload = { + type: 'CapacitorHttp', + }; + const isHttpEnabled = prompt(JSON.stringify(payload)); + if (isHttpEnabled === 'true') { + doPatchHttp = true; + } + } + else if (typeof win.CapacitorHttpAndroidInterface !== 'undefined') { + const isHttpEnabled = win.CapacitorHttpAndroidInterface.isEnabled(); + if (isHttpEnabled === true) { + doPatchHttp = true; + } + } + if (doPatchHttp) { + // fetch patch + window.fetch = async (resource, options) => { + const request = new Request(resource, options); + if (request.url.startsWith(`${cap.getServerUrl()}/`)) { + return win.CapacitorWebFetch(resource, options); + } + const { method } = request; + if (method.toLocaleUpperCase() === 'GET' || + method.toLocaleUpperCase() === 'HEAD' || + method.toLocaleUpperCase() === 'OPTIONS' || + method.toLocaleUpperCase() === 'TRACE') { + if (typeof resource === 'string') { + return await win.CapacitorWebFetch(createProxyUrl(resource, win), options); + } + else if (resource instanceof Request) { + const modifiedRequest = new Request(createProxyUrl(resource.url, win), resource); + return await win.CapacitorWebFetch(modifiedRequest, options); + } + } + const tag = `CapacitorHttp fetch ${Date.now()} ${resource}`; + console.time(tag); + try { + const { body } = request; + const optionHeaders = Object.fromEntries(request.headers.entries()); + const { data: requestData, type, headers, } = await convertBody((options === null || options === void 0 ? void 0 : options.body) || body || undefined, optionHeaders['Content-Type'] || optionHeaders['content-type']); + const nativeResponse = await cap.nativePromise('CapacitorHttp', 'request', { + url: request.url, + method: method, + data: requestData, + dataType: type, + headers: Object.assign(Object.assign({}, headers), optionHeaders), + }); + const contentType = nativeResponse.headers['Content-Type'] || + nativeResponse.headers['content-type']; + let data = (contentType === null || contentType === void 0 ? void 0 : contentType.startsWith('application/json')) + ? JSON.stringify(nativeResponse.data) + : nativeResponse.data; + // use null data for 204 No Content HTTP response + if (nativeResponse.status === 204) { + data = null; + } + // intercept & parse response before returning + const response = new Response(data, { + headers: nativeResponse.headers, + status: nativeResponse.status, + }); + /* + * copy url to response, `cordova-plugin-ionic` uses this url from the response + * we need `Object.defineProperty` because url is an inherited getter on the Response + * see: https://stackoverflow.com/a/57382543 + * */ + Object.defineProperty(response, 'url', { + value: nativeResponse.url, + }); + console.timeEnd(tag); + return response; + } + catch (error) { + console.timeEnd(tag); + return Promise.reject(error); + } + }; + window.XMLHttpRequest = function () { + const xhr = new win.CapacitorWebXMLHttpRequest.constructor(); + Object.defineProperties(xhr, { + _headers: { + value: {}, + writable: true, + }, + _method: { + value: xhr.method, + writable: true, + }, + }); + const prototype = win.CapacitorWebXMLHttpRequest.prototype; + const isProgressEventAvailable = () => typeof ProgressEvent !== 'undefined' && + ProgressEvent.prototype instanceof Event; + // XHR patch abort + prototype.abort = function () { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.abort.call(this); + } + this.readyState = 0; + setTimeout(() => { + this.dispatchEvent(new Event('abort')); + this.dispatchEvent(new Event('loadend')); + }); + }; + // XHR patch open + prototype.open = function (method, url) { + this._method = method.toLocaleUpperCase(); + this._url = url; + if (!this._method || + this._method === 'GET' || + this._method === 'HEAD' || + this._method === 'OPTIONS' || + this._method === 'TRACE') { + if (isRelativeOrProxyUrl(url)) { + return win.CapacitorWebXMLHttpRequest.open.call(this, method, url); + } + this._url = createProxyUrl(this._url, win); + return win.CapacitorWebXMLHttpRequest.open.call(this, method, this._url); + } + Object.defineProperties(this, { + readyState: { + get: function () { + var _a; + return (_a = this._readyState) !== null && _a !== void 0 ? _a : 0; + }, + set: function (val) { + this._readyState = val; + setTimeout(() => { + this.dispatchEvent(new Event('readystatechange')); + }); + }, + }, + }); + setTimeout(() => { + this.dispatchEvent(new Event('loadstart')); + }); + this.readyState = 1; + }; + // XHR patch set request header + prototype.setRequestHeader = function (header, value) { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.setRequestHeader.call(this, header, value); + } + this._headers[header] = value; + }; + // XHR patch send + prototype.send = function (body) { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.send.call(this, body); + } + const tag = `CapacitorHttp XMLHttpRequest ${Date.now()} ${this._url}`; + console.time(tag); + try { + this.readyState = 2; + Object.defineProperties(this, { + response: { + value: '', + writable: true, + }, + responseText: { + value: '', + writable: true, + }, + responseURL: { + value: '', + writable: true, + }, + status: { + value: 0, + writable: true, + }, + }); + convertBody(body).then(({ data, type, headers }) => { + const otherHeaders = this._headers != null && Object.keys(this._headers).length > 0 + ? this._headers + : undefined; + // intercept request & pass to the bridge + cap + .nativePromise('CapacitorHttp', 'request', { + url: this._url, + method: this._method, + data: data !== null ? data : undefined, + headers: Object.assign(Object.assign({}, headers), otherHeaders), + dataType: type, + }) + .then((nativeResponse) => { + var _a; + // intercept & parse response before returning + if (this.readyState == 2) { + //TODO: Add progress event emission on native side + if (isProgressEventAvailable()) { + this.dispatchEvent(new ProgressEvent('progress', { + lengthComputable: true, + loaded: nativeResponse.data.length, + total: nativeResponse.data.length, + })); + } + this._headers = nativeResponse.headers; + this.status = nativeResponse.status; + const responseString = typeof nativeResponse.data !== 'string' + ? JSON.stringify(nativeResponse.data) + : nativeResponse.data; + if (this.responseType === '' || + this.responseType === 'text') { + this.response = responseString; + } + else if (this.responseType === 'blob') { + this.response = new Blob([responseString], { + type: 'application/json', + }); + } + else if (this.responseType === 'arraybuffer') { + const encoder = new TextEncoder(); + const uint8Array = encoder.encode(responseString); + this.response = uint8Array.buffer; + } + else { + this.response = nativeResponse.data; + } + this.responseText = ((_a = nativeResponse.headers['Content-Type']) === null || _a === void 0 ? void 0 : _a.startsWith('application/json')) + ? JSON.stringify(nativeResponse.data) + : nativeResponse.data; + this.responseURL = nativeResponse.url; + this.readyState = 4; + setTimeout(() => { + this.dispatchEvent(new Event('load')); + this.dispatchEvent(new Event('loadend')); + }); + } + console.timeEnd(tag); + }) + .catch((error) => { + this.status = error.status; + this._headers = error.headers; + this.response = error.data; + this.responseText = JSON.stringify(error.data); + this.responseURL = error.url; + this.readyState = 4; + if (isProgressEventAvailable()) { + this.dispatchEvent(new ProgressEvent('progress', { + lengthComputable: false, + loaded: 0, + total: 0, + })); + } + setTimeout(() => { + this.dispatchEvent(new Event('error')); + this.dispatchEvent(new Event('loadend')); + }); + console.timeEnd(tag); + }); + }); + } + catch (error) { + this.status = 500; + this._headers = {}; + this.response = error; + this.responseText = error.toString(); + this.responseURL = this._url; + this.readyState = 4; + if (isProgressEventAvailable()) { + this.dispatchEvent(new ProgressEvent('progress', { + lengthComputable: false, + loaded: 0, + total: 0, + })); + } + setTimeout(() => { + this.dispatchEvent(new Event('error')); + this.dispatchEvent(new Event('loadend')); + }); + console.timeEnd(tag); + } + }; + // XHR patch getAllResponseHeaders + prototype.getAllResponseHeaders = function () { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.getAllResponseHeaders.call(this); + } + let returnString = ''; + for (const key in this._headers) { + if (key.toLowerCase() !== 'set-cookie') { + returnString += key + ': ' + this._headers[key] + '\r\n'; + } + } + return returnString; + }; + // XHR patch getResponseHeader + prototype.getResponseHeader = function (name) { + if (isRelativeOrProxyUrl(this._url)) { + return win.CapacitorWebXMLHttpRequest.getResponseHeader.call(this, name); + } + for (const key in this._headers) { + if (key.toLowerCase() === name.toLowerCase()) { + return this._headers[key]; + } + } + return null; + }; + Object.setPrototypeOf(xhr, prototype); + return xhr; + }; + Object.assign(window.XMLHttpRequest, win.CapacitorWebXMLHttpRequest.fullObject); + } + } + // patch window.console on iOS and store original console fns + const isIos = getPlatformId(win) === 'ios'; + if (win.console && isIos) { + Object.defineProperties(win.console, BRIDGED_CONSOLE_METHODS.reduce((props, method) => { + const consoleMethod = win.console[method].bind(win.console); + props[method] = { + value: (...args) => { + const msgs = [...args]; + cap.toNative('Console', 'log', { + level: method, + message: msgs.map(serializeConsoleMessage).join(' '), + }); + return consoleMethod(...args); + }, + }; + return props; + }, {})); + } + cap.logJs = (msg, level) => { + switch (level) { + case 'error': + win.console.error(msg); + break; + case 'warn': + win.console.warn(msg); + break; + case 'info': + win.console.info(msg); + break; + default: + win.console.log(msg); + } + }; + cap.logToNative = createLogToNative(win.console); + cap.logFromNative = createLogFromNative(win.console); + cap.handleError = err => win.console.error(err); + win.Capacitor = cap; + }; + function initNativeBridge(win) { + const cap = win.Capacitor || {}; + // keep a collection of callbacks for native response data + const callbacks = new Map(); + const webviewServerUrl = typeof win.WEBVIEW_SERVER_URL === 'string' ? win.WEBVIEW_SERVER_URL : ''; + cap.getServerUrl = () => webviewServerUrl; + cap.convertFileSrc = filePath => convertFileSrcServerUrl(webviewServerUrl, filePath); + // Counter of callback ids, randomized to avoid + // any issues during reloads if a call comes back with + // an existing callback id from an old session + let callbackIdCount = Math.floor(Math.random() * 134217728); + let postToNative = null; + const isNativePlatform = () => true; + const getPlatform = () => getPlatformId(win); + cap.getPlatform = getPlatform; + cap.isPluginAvailable = name => Object.prototype.hasOwnProperty.call(cap.Plugins, name); + cap.isNativePlatform = isNativePlatform; + // create the postToNative() fn if needed + if (getPlatformId(win) === 'android') { + // android platform + postToNative = data => { + var _a; + try { + win.androidBridge.postMessage(JSON.stringify(data)); + } + catch (e) { + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e); + } + }; + } + else if (getPlatformId(win) === 'ios') { + // ios platform + postToNative = data => { + var _a; + try { + data.type = data.type ? data.type : 'message'; + win.webkit.messageHandlers.bridge.postMessage(data); + } + catch (e) { + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.error(e); + } + }; + } + cap.handleWindowError = (msg, url, lineNo, columnNo, err) => { + const str = msg.toLowerCase(); + if (str.indexOf('script error') > -1) ; + else { + const errObj = { + type: 'js.error', + error: { + message: msg, + url: url, + line: lineNo, + col: columnNo, + errorObject: JSON.stringify(err), + }, + }; + if (err !== null) { + cap.handleError(err); + } + postToNative(errObj); + } + return false; + }; + if (cap.DEBUG) { + window.onerror = cap.handleWindowError; + } + initLogger(win, cap); + /** + * Send a plugin method call to the native layer + */ + cap.toNative = (pluginName, methodName, options, storedCallback) => { + var _a, _b; + try { + if (typeof postToNative === 'function') { + let callbackId = '-1'; + if (storedCallback && + (typeof storedCallback.callback === 'function' || + typeof storedCallback.resolve === 'function')) { + // store the call for later lookup + callbackId = String(++callbackIdCount); + callbacks.set(callbackId, storedCallback); + } + const callData = { + callbackId: callbackId, + pluginId: pluginName, + methodName: methodName, + options: options || {}, + }; + if (cap.isLoggingEnabled && pluginName !== 'Console') { + cap.logToNative(callData); + } + // post the call data to native + postToNative(callData); + return callbackId; + } + else { + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(`implementation unavailable for: ${pluginName}`); + } + } + catch (e) { + (_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e); + } + return null; + }; + if (win === null || win === void 0 ? void 0 : win.androidBridge) { + win.androidBridge.onmessage = function (event) { + returnResult(JSON.parse(event.data)); + }; + } + /** + * Process a response from the native layer. + */ + cap.fromNative = result => { + returnResult(result); + }; + const returnResult = (result) => { + var _a, _b; + if (cap.isLoggingEnabled && result.pluginId !== 'Console') { + cap.logFromNative(result); + } + // get the stored call, if it exists + try { + const storedCall = callbacks.get(result.callbackId); + if (storedCall) { + // looks like we've got a stored call + if (result.error) { + // ensure stacktraces by copying error properties to an Error + result.error = Object.keys(result.error).reduce((err, key) => { + // use any type to avoid importing util and compiling most of .ts files + err[key] = result.error[key]; + return err; + }, new cap.Exception('')); + } + if (typeof storedCall.callback === 'function') { + // callback + if (result.success) { + storedCall.callback(result.data); + } + else { + storedCall.callback(null, result.error); + } + } + else if (typeof storedCall.resolve === 'function') { + // promise + if (result.success) { + storedCall.resolve(result.data); + } + else { + storedCall.reject(result.error); + } + // no need to keep this stored callback + // around for a one time resolve promise + callbacks.delete(result.callbackId); + } + } + else if (!result.success && result.error) { + // no stored callback, but if there was an error let's log it + (_a = win === null || win === void 0 ? void 0 : win.console) === null || _a === void 0 ? void 0 : _a.warn(result.error); + } + if (result.save === false) { + callbacks.delete(result.callbackId); + } + } + catch (e) { + (_b = win === null || win === void 0 ? void 0 : win.console) === null || _b === void 0 ? void 0 : _b.error(e); + } + // always delete to prevent memory leaks + // overkill but we're not sure what apps will do with this data + delete result.data; + delete result.error; + }; + cap.nativeCallback = (pluginName, methodName, options, callback) => { + if (typeof options === 'function') { + console.warn(`Using a callback as the 'options' parameter of 'nativeCallback()' is deprecated.`); + callback = options; + options = null; + } + return cap.toNative(pluginName, methodName, options, { callback }); + }; + cap.nativePromise = (pluginName, methodName, options) => { + return new Promise((resolve, reject) => { + cap.toNative(pluginName, methodName, options, { + resolve: resolve, + reject: reject, + }); + }); + }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + cap.withPlugin = (_pluginId, _fn) => dummy; + cap.Exception = CapacitorException; + initEvents(win, cap); + initLegacyHandlers(win, cap); + initVendor(win, cap); + win.Capacitor = cap; + } + initNativeBridge(w); + }; + initBridge(typeof globalThis !== 'undefined' + ? globalThis + : typeof self !== 'undefined' + ? self + : typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}); + + dummy = initBridge; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); diff --git a/node_modules/@capacitor/ios/CapacitorCordova.podspec b/node_modules/@capacitor/ios/CapacitorCordova.podspec new file mode 100644 index 0000000..478142b --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova.podspec @@ -0,0 +1,26 @@ +require 'json' +package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) +prefix = if ENV['NATIVE_PUBLISH'] == 'true' + 'ios/' + else + '' + end + +Pod::Spec.new do |s| + s.name = 'CapacitorCordova' + s.module_name = 'Cordova' + s.version = package['version'] + s.summary = 'Capacitor Cordova Compatibility Layer' + s.homepage = 'https://capacitorjs.com' + s.license = 'MIT' + s.authors = { 'Ionic Team' => 'hi@ionicframework.com' } + s.source = { git: 'https://github.com/ionic-team/capacitor', tag: s.version.to_s } + s.platform = :ios, 13.0 + s.source_files = "#{prefix}CapacitorCordova/CapacitorCordova/**/*.{h,m}" + s.public_header_files = "#{prefix}CapacitorCordova/CapacitorCordova/Classes/Public/*.h", + "#{prefix}CapacitorCordova/CapacitorCordova/CapacitorCordova.h" + s.module_map = "#{prefix}CapacitorCordova/CapacitorCordova/CapacitorCordova.modulemap" + s.resources = ["#{prefix}CapacitorCordova/CapacitorCordova/PrivacyInfo.xcprivacy"] + s.requires_arc = true + s.framework = 'WebKit' +end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/CapacitorCordova.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/CapacitorCordova.h new file mode 100644 index 0000000..a2ce9d5 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/CapacitorCordova.h @@ -0,0 +1,24 @@ +#import + +//! Project version number for CapacitorCordova. +FOUNDATION_EXPORT double CapacitorCordovaVersionNumber; + +//! Project version string for CapacitorCordova. +FOUNDATION_EXPORT const unsigned char CapacitorCordovaVersionString[]; + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/CapacitorCordova.modulemap b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/CapacitorCordova.modulemap new file mode 100644 index 0000000..32af43c --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/CapacitorCordova.modulemap @@ -0,0 +1,6 @@ +framework module Cordova { + umbrella header "CapacitorCordova.h" + + export * + module * { export * } +} diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/AppDelegate.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/AppDelegate.h new file mode 100644 index 0000000..17678ea --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/AppDelegate.h @@ -0,0 +1,8 @@ +#import +#import "CDVViewController.h" + +@interface AppDelegate : NSObject + +@property (nonatomic, strong) CDVViewController* viewController; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/AppDelegate.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/AppDelegate.m new file mode 100644 index 0000000..1b9f2c8 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/AppDelegate.m @@ -0,0 +1,5 @@ +#import "AppDelegate.h" + +@implementation AppDelegate + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDV.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDV.h new file mode 100644 index 0000000..8f8fc04 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDV.h @@ -0,0 +1,28 @@ +/* + 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 "CDVAvailability.h" +#import "CDVPlugin.h" +#import "CDVPluginResult.h" +#import "CDVCommandDelegate.h" +#import "CDVInvokedUrlCommand.h" +#import "CDVViewController.h" +#import "CDVURLProtocol.h" +#import "CDVScreenOrientationDelegate.h" +#import "CDVWebViewProcessPoolFactory.h" diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVAvailability.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVAvailability.h new file mode 100644 index 0000000..cc4c8fc --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVAvailability.h @@ -0,0 +1,109 @@ +/* + 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. + */ + +#define __CORDOVA_IOS__ + +#define __CORDOVA_0_9_6 906 +#define __CORDOVA_1_0_0 10000 +#define __CORDOVA_1_1_0 10100 +#define __CORDOVA_1_2_0 10200 +#define __CORDOVA_1_3_0 10300 +#define __CORDOVA_1_4_0 10400 +#define __CORDOVA_1_4_1 10401 +#define __CORDOVA_1_5_0 10500 +#define __CORDOVA_1_6_0 10600 +#define __CORDOVA_1_6_1 10601 +#define __CORDOVA_1_7_0 10700 +#define __CORDOVA_1_8_0 10800 +#define __CORDOVA_1_8_1 10801 +#define __CORDOVA_1_9_0 10900 +#define __CORDOVA_2_0_0 20000 +#define __CORDOVA_2_1_0 20100 +#define __CORDOVA_2_2_0 20200 +#define __CORDOVA_2_3_0 20300 +#define __CORDOVA_2_4_0 20400 +#define __CORDOVA_2_5_0 20500 +#define __CORDOVA_2_6_0 20600 +#define __CORDOVA_2_7_0 20700 +#define __CORDOVA_2_8_0 20800 +#define __CORDOVA_2_9_0 20900 +#define __CORDOVA_3_0_0 30000 +#define __CORDOVA_3_1_0 30100 +#define __CORDOVA_3_2_0 30200 +#define __CORDOVA_3_3_0 30300 +#define __CORDOVA_3_4_0 30400 +#define __CORDOVA_3_4_1 30401 +#define __CORDOVA_3_5_0 30500 +#define __CORDOVA_3_6_0 30600 +#define __CORDOVA_3_7_0 30700 +#define __CORDOVA_3_8_0 30800 +#define __CORDOVA_3_9_0 30900 +#define __CORDOVA_3_9_1 30901 +#define __CORDOVA_3_9_2 30902 +#define __CORDOVA_4_0_0 40000 +#define __CORDOVA_4_0_1 40001 +#define __CORDOVA_4_1_0 40100 +#define __CORDOVA_4_1_1 40101 +#define __CORDOVA_4_2_0 40200 +#define __CORDOVA_4_2_1 40201 +#define __CORDOVA_4_3_0 40300 +#define __CORDOVA_4_3_1 40301 +#define __CORDOVA_4_4_0 40400 +#define __CORDOVA_4_5_0 40500 +#define __CORDOVA_4_5_1 40501 +#define __CORDOVA_4_5_2 40502 +#define __CORDOVA_4_5_4 40504 +/* coho:next-version,insert-before */ +#define __CORDOVA_NA 99999 /* not available */ + +/* + #if CORDOVA_VERSION_MIN_REQUIRED >= __CORDOVA_4_0_0 + // do something when its at least 4.0.0 + #else + // do something else (non 4.0.0) + #endif + */ +#ifndef CORDOVA_VERSION_MIN_REQUIRED + /* coho:next-version-min-required,replace-after */ + #define CORDOVA_VERSION_MIN_REQUIRED __CORDOVA_4_5_4 +#endif + +/* + Returns YES if it is at least version specified as NSString(X) + Usage: + if (IsAtLeastiOSVersion(@"5.1")) { + // do something for iOS 5.1 or greater + } + */ +#define IsAtLeastiOSVersion(X) ([[[UIDevice currentDevice] systemVersion] compare:X options:NSNumericSearch] != NSOrderedAscending) + +/* Return the string version of the decimal version */ +#define CDV_VERSION [NSString stringWithFormat:@"%d.%d.%d", \ + (CORDOVA_VERSION_MIN_REQUIRED / 10000), \ + (CORDOVA_VERSION_MIN_REQUIRED % 10000) / 100, \ + (CORDOVA_VERSION_MIN_REQUIRED % 10000) % 100] + +// Enable this to log all exec() calls. +#define CDV_ENABLE_EXEC_LOGGING 0 +#if CDV_ENABLE_EXEC_LOGGING + #define CDV_EXEC_LOG NSLog +#else + #define CDV_EXEC_LOG(...) do { \ +} while (NO) +#endif diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegate.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegate.h new file mode 100644 index 0000000..45869bd --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegate.h @@ -0,0 +1,49 @@ +/* + 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 "CDVInvokedUrlCommand.h" + +@class CDVPlugin; +@class CDVPluginResult; + +typedef NSURL* (^ UrlTransformerBlock)(NSURL*); + +@protocol CDVCommandDelegate + +@property (nonatomic, readonly) NSDictionary* settings; +@property (nonatomic, copy) UrlTransformerBlock urlTransformer; + +- (NSString*)pathForResource:(NSString*)resourcepath; +- (id)getCommandInstance:(NSString*)pluginName; + +// Sends a plugin result to the JS. This is thread-safe. +- (void)sendPluginResult:(CDVPluginResult*)result callbackId:(NSString*)callbackId; +// Evaluates the given JS. This is thread-safe. +- (void)evalJs:(NSString*)js; +// Can be used to evaluate JS right away instead of scheduling it on the run-loop. +// This is required for dispatch resign and pause events, but should not be used +// without reason. Without the run-loop delay, alerts used in JS callbacks may result +// in dead-lock. This method must be called from the UI thread. +- (void)evalJs:(NSString*)js scheduledOnRunLoop:(BOOL)scheduledOnRunLoop; +// Run the javascript +- (void)evalJsHelper2:(NSString*)js; +// Runs the given block on a background thread using a shared thread-pool. +- (void)runInBackground:(void (^)(void))block; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegateImpl.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegateImpl.h new file mode 100644 index 0000000..f42654e --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegateImpl.h @@ -0,0 +1,39 @@ +/* + 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 +#import "CDVCommandDelegate.h" +#import +#import "CDVPluginManager.h" + +@class CDVViewController; +@class CDVCommandQueue; + +@interface CDVCommandDelegateImpl : NSObject { + @private + __weak WKWebView* _webView; + __weak CDVPluginManager* _manager; + NSRegularExpression* _callbackIdPattern; + @protected + __weak CDVCommandQueue* _commandQueue; + BOOL _delayResponses; +} +- (id)initWithWebView:(WKWebView*)webView pluginManager:(CDVPluginManager *)manager; +- (void)flushCommandQueueWithDelayedJs; +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegateImpl.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegateImpl.m new file mode 100644 index 0000000..29a02b7 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVCommandDelegateImpl.m @@ -0,0 +1,149 @@ +/* + 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 "CDVCommandDelegateImpl.h" +#import "CDVPluginResult.h" +#import + +@implementation CDVCommandDelegateImpl + +@synthesize urlTransformer; + +- (id)initWithWebView:(WKWebView*)webView pluginManager:(CDVPluginManager *)manager +{ + self = [super init]; + if (self != nil) { + _webView = webView; + _manager = manager; + NSError* err = nil; + _callbackIdPattern = [NSRegularExpression regularExpressionWithPattern:@"[^A-Za-z0-9._-]" options:0 error:&err]; + if (err != nil) { + // Couldn't initialize Regex + NSLog(@"Error: Couldn't initialize regex"); + _callbackIdPattern = nil; + } + } + return self; +} + +- (NSString*)pathForResource:(NSString*)resourcepath +{ + NSBundle* mainBundle = [NSBundle mainBundle]; + NSMutableArray* directoryParts = [NSMutableArray arrayWithArray:[resourcepath componentsSeparatedByString:@"/"]]; + NSString* filename = [directoryParts lastObject]; + + [directoryParts removeLastObject]; + + NSString* directoryPartsJoined = [directoryParts componentsJoinedByString:@"/"]; + NSString* baseFolder = @"public"; + NSString* directoryStr = baseFolder; + + if ([directoryPartsJoined length] > 0) { + directoryStr = [NSString stringWithFormat:@"%@/%@", baseFolder, [directoryParts componentsJoinedByString:@"/"]]; + } + + return [mainBundle pathForResource:filename ofType:@"" inDirectory:directoryStr]; +} + +- (void)flushCommandQueueWithDelayedJs +{ + _delayResponses = YES; + _delayResponses = NO; +} + +- (void)evalJsHelper2:(NSString*)js +{ + dispatch_async(dispatch_get_main_queue(), ^{ + [self->_webView evaluateJavaScript:js completionHandler:^(id obj, NSError* error) { + // TODO: obj can be something other than string + if ([obj isKindOfClass:[NSString class]]) { + NSString* commandsJSON = (NSString*)obj; + if ([commandsJSON length] > 0) { + NSLog(@"Exec: Retrieved new exec messages by chaining."); + } + } + }]; + }); +} + +- (BOOL)isValidCallbackId:(NSString*)callbackId +{ + if ((callbackId == nil) || (_callbackIdPattern == nil)) { + return NO; + } + + // Disallow if too long or if any invalid characters were found. + if (([callbackId length] > 100) || [_callbackIdPattern firstMatchInString:callbackId options:0 range:NSMakeRange(0, [callbackId length])]) { + return NO; + } + return YES; +} + +- (void)sendPluginResult:(CDVPluginResult*)result callbackId:(NSString*)callbackId +{ + // This occurs when there is are no win/fail callbacks for the call. + if ([@"INVALID" isEqualToString:callbackId]) { + return; + } + // This occurs when the callback id is malformed. + if (![self isValidCallbackId:callbackId]) { + NSLog(@"Invalid callback id received by sendPluginResult"); + return; + } + int status = [result.status intValue]; + BOOL keepCallback = [result.keepCallback boolValue]; + NSString* argumentsAsJSON = [result argumentsAsJSON]; + BOOL debug = NO; + +#ifdef DEBUG + debug = YES; +#endif + + NSString* js = [NSString stringWithFormat:@"cordova.require('cordova/exec').nativeCallback('%@',%d,%@,%d, %d)", callbackId, status, argumentsAsJSON, keepCallback, debug]; + + [self evalJsHelper2:js]; +} + +- (void)evalJs:(NSString*)js +{ + [self evalJs:js scheduledOnRunLoop:YES]; +} + +- (void)evalJs:(NSString*)js scheduledOnRunLoop:(BOOL)scheduledOnRunLoop +{ + js = [NSString stringWithFormat:@"try{cordova.require('cordova/exec').nativeEvalAndFetch(function(){%@})}catch(e){console.log('exception nativeEvalAndFetch : '+e);};", js]; + [self evalJsHelper2:js]; +} + +- (id)getCommandInstance:(NSString*)pluginName +{ + return [_manager getCommandInstance:pluginName]; +} + +- (void)runInBackground:(void (^)(void))block +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block); +} + +- (NSDictionary*)settings +{ + return _manager.settings; +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVConfigParser.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVConfigParser.h new file mode 100644 index 0000000..68fdbe6 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVConfigParser.h @@ -0,0 +1,31 @@ +/* + 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 + +@interface CDVConfigParser : NSObject +{ + NSString* featureName; +} + +@property (nonatomic, readonly, strong) NSMutableDictionary* pluginsDict; +@property (nonatomic, readonly, strong) NSMutableDictionary* settings; +@property (nonatomic, readonly, strong) NSMutableArray* startupPluginNames; +@property (nonatomic, readonly, strong) NSString* startPage; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVConfigParser.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVConfigParser.m new file mode 100644 index 0000000..ab32b4a --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVConfigParser.m @@ -0,0 +1,81 @@ +/* + 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 "CDVConfigParser.h" + +@interface CDVConfigParser () + +@property (nonatomic, readwrite, strong) NSMutableDictionary* pluginsDict; +@property (nonatomic, readwrite, strong) NSMutableDictionary* settings; +@property (nonatomic, readwrite, strong) NSMutableArray* startupPluginNames; +@property (nonatomic, readwrite, strong) NSString* startPage; + +@end + +@implementation CDVConfigParser + +@synthesize pluginsDict, settings, startPage, startupPluginNames; + +- (id)init +{ + self = [super init]; + if (self != nil) { + self.pluginsDict = [[NSMutableDictionary alloc] initWithCapacity:30]; + self.settings = [[NSMutableDictionary alloc] initWithCapacity:30]; + self.startupPluginNames = [[NSMutableArray alloc] initWithCapacity:8]; + featureName = nil; + } + return self; +} + +- (void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict +{ + if ([elementName isEqualToString:@"preference"]) { + settings[[attributeDict[@"name"] lowercaseString]] = attributeDict[@"value"]; + } else if ([elementName isEqualToString:@"feature"]) { // store feature name to use with correct parameter set + featureName = [attributeDict[@"name"] lowercaseString]; + } else if ((featureName != nil) && [elementName isEqualToString:@"param"]) { + NSString* paramName = [attributeDict[@"name"] lowercaseString]; + id value = attributeDict[@"value"]; + if ([paramName isEqualToString:@"ios-package"]) { + pluginsDict[featureName] = value; + } + BOOL paramIsOnload = ([paramName isEqualToString:@"onload"] && [@"true" isEqualToString : value]); + BOOL attribIsOnload = [@"true" isEqualToString :[attributeDict[@"onload"] lowercaseString]]; + if (paramIsOnload || attribIsOnload) { + [self.startupPluginNames addObject:featureName]; + } + } else if ([elementName isEqualToString:@"content"]) { + self.startPage = attributeDict[@"src"]; + } +} + +- (void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName +{ + if ([elementName isEqualToString:@"feature"]) { // no longer handling a feature so release + featureName = nil; + } +} + +- (void)parser:(NSXMLParser*)parser parseErrorOccurred:(NSError*)parseError +{ + NSAssert(NO, @"config.xml parse error line %ld col %ld", (long)[parser lineNumber], (long)[parser columnNumber]); +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVInvokedUrlCommand.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVInvokedUrlCommand.h new file mode 100644 index 0000000..993e0a2 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVInvokedUrlCommand.h @@ -0,0 +1,52 @@ +/* + 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 + +@interface CDVInvokedUrlCommand : NSObject { + NSString* _callbackId; + NSString* _className; + NSString* _methodName; + NSArray* _arguments; +} + +@property (nonatomic, readonly) NSArray* arguments; +@property (nonatomic, readonly) NSString* callbackId; +@property (nonatomic, readonly) NSString* className; +@property (nonatomic, readonly) NSString* methodName; + ++ (CDVInvokedUrlCommand*)commandFromJson:(NSArray*)jsonEntry; + +- (id)initWithArguments:(NSArray*)arguments + callbackId:(NSString*)callbackId + className:(NSString*)className + methodName:(NSString*)methodName; + +- (id)initFromJson:(NSArray*)jsonEntry; + +// Returns the argument at the given index. +// If index >= the number of arguments, returns nil. +// If the argument at the given index is NSNull, returns nil. +- (id)argumentAtIndex:(NSUInteger)index; +// Same as above, but returns defaultValue instead of nil. +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue; +// Same as above, but returns defaultValue instead of nil, and if the argument is not of the expected class, returns defaultValue +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue andClass:(Class)aClass; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVInvokedUrlCommand.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVInvokedUrlCommand.m new file mode 100644 index 0000000..fd42dd1 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVInvokedUrlCommand.m @@ -0,0 +1,116 @@ +/* + 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 "CDVInvokedUrlCommand.h" + + +@implementation CDVInvokedUrlCommand + +@synthesize arguments = _arguments; +@synthesize callbackId = _callbackId; +@synthesize className = _className; +@synthesize methodName = _methodName; + ++ (CDVInvokedUrlCommand*)commandFromJson:(NSArray*)jsonEntry +{ + return [[CDVInvokedUrlCommand alloc] initFromJson:jsonEntry]; +} + +- (id)initFromJson:(NSArray*)jsonEntry +{ + id tmp = [jsonEntry objectAtIndex:0]; + NSString* callbackId = tmp == [NSNull null] ? nil : tmp; + NSString* className = [jsonEntry objectAtIndex:1]; + NSString* methodName = [jsonEntry objectAtIndex:2]; + NSMutableArray* arguments = [jsonEntry objectAtIndex:3]; + + return [self initWithArguments:arguments + callbackId:callbackId + className:className + methodName:methodName]; +} + +- (id)initWithArguments:(NSArray*)arguments + callbackId:(NSString*)callbackId + className:(NSString*)className + methodName:(NSString*)methodName +{ + self = [super init]; + if (self != nil) { + _arguments = arguments; + _callbackId = callbackId; + _className = className; + _methodName = methodName; + } + [self massageArguments]; + return self; +} + +- (void)massageArguments +{ + NSMutableArray* newArgs = nil; + + for (NSUInteger i = 0, count = [_arguments count]; i < count; ++i) { + id arg = [_arguments objectAtIndex:i]; + if (![arg isKindOfClass:[NSDictionary class]]) { + continue; + } + NSDictionary* dict = arg; + NSString* type = [dict objectForKey:@"CDVType"]; + if (!type || ![type isEqualToString:@"ArrayBuffer"]) { + continue; + } + NSString* data = [dict objectForKey:@"data"]; + if (!data) { + continue; + } + if (newArgs == nil) { + newArgs = [NSMutableArray arrayWithArray:_arguments]; + _arguments = newArgs; + } + [newArgs replaceObjectAtIndex:i withObject:[[NSData alloc] initWithBase64EncodedString:data options:0]]; + } +} + +- (id)argumentAtIndex:(NSUInteger)index +{ + return [self argumentAtIndex:index withDefault:nil]; +} + +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue +{ + return [self argumentAtIndex:index withDefault:defaultValue andClass:nil]; +} + +- (id)argumentAtIndex:(NSUInteger)index withDefault:(id)defaultValue andClass:(Class)aClass +{ + if (index >= [_arguments count]) { + return defaultValue; + } + id ret = [_arguments objectAtIndex:index]; + if (ret == [NSNull null]) { + ret = defaultValue; + } + if ((aClass != nil) && ![ret isKindOfClass:aClass]) { + ret = defaultValue; + } + return ret; +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin+Resources.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin+Resources.h new file mode 100644 index 0000000..cc43b16 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin+Resources.h @@ -0,0 +1,39 @@ +/* + 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 +#import "CDVPlugin.h" + +@interface CDVPlugin (CDVPluginResources) + +/* + This will return the localized string for a key in a .bundle that is named the same as your class + For example, if your plugin class was called Foo, and you have a Spanish localized strings file, it will + try to load the desired key from Foo.bundle/es.lproj/Localizable.strings + */ +- (NSString*)pluginLocalizedString:(NSString*)key; + +/* + This will return the image for a name in a .bundle that is named the same as your class + For example, if your plugin class was called Foo, and you have an image called "bar", + it will try to load the image from Foo.bundle/bar.png (and appropriately named retina versions) + */ +- (UIImage*)pluginImageResource:(NSString*)name; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin+Resources.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin+Resources.m new file mode 100644 index 0000000..5690738 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin+Resources.m @@ -0,0 +1,38 @@ +/* + 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 "CDVPlugin+Resources.h" + +@implementation CDVPlugin (CDVPluginResources) + +- (NSString*)pluginLocalizedString:(NSString*)key +{ + NSBundle* bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:NSStringFromClass([self class]) ofType:@"bundle"]]; + + return [bundle localizedStringForKey:(key) value:nil table:nil]; +} + +- (UIImage*)pluginImageResource:(NSString*)name +{ + NSString* resourceIdentifier = [NSString stringWithFormat:@"%@.bundle/%@", NSStringFromClass([self class]), name]; + + return [UIImage imageNamed:resourceIdentifier]; +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin.h new file mode 100644 index 0000000..29ba4cd --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin.h @@ -0,0 +1,82 @@ +/* + 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 +#import +#import "CDVPluginResult.h" +#import "CDVCommandDelegate.h" +#import "CDVAvailability.h" +#import + +@interface UIView (org_apache_cordova_UIView_Extension) + +@property (nonatomic, weak) UIScrollView* scrollView; + +@end + +extern NSString* const CDVPageDidLoadNotification; +extern NSString* const CDVPluginHandleOpenURLNotification; +extern NSString* const CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification; +extern NSString* const CDVPluginResetNotification; +extern NSString* const CDVViewWillAppearNotification; +extern NSString* const CDVViewDidAppearNotification; +extern NSString* const CDVViewWillDisappearNotification; +extern NSString* const CDVViewDidDisappearNotification; +extern NSString* const CDVViewWillLayoutSubviewsNotification; +extern NSString* const CDVViewDidLayoutSubviewsNotification; +extern NSString* const CDVViewWillTransitionToSizeNotification; + +/* + * The local and remote push notification functionality has been removed from the core in cordova-ios 4.x, + * but these constants have unfortunately have not been removed, but will be removed in 5.x. + * + * To have the same functionality as 3.x, use a third-party plugin or the experimental + * https://github.com/apache/cordova-plugins/tree/master/notification-rebroadcast + */ + + +@interface CDVPlugin : NSObject {} + +- (instancetype)initWithWebViewEngine:(WKWebView *)theWebViewEngine; +@property (nonatomic, weak) UIView* webView; +@property (nonatomic, weak) WKWebView * webViewEngine; +@property (nonatomic, strong) NSString * className; + +@property (nonatomic, weak) UIViewController* viewController; +@property (nonatomic, weak) id commandDelegate; + +- (void)pluginInitialize; + +- (void)handleOpenURL:(NSNotification*)notification; +- (void)onAppTerminate; +- (void)onMemoryWarning; +- (void)onReset; +- (void)dispose; + +/* + // see initWithWebView implementation + - (void) onPause {} + - (void) onResume {} + - (void) onOrientationWillChange {} + - (void) onOrientationDidChange {} + */ + +- (id)appDelegate; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin.m new file mode 100644 index 0000000..010ff3a --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPlugin.m @@ -0,0 +1,154 @@ +/* + 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 "CDVPlugin.h" +#include + +@implementation UIView (org_apache_cordova_UIView_Extension) + +@dynamic scrollView; + +- (UIScrollView*)scrollView +{ + SEL scrollViewSelector = NSSelectorFromString(@"scrollView"); + + if ([self respondsToSelector:scrollViewSelector]) { + return ((id (*)(id, SEL))objc_msgSend)(self, scrollViewSelector); + } + + return nil; +} + +@end + +NSString* const CDVPageDidLoadNotification = @"CDVPageDidLoadNotification"; +NSString* const CDVPluginHandleOpenURLNotification = @"CDVPluginHandleOpenURLNotification"; +NSString* const CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification = @"CDVPluginHandleOpenURLWithAppSourceAndAnnotationNotification"; +NSString* const CDVPluginResetNotification = @"CDVPluginResetNotification"; +NSString* const CDVLocalNotification = @"CDVLocalNotification"; +NSString* const CDVRemoteNotification = @"CDVRemoteNotification"; +NSString* const CDVRemoteNotificationError = @"CDVRemoteNotificationError"; +NSString* const CDVViewWillAppearNotification = @"CDVViewWillAppearNotification"; +NSString* const CDVViewDidAppearNotification = @"CDVViewDidAppearNotification"; +NSString* const CDVViewWillDisappearNotification = @"CDVViewWillDisappearNotification"; +NSString* const CDVViewDidDisappearNotification = @"CDVViewDidDisappearNotification"; +NSString* const CDVViewWillLayoutSubviewsNotification = @"CDVViewWillLayoutSubviewsNotification"; +NSString* const CDVViewDidLayoutSubviewsNotification = @"CDVViewDidLayoutSubviewsNotification"; +NSString* const CDVViewWillTransitionToSizeNotification = @"CDVViewWillTransitionToSizeNotification"; + +@interface CDVPlugin () + +@property (readwrite, assign) BOOL hasPendingOperation; + +@end + +@implementation CDVPlugin +@synthesize webViewEngine, viewController, commandDelegate, hasPendingOperation, webView; + +// Do not override these methods. Use pluginInitialize instead. +- (instancetype)initWithWebViewEngine:(WKWebView *)theWebViewEngine +{ + self = [super init]; + if (self) { + self.webViewEngine = theWebViewEngine; + } + return self; +} + +- (void)pluginInitialize +{ + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppTerminate) name:UIApplicationWillTerminateNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:CDVPluginHandleOpenURLNotification object:nil]; + // You can listen to more app notifications, see: + // http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006728-CH3-DontLinkElementID_4 + + // NOTE: if you want to use these, make sure you uncomment the corresponding notification handler + + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onOrientationWillChange) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onOrientationDidChange) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; + + // Added in 2.5.0 + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageDidLoad:) name:CDVPageDidLoadNotification object:self.webView]; + //Added in 4.3.0 + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillAppear:) name:CDVViewWillAppearNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidAppear:) name:CDVViewDidAppearNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillDisappear:) name:CDVViewWillDisappearNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidDisappear:) name:CDVViewDidDisappearNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillLayoutSubviews:) name:CDVViewWillLayoutSubviewsNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidLayoutSubviews:) name:CDVViewDidLayoutSubviewsNotification object:nil]; + // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillTransitionToSize:) name:CDVViewWillTransitionToSizeNotification object:nil]; +} + +- (void)dispose +{ + viewController = nil; + commandDelegate = nil; +} + +/* +// NOTE: for onPause and onResume, calls into JavaScript must not call or trigger any blocking UI, like alerts +- (void) onPause {} +- (void) onResume {} +- (void) onOrientationWillChange {} +- (void) onOrientationDidChange {} +*/ + +/* NOTE: calls into JavaScript must not call or trigger any blocking UI, like alerts */ +- (void)handleOpenURL:(NSNotification*)notification +{ + // override to handle urls sent to your app + // register your url schemes in your App-Info.plist + + NSURL* url = [notification object]; + + if ([url isKindOfClass:[NSURL class]]) { + /* Do your thing! */ + } +} + +/* NOTE: calls into JavaScript must not call or trigger any blocking UI, like alerts */ +- (void)onAppTerminate +{ + // override this if you need to do any cleanup on app exit +} + +- (void)onMemoryWarning +{ + // override to remove caches, etc +} + +- (void)onReset +{ + // Override to cancel any long-running requests when the WebView navigates or refreshes. +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; // this will remove all notifications unless added using addObserverForName:object:queue:usingBlock: +} + +- (id)appDelegate +{ + return [[UIApplication sharedApplication] delegate]; +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginManager.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginManager.h new file mode 100644 index 0000000..134959c --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginManager.h @@ -0,0 +1,25 @@ +// +// CDVPluginManager.h +// CapacitorCordova +// +// Created by Julio Cesar Sanchez Hernandez on 26/2/18. +// + +#import +#import "CDVPlugin.h" +#import "CDVConfigParser.h" +#import "CDVCommandDelegate.h" + +@interface CDVPluginManager : NSObject + +@property (nonatomic, strong) NSMutableDictionary * pluginsMap; +@property (nonatomic, strong) NSMutableDictionary * pluginObjects; +@property (nonatomic, strong) NSMutableDictionary * settings; +@property (nonatomic, strong) UIViewController * viewController; +@property (nonatomic, strong) WKWebView * webView; +@property (nonatomic, strong) id commandDelegate; + +- (id)initWithParser:(CDVConfigParser*)parser viewController:(UIViewController*)viewController webView:(WKWebView *)webview; +- (CDVPlugin *)getCommandInstance:(NSString*)pluginName; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginManager.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginManager.m new file mode 100644 index 0000000..37609ac --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginManager.m @@ -0,0 +1,77 @@ +#import "CDVPluginManager.h" +#import "CDVPlugin.h" +#import "CDVCommandDelegateImpl.h" + +@implementation CDVPluginManager + +- (id)initWithParser:(CDVConfigParser*)parser viewController:(UIViewController*)viewController webView:(WKWebView *)webview +{ + self = [super init]; + if (self != nil) { + _pluginsMap = parser.pluginsDict; + _settings = parser.settings; + _viewController = viewController; + _webView = webview; + _pluginObjects = [[NSMutableDictionary alloc] init]; + _commandDelegate = [[CDVCommandDelegateImpl alloc] initWithWebView:_webView pluginManager:self]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackground:) + name:UIApplicationDidEnterBackgroundNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) + name:UIApplicationWillEnterForegroundNotification object:nil]; + } + return self; +} + +/** + Returns an instance of a CordovaCommand object, based on its name. If one exists already, it is returned. + */ +- (CDVPlugin *)getCommandInstance:(NSString*)pluginName +{ + NSString* className = [self.pluginsMap objectForKey:[pluginName lowercaseString]]; + + if (className == nil) { + return nil; + } + + id obj = [self.pluginObjects objectForKey:className]; + if (!obj) { + obj = [[NSClassFromString(className)alloc] initWithWebViewEngine: self.webView]; + if (!obj) { + NSString* fullClassName = [NSString stringWithFormat:@"%@.%@", + NSBundle.mainBundle.infoDictionary[@"CFBundleExecutable"], + className]; + obj = [[NSClassFromString(fullClassName)alloc] initWithWebViewEngine: self.webView]; + } + + if (obj != nil) { + [self registerPlugin:obj withClassName:className]; + } else { + NSLog(@"CDVPlugin class %@ (pluginName: %@) does not exist.", className, pluginName); + } + } + [obj setClassName:className]; + + return obj; +} + + +- (void)registerPlugin:(CDVPlugin*)plugin withClassName:(NSString*)className +{ + [self.pluginObjects setObject:plugin forKey:className]; + plugin.viewController = self.viewController; + plugin.webView = self.webView; + plugin.commandDelegate = self.commandDelegate; + [plugin pluginInitialize]; +} + +- (void)onAppDidEnterBackground:(NSNotification*)notification +{ + [self.commandDelegate evalJsHelper2:@"window.Capacitor.triggerEvent('pause', 'document');"]; +} + +- (void)onAppWillEnterForeground:(NSNotification*)notification +{ + [self.commandDelegate evalJsHelper2:@"window.Capacitor.triggerEvent('resume', 'document');"]; +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginResult.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginResult.h new file mode 100644 index 0000000..2947af8 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginResult.h @@ -0,0 +1,82 @@ +/* + 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 + +typedef NS_ENUM(NSUInteger, CDVCommandStatus) { + CDVCommandStatus_NO_RESULT NS_SWIFT_NAME(noResult) = 0, + CDVCommandStatus_OK NS_SWIFT_NAME(ok), + CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION NS_SWIFT_NAME(classNotFoundException), + CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION NS_SWIFT_NAME(illegalAccessException), + CDVCommandStatus_INSTANTIATION_EXCEPTION NS_SWIFT_NAME(instantiationException), + CDVCommandStatus_MALFORMED_URL_EXCEPTION NS_SWIFT_NAME(malformedUrlException), + CDVCommandStatus_IO_EXCEPTION NS_SWIFT_NAME(ioException), + CDVCommandStatus_INVALID_ACTION NS_SWIFT_NAME(invalidAction), + CDVCommandStatus_JSON_EXCEPTION NS_SWIFT_NAME(jsonException), + CDVCommandStatus_ERROR NS_SWIFT_NAME(error) +}; + +// This exists to preserve compatibility with early Swift plugins, who are +// using CDVCommandStatus as ObjC-style constants rather than as Swift enum +// values. +// This declares extern'ed constants (implemented in CDVPluginResult.m) +#define SWIFT_ENUM_COMPAT_HACK(enumVal) extern const CDVCommandStatus SWIFT_##enumVal NS_SWIFT_NAME(enumVal) +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_NO_RESULT); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_OK); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INSTANTIATION_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_MALFORMED_URL_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_IO_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INVALID_ACTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_JSON_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ERROR); +#undef SWIFT_ENUM_COMPAT_HACK + +@interface CDVPluginResult : NSObject {} + +@property (nonatomic, strong, readonly) NSNumber* status; +@property (nonatomic, strong, readonly) id message; +@property (nonatomic, strong) NSNumber* keepCallback; +// This property can be used to scope the lifetime of another object. For example, +// Use it to store the associated NSData when `message` is created using initWithBytesNoCopy. +@property (nonatomic, strong) id associatedObject; + +- (CDVPluginResult*)init; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsString:(NSString*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArray:(NSArray*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsInt:(int)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsNSInteger:(NSInteger)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsNSUInteger:(NSUInteger)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDouble:(double)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsBool:(BOOL)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDictionary:(NSDictionary*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArrayBuffer:(NSData*)theMessage; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsMultipart:(NSArray*)theMessages; ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageToErrorObject:(int)errorCode; + ++ (void)setVerbose:(BOOL)verbose; ++ (BOOL)isVerbose; + +- (void)setKeepCallbackAsBool:(BOOL)bKeepCallback; + +- (NSString*)argumentsAsJSON; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginResult.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginResult.m new file mode 100644 index 0000000..80e6914 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginResult.m @@ -0,0 +1,216 @@ +/* + 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 "CDVPluginResult.h" + +// This exists to preserve compatibility with early Swift plugins, who are +// using CDVCommandStatus as ObjC-style constants rather than as Swift enum +// values. +// These constants alias the enum values back to their previous names. +#define SWIFT_ENUM_COMPAT_HACK(enumVal) const CDVCommandStatus SWIFT_##enumVal NS_SWIFT_NAME(enumVal) = enumVal +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_NO_RESULT); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_OK); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_CLASS_NOT_FOUND_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INSTANTIATION_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_MALFORMED_URL_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_IO_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_INVALID_ACTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_JSON_EXCEPTION); +SWIFT_ENUM_COMPAT_HACK(CDVCommandStatus_ERROR); +#undef SWIFT_ENUM_COMPAT_HACK + +@interface CDVPluginResult () + +- (CDVPluginResult*)initWithStatus:(CDVCommandStatus)statusOrdinal message:(id)theMessage; + +@end + +@implementation CDVPluginResult +@synthesize status, message, keepCallback, associatedObject; + +static NSArray* org_apache_cordova_CommandStatusMsgs; + +id messageFromArrayBuffer(NSData* data) +{ + return @{ + @"CDVType" : @"ArrayBuffer", + @"data" :[data base64EncodedStringWithOptions:0] + }; +} + +id massageMessage(id message) +{ + if ([message isKindOfClass:[NSData class]]) { + return messageFromArrayBuffer(message); + } + return message; +} + +id messageFromMultipart(NSArray* theMessages) +{ + NSMutableArray* messages = [NSMutableArray arrayWithArray:theMessages]; + + for (NSUInteger i = 0; i < messages.count; ++i) { + [messages replaceObjectAtIndex:i withObject:massageMessage([messages objectAtIndex:i])]; + } + + return @{ + @"CDVType" : @"MultiPart", + @"messages" : messages + }; +} + ++ (void)initialize +{ + org_apache_cordova_CommandStatusMsgs = [[NSArray alloc] initWithObjects:@"No result", + @"OK", + @"Class not found", + @"Illegal access", + @"Instantiation error", + @"Malformed url", + @"IO error", + @"Invalid action", + @"JSON error", + @"Error", + nil]; +} + +- (CDVPluginResult*)init +{ + return [self initWithStatus:CDVCommandStatus_NO_RESULT message:nil]; +} + +- (CDVPluginResult*)initWithStatus:(CDVCommandStatus)statusOrdinal message:(id)theMessage +{ + self = [super init]; + if (self) { + status = [NSNumber numberWithUnsignedLong:statusOrdinal]; + message = theMessage; + keepCallback = [NSNumber numberWithBool:NO]; + } + return self; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal +{ + return [[self alloc] initWithStatus:statusOrdinal message:nil]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsString:(NSString*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:theMessage]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArray:(NSArray*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:theMessage]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsInt:(int)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithInt:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsNSInteger:(NSInteger)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithInteger:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsNSUInteger:(NSUInteger)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithUnsignedInteger:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDouble:(double)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithDouble:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsBool:(BOOL)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:[NSNumber numberWithBool:theMessage]]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsDictionary:(NSDictionary*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:theMessage]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsArrayBuffer:(NSData*)theMessage +{ + return [[self alloc] initWithStatus:statusOrdinal message:messageFromArrayBuffer(theMessage)]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAsMultipart:(NSArray*)theMessages +{ + return [[self alloc] initWithStatus:statusOrdinal message:messageFromMultipart(theMessages)]; +} + ++ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageToErrorObject:(int)errorCode +{ + NSDictionary* errDict = @{@"code" :[NSNumber numberWithInt:errorCode]}; + + return [[self alloc] initWithStatus:statusOrdinal message:errDict]; +} + +- (void)setKeepCallbackAsBool:(BOOL)bKeepCallback +{ + [self setKeepCallback:[NSNumber numberWithBool:bKeepCallback]]; +} + +- (NSString*)argumentsAsJSON +{ + id arguments = (self.message == nil ? [NSNull null] : self.message); + NSArray* argumentsWrappedInArray = [NSArray arrayWithObject:arguments]; + + NSString* argumentsJSON = [self JSONStringFromArray:argumentsWrappedInArray]; + + argumentsJSON = [argumentsJSON substringWithRange:NSMakeRange(1, [argumentsJSON length] - 2)]; + + return argumentsJSON; +} + +static BOOL gIsVerbose = NO; ++ (void)setVerbose:(BOOL)verbose +{ + gIsVerbose = verbose; +} + ++ (BOOL)isVerbose +{ + return gIsVerbose; +} + +- (NSString*)JSONStringFromArray:(NSArray *) array +{ + NSError* error = nil; + NSData* jsonData = [NSJSONSerialization dataWithJSONObject:array + options:0 + error:&error]; + + if (error != nil) { + NSLog(@"NSArray JSONString error: %@", [error localizedDescription]); + return nil; + } else { + return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + } +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVScreenOrientationDelegate.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVScreenOrientationDelegate.h new file mode 100644 index 0000000..519dd49 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVScreenOrientationDelegate.h @@ -0,0 +1,33 @@ +/* + 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 + +@protocol CDVScreenOrientationDelegate + +#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000 +- (NSUInteger)supportedInterfaceOrientations; +#else +- (UIInterfaceOrientationMask)supportedInterfaceOrientations; +#endif + +- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; +- (BOOL)shouldAutorotate; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVURLProtocol.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVURLProtocol.h new file mode 100644 index 0000000..0561e04 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVURLProtocol.h @@ -0,0 +1,27 @@ +/* + 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 +#import "CDVAvailability.h" + +@class CDVViewController; + +@interface CDVURLProtocol : NSURLProtocol {} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVURLProtocol.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVURLProtocol.m new file mode 100644 index 0000000..e9cdfb6 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVURLProtocol.m @@ -0,0 +1,74 @@ +/* + 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 +#import "CDVURLProtocol.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 +{ + return NO; +} + ++ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request +{ + // NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd)); + return request; +} + +- (void)startLoading +{ + return; +} + +- (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]; +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVViewController.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVViewController.h new file mode 100644 index 0000000..81ed006 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVViewController.h @@ -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. + */ + +#import + +@interface CDVViewController : UIViewController + +@property (nonatomic, readonly, strong) NSMutableDictionary* pluginObjects; +@property (nonatomic, readonly, strong) NSMutableDictionary* settings; +@property (nonatomic, readonly, weak) UIView* webView; + +- (id) getCommandInstance:(NSString*)className; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVViewController.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVViewController.m new file mode 100644 index 0000000..1f23362 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVViewController.m @@ -0,0 +1,37 @@ +/* + 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 "CDVViewController.h" + +@interface CDVViewController () { + +} + + +@property (nonatomic, readwrite, strong) NSMutableDictionary* pluginObjects; + +@end + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wincomplete-implementation" +@implementation CDVViewController + +@end +#pragma clang diagnostic pop diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVWebViewProcessPoolFactory.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVWebViewProcessPoolFactory.h new file mode 100644 index 0000000..b156289 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVWebViewProcessPoolFactory.h @@ -0,0 +1,27 @@ +/* + 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 + +@interface CDVWebViewProcessPoolFactory : NSObject +@property (nonatomic, retain) WKProcessPool* sharedPool; + ++(instancetype) sharedFactory; +-(WKProcessPool*) sharedProcessPool; +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVWebViewProcessPoolFactory.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVWebViewProcessPoolFactory.m new file mode 100644 index 0000000..3781f48 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVWebViewProcessPoolFactory.m @@ -0,0 +1,49 @@ +/* + 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 Foundation; +@import WebKit; +#import + +static CDVWebViewProcessPoolFactory *factory = nil; + +@implementation CDVWebViewProcessPoolFactory + ++ (instancetype)sharedFactory +{ + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + factory = [[CDVWebViewProcessPoolFactory alloc] init]; + }); + + return factory; +} + +- (instancetype)init +{ + if (self = [super init]) { + _sharedPool = [[WKProcessPool alloc] init]; + } + return self; +} + +- (WKProcessPool*) sharedProcessPool { + return _sharedPool; +} +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/NSDictionary+CordovaPreferences.h b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/NSDictionary+CordovaPreferences.h new file mode 100644 index 0000000..9be2be2 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/NSDictionary+CordovaPreferences.h @@ -0,0 +1,35 @@ +/* + 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 +#import + +@interface NSDictionary (CordovaPreferences) + +- (id)cordovaSettingForKey:(NSString*)key; +- (BOOL)cordovaBoolSettingForKey:(NSString*)key defaultValue:(BOOL)defaultValue; +- (CGFloat)cordovaFloatSettingForKey:(NSString*)key defaultValue:(CGFloat)defaultValue; + +@end + +@interface NSMutableDictionary (CordovaPreferences) + +- (void)setCordovaSetting:(id)value forKey:(NSString*)key; + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/NSDictionary+CordovaPreferences.m b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/NSDictionary+CordovaPreferences.m new file mode 100644 index 0000000..dcac40f --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Classes/Public/NSDictionary+CordovaPreferences.m @@ -0,0 +1,63 @@ +/* + 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 "NSDictionary+CordovaPreferences.h" +#import + +@implementation NSDictionary (CordovaPreferences) + +- (id)cordovaSettingForKey:(NSString*)key +{ + return [self objectForKey:[key lowercaseString]]; +} + +- (BOOL)cordovaBoolSettingForKey:(NSString*)key defaultValue:(BOOL)defaultValue +{ + BOOL value = defaultValue; + id prefObj = [self cordovaSettingForKey:key]; + + if (prefObj != nil) { + value = [(NSNumber*)prefObj boolValue]; + } + + return value; +} + +- (CGFloat)cordovaFloatSettingForKey:(NSString*)key defaultValue:(CGFloat)defaultValue +{ + CGFloat value = defaultValue; + id prefObj = [self cordovaSettingForKey:key]; + + if (prefObj != nil) { + value = [prefObj floatValue]; + } + + return value; +} + +@end + +@implementation NSMutableDictionary (CordovaPreferences) + +- (void)setCordovaSetting:(id)value forKey:(NSString*)key +{ + [self setObject:value forKey:[key lowercaseString]]; +} + +@end diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Info.plist b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Info.plist new file mode 100644 index 0000000..1483c47 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Cordova + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/PrivacyInfo.xcprivacy b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..e3c6072 --- /dev/null +++ b/node_modules/@capacitor/ios/CapacitorCordova/CapacitorCordova/PrivacyInfo.xcprivacy @@ -0,0 +1,14 @@ + + + + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyTracking + + NSPrivacyAccessedAPITypes + + + diff --git a/node_modules/@capacitor/ios/LICENSE b/node_modules/@capacitor/ios/LICENSE new file mode 100644 index 0000000..c3e903b --- /dev/null +++ b/node_modules/@capacitor/ios/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-present Drifty Co. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall 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. diff --git a/node_modules/@capacitor/ios/package.json b/node_modules/@capacitor/ios/package.json new file mode 100644 index 0000000..9fdd600 --- /dev/null +++ b/node_modules/@capacitor/ios/package.json @@ -0,0 +1,33 @@ +{ + "name": "@capacitor/ios", + "version": "5.7.8", + "description": "Capacitor: Cross-platform apps with JavaScript and the web", + "homepage": "https://capacitorjs.com", + "author": "Ionic Team (https://ionic.io)", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ionic-team/capacitor.git" + }, + "bugs": { + "url": "https://github.com/ionic-team/capacitor/issues" + }, + "files": [ + "Capacitor/Capacitor/", + "CapacitorCordova/CapacitorCordova/", + "Capacitor.podspec", + "CapacitorCordova.podspec", + "scripts/pods_helpers.rb" + ], + "scripts": { + "verify": "npm run xc:build:Capacitor && npm run xc:build:CapacitorCordova", + "xc:build:Capacitor": "cd Capacitor && xcodebuild -workspace Capacitor.xcworkspace -scheme Capacitor && cd ..", + "xc:build:CapacitorCordova": "cd CapacitorCordova && xcodebuild && cd .." + }, + "peerDependencies": { + "@capacitor/core": "^5.7.0" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/@capacitor/ios/scripts/pods_helpers.rb b/node_modules/@capacitor/ios/scripts/pods_helpers.rb new file mode 100644 index 0000000..3fff52f --- /dev/null +++ b/node_modules/@capacitor/ios/scripts/pods_helpers.rb @@ -0,0 +1,18 @@ +def assertDeploymentTarget(installer) + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + # ensure IPHONEOS_DEPLOYMENT_TARGET is at least 13.0 + deployment_target = config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'].to_f + should_upgrade = deployment_target < 13.0 && deployment_target != 0.0 + if should_upgrade + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0' + end + # workaround for Xcode 15 and Cocoapods + # Should not be needed after Cocoapods 1.13.0 + xcconfig_path = config.base_configuration_reference.real_path + xcconfig = File.read(xcconfig_path) + xcconfig_mod = xcconfig.gsub(/DT_TOOLCHAIN_DIR/, "TOOLCHAIN_DIR") + File.open(xcconfig_path, "w") { |file| file << xcconfig_mod } + end + end +end \ No newline at end of file diff --git a/node_modules/@typescript/typescript-linux-x64/LICENSE b/node_modules/@typescript/typescript-linux-x64/LICENSE deleted file mode 100644 index 8746124..0000000 --- a/node_modules/@typescript/typescript-linux-x64/LICENSE +++ /dev/null @@ -1,55 +0,0 @@ -Apache License - -Version 2.0, January 2004 - -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and - -You must cause any modified files to carry prominent notices stating that You changed the files; and - -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and - -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS diff --git a/node_modules/@typescript/typescript-linux-x64/NOTICE.txt b/node_modules/@typescript/typescript-linux-x64/NOTICE.txt deleted file mode 100644 index 0c40b1e..0000000 --- a/node_modules/@typescript/typescript-linux-x64/NOTICE.txt +++ /dev/null @@ -1,436 +0,0 @@ -NOTICES AND INFORMATION -Do Not Translate or Localize - -This software incorporates material from third parties. -Microsoft makes certain open source code available at https://3rdpartysource.microsoft.com, -or you may send a check or money order for US $5.00, including the product name, -the open source component name, platform, and version number, to: - -Source Code Compliance Team -Microsoft Corporation -One Microsoft Way -Redmond, WA 98052 -USA - -Notwithstanding any other terms, you may reverse engineer this software to the extent -required to debug changes to any libraries licensed under the GNU Lesser General Public License. - - -------------------- DefinitelyTyped -------------------- -This file is based on or incorporates material from the projects listed below (collectively "Third Party Code"). Microsoft is not the original author of the Third Party Code. The original copyright notice and the license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms set forth in the EULA for the Microsoft Product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise. -DefinitelyTyped -This project is licensed under the MIT license. Copyrights are respective of each contributor listed at the beginning of each definition file. Provided for Informational Purposes Only - -MIT License -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall 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. --------------------------------------------------------------------------------------- - -------------------- Unicode -------------------- -UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE - -Unicode Data Files include all data files under the directories -http://www.unicode.org/Public/, http://www.unicode.org/reports/, -http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and -http://www.unicode.org/utility/trac/browser/. - -Unicode Data Files do not include PDF online code charts under the -directory http://www.unicode.org/Public/. - -Software includes any source code published in the Unicode Standard -or under the directories -http://www.unicode.org/Public/, http://www.unicode.org/reports/, -http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and -http://www.unicode.org/utility/trac/browser/. - -NOTICE TO USER: Carefully read the following legal agreement. -BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S -DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), -YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE -TERMS AND CONDITIONS OF THIS AGREEMENT. -IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE -THE DATA FILES OR SOFTWARE. - -COPYRIGHT AND PERMISSION NOTICE - -Copyright (c) 1991-2017 Unicode, Inc. All rights reserved. -Distributed under the Terms of Use in http://www.unicode.org/copyright.html. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Unicode data files and any associated documentation -(the "Data Files") or Unicode software and any associated documentation -(the "Software") to deal in the Data Files or Software -without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, and/or sell copies of -the Data Files or Software, and to permit persons to whom the Data Files -or Software are furnished to do so, provided that either -(a) this copyright and permission notice appear with all copies -of the Data Files or Software, or -(b) this copyright and permission notice appear in associated -Documentation. - -THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS. -IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS -NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL -DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, -DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THE DATA FILES OR SOFTWARE. - -Except as contained in this notice, the name of a copyright holder -shall not be used in advertising or otherwise to promote the sale, -use or other dealings in these Data Files or Software without prior -written authorization of the copyright holder. -------------------------------------------------------------------------------------- - --------------------Document Object Model----------------------------- -DOM - -W3C License -This work is being provided by the copyright holders under the following license. -By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. -Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following -on ALL copies of the work or portions thereof, including modifications: -* The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. -* Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. -* Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived -from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." -Disclaimers -THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR -FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. -COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. -The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. -Title to copyright in this work will at all times remain with copyright holders. - ---------- - -DOM -Copyright © 2018 WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License: Attribution 4.0 International -======================================================================= -Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: - -wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= -Creative Commons Attribution 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. - --------------------------------------------------------------------------------- - -----------------------Web Background Synchronization------------------------------ - -Web Background Synchronization Specification -Portions of spec © by W3C - -W3C Community Final Specification Agreement -To secure commitments from participants for the full text of a Community or Business Group Report, the group may call for voluntary commitments to the following terms; a "summary" is -available. See also the related "W3C Community Contributor License Agreement". -1. The Purpose of this Agreement. -This Agreement sets forth the terms under which I make certain copyright and patent rights available to you for your implementation of the Specification. -Any other capitalized terms not specifically defined herein have the same meaning as those terms have in the "W3C Patent Policy", and if not defined there, in the "W3C Process Document". -2. Copyrights. -2.1. Copyright Grant. I grant to you a perpetual (for the duration of the applicable copyright), worldwide, non-exclusive, no-charge, royalty-free, copyright license, without any obligation for accounting to me, to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, distribute, and implement the Specification to the full extent of my copyright interest in the Specification. -2.2. Attribution. As a condition of the copyright grant, you must include an attribution to the Specification in any derivative work you make based on the Specification. That attribution must include, at minimum, the Specification name and version number. -3. Patents. -3.1. Patent Licensing Commitment. I agree to license my Essential Claims under the W3C Community RF Licensing Requirements. This requirement includes Essential Claims that I own and any that I have the right to license without obligation of payment or other consideration to an unrelated third party. W3C Community RF Licensing Requirements obligations made concerning the Specification and described in this policy are binding on me for the life of the patents in question and encumber the patents containing Essential Claims, regardless of changes in participation status or W3C Membership. I also agree to license my Essential Claims under the W3C Community RF Licensing Requirements in derivative works of the Specification so long as all normative portions of the Specification are maintained and that this licensing commitment does not extend to any portion of the derivative work that was not included in the Specification. -3.2. Optional, Additional Patent Grant. In addition to the provisions of Section 3.1, I may also, at my option, make certain intellectual property rights infringed by implementations of the Specification, including Essential Claims, available by providing those terms via the W3C Web site. -4. No Other Rights. Except as specifically set forth in this Agreement, no other express or implied patent, trademark, copyright, or other property rights are granted under this Agreement, including by implication, waiver, or estoppel. -5. Antitrust Compliance. I acknowledge that I may compete with other participants, that I am under no obligation to implement the Specification, that each participant is free to develop competing technologies and standards, and that each party is free to license its patent rights to third parties, including for the purpose of enabling competing technologies and standards. -6. Non-Circumvention. I agree that I will not intentionally take or willfully assist any third party to take any action for the purpose of circumventing my obligations under this Agreement. -7. Transition to W3C Recommendation Track. The Specification developed by the Project may transition to the W3C Recommendation Track. The W3C Team is responsible for notifying me that a Corresponding Working Group has been chartered. I have no obligation to join the Corresponding Working Group. If the Specification developed by the Project transitions to the W3C Recommendation Track, the following terms apply: -7.1. If I join the Corresponding Working Group. If I join the Corresponding Working Group, I will be subject to all W3C rules, obligations, licensing commitments, and policies that govern that Corresponding Working Group. -7.2. If I Do Not Join the Corresponding Working Group. -7.2.1. Licensing Obligations to Resulting Specification. If I do not join the Corresponding Working Group, I agree to offer patent licenses according to the W3C Royalty-Free licensing requirements described in Section 5 of the W3C Patent Policy for the portions of the Specification included in the resulting Recommendation. This licensing commitment does not extend to any portion of an implementation of the Recommendation that was not included in the Specification. This licensing commitment may not be revoked but may be modified through the exclusion process defined in Section 4 of the W3C Patent Policy. I am not required to join the Corresponding Working Group to exclude patents from the W3C Royalty-Free licensing commitment, but must otherwise follow the normal exclusion procedures defined by the W3C Patent Policy. The W3C Team will notify me of any Call for Exclusion in the Corresponding Working Group as set forth in Section 4.5 of the W3C Patent Policy. -7.2.2. No Disclosure Obligation. If I do not join the Corresponding Working Group, I have no patent disclosure obligations outside of those set forth in Section 6 of the W3C Patent Policy. -8. Conflict of Interest. I will disclose significant relationships when those relationships might reasonably be perceived as creating a conflict of interest with my role. I will notify W3C of any change in my affiliation using W3C-provided mechanisms. -9. Representations, Warranties and Disclaimers. I represent and warrant that I am legally entitled to grant the rights and promises set forth in this Agreement. IN ALL OTHER RESPECTS THE SPECIFICATION IS PROVIDED “AS IS.” The entire risk as to implementing or otherwise using the Specification is assumed by the implementer and user. Except as stated herein, I expressly disclaim any warranties (express, implied, or otherwise), including implied warranties of merchantability, non-infringement, fitness for a particular purpose, or title, related to the Specification. IN NO EVENT WILL ANY PARTY BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS OR ANY FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO THIS AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. All of my obligations under Section 3 regarding the transfer, successors in interest, or assignment of Granted Claims will be satisfied if I notify the transferee or assignee of any patent that I know contains Granted Claims of the obligations under Section 3. Nothing in this Agreement requires me to undertake a patent search. -10. Definitions. -10.1. Agreement. “Agreement” means this W3C Community Final Specification Agreement. -10.2. Corresponding Working Group. “Corresponding Working Group” is a W3C Working Group that is chartered to develop a Recommendation, as defined in the W3C Process Document, that takes the Specification as an input. -10.3. Essential Claims. “Essential Claims” shall mean all claims in any patent or patent application in any jurisdiction in the world that would necessarily be infringed by implementation of the Specification. A claim is necessarily infringed hereunder only when it is not possible to avoid infringing it because there is no non-infringing alternative for implementing the normative portions of the Specification. Existence of a non-infringing alternative shall be judged based on the state of the art at the time of the publication of the Specification. The following are expressly excluded from and shall not be deemed to constitute Essential Claims: -10.3.1. any claims other than as set forth above even if contained in the same patent as Essential Claims; and -10.3.2. claims which would be infringed only by: -portions of an implementation that are not specified in the normative portions of the Specification, or -enabling technologies that may be necessary to make or use any product or portion thereof that complies with the Specification and are not themselves expressly set forth in the Specification (e.g., semiconductor manufacturing technology, compiler technology, object-oriented technology, basic operating system technology, and the like); or -the implementation of technology developed elsewhere and merely incorporated by reference in the body of the Specification. -10.3.3. design patents and design registrations. -For purposes of this definition, the normative portions of the Specification shall be deemed to include only architectural and interoperability requirements. Optional features in the RFC 2119 sense are considered normative unless they are specifically identified as informative. Implementation examples or any other material that merely illustrate the requirements of the Specification are informative, rather than normative. -10.4. I, Me, or My. “I,” “me,” or “my” refers to the signatory. -10.5 Project. “Project” means the W3C Community Group or Business Group for which I executed this Agreement. -10.6. Specification. “Specification” means the Specification identified by the Project as the target of this agreement in a call for Final Specification Commitments. W3C shall provide the authoritative mechanisms for the identification of this Specification. -10.7. W3C Community RF Licensing Requirements. “W3C Community RF Licensing Requirements” license shall mean a non-assignable, non-sublicensable license to make, have made, use, sell, have sold, offer to sell, import, and distribute and dispose of implementations of the Specification that: -10.7.1. shall be available to all, worldwide, whether or not they are W3C Members; -10.7.2. shall extend to all Essential Claims owned or controlled by me; -10.7.3. may be limited to implementations of the Specification, and to what is required by the Specification; -10.7.4. may be conditioned on a grant of a reciprocal RF license (as defined in this policy) to all Essential Claims owned or controlled by the licensee. A reciprocal license may be required to be available to all, and a reciprocal license may itself be conditioned on a further reciprocal license from all. -10.7.5. may not be conditioned on payment of royalties, fees or other consideration; -10.7.6. may be suspended with respect to any licensee when licensor issued by licensee for infringement of claims essential to implement the Specification or any W3C Recommendation; -10.7.7. may not impose any further conditions or restrictions on the use of any technology, intellectual property rights, or other restrictions on behavior of the licensee, but may include reasonable, customary terms relating to operation or maintenance of the license relationship such as the following: choice of law and dispute resolution; -10.7.8. shall not be considered accepted by an implementer who manifests an intent not to accept the terms of the W3C Community RF Licensing Requirements license as offered by the licensor. -10.7.9. The RF license conforming to the requirements in this policy shall be made available by the licensor as long as the Specification is in effect. The term of such license shall be for the life of the patents in question. -I am encouraged to provide a contact from which licensing information can be obtained and other relevant licensing information. Any such information will be made publicly available. -10.8. You or Your. “You,” “you,” or “your” means any person or entity who exercises copyright or patent rights granted under this Agreement, and any person that person or entity controls. - -------------------------------------------------------------------------------------- - -------------------- WebGL ----------------------------- -Copyright (c) 2018 The Khronos Group Inc. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and/or associated documentation files (the -"Materials"), to deal in the Materials without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Materials, and to -permit persons to whom the Materials are furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Materials. - -THE MATERIALS ARE 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 -MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. ------------------------------------------------------- - ---------------------------------------------------------- - -github.com/zeebo/xxh3 v1.1.0 - BSD-2-Clause - - -Copyright (c) 2019, Jeff Wendling -Copyright (c) 2012-2014, Yann Collet - -Copyright (c) . All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ---------------------------------------------------------- - ---------------------------------------------------------- - -github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 - BSD-3-Clause - - -Copyright 2010 The Go Authors -Copyright 2011 The Go Authors -Copyright 2016 The Go Authors -Copyright 2018 The Go Authors -Copyright 2020 The Go Authors -Copyright 2021 The Go Authors -Copyright 2022 The Go Authors -Copyright 2023 The Go Authors -Copyright 2024 The Go Authors -Copyright (c) 2020 The Go Authors - -Copyright (c) . All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - - 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ---------------------------------------------------------- - ---------------------------------------------------------- - -golang.org/x/sync v0.21.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - - -Copyright 2009 The Go Authors -Copyright 2013 The Go Authors -Copyright 2016 The Go Authors -Copyright 2017 The Go Authors -Copyright 2019 The Go Authors - -BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - ---------------------------------------------------------- - ---------------------------------------------------------- - -golang.org/x/sys v0.46.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - - -Copyright 2009 The Go Authors -Copyright 2010 The Go Authors -Copyright 2011 The Go Authors -Copyright 2012 The Go Authors -Copyright 2013 The Go Authors -Copyright 2014 The Go Authors -Copyright 2015 The Go Authors -Copyright 2016 The Go Authors -Copyright 2017 The Go Authors -Copyright 2018 The Go Authors -Copyright 2019 The Go Authors -Copyright 2020 The Go Authors -Copyright 2021 The Go Authors -Copyright 2022 The Go Authors -Copyright 2023 The Go Authors -Copyright 2024 The Go Authors -Copyright 2025 The Go Authors -Copyright 2009,2010 The Go Authors - -BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - ---------------------------------------------------------- - ---------------------------------------------------------- - -golang.org/x/term v0.44.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - - -Copyright 2009 The Go Authors -Copyright 2011 The Go Authors -Copyright 2013 The Go Authors -Copyright 2019 The Go Authors -Copyright 2021 The Go Authors - -BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - ---------------------------------------------------------- - ---------------------------------------------------------- - -golang.org/x/text v0.38.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - - -(c) AeHa (c) -(c) EeAoq (c) -(c) EAiE (c) A -(c) lEEe (c) AE -(c) (c) AAEE (c) -(c) oav!A (c) AY -(c) aA"AE (c) 1AE (c) -Copyright 2009 The Go Authors -Copyright 2011 The Go Authors -Copyright 2012 The Go Authors -Copyright 2013 The Go Authors -Copyright 2014 The Go Authors -Copyright 2015 The Go Authors -Copyright 2016 The Go Authors -Copyright 2017 The Go Authors -Copyright 2018 The Go Authors -Copyright 2019 The Go Authors -Copyright 2021 The Go Authors -Copyright 2025 The Go Authors - -BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang - ---------------------------------------------------------- - ---------------------------------------------------------- - -github.com/klauspost/cpuid/v2 v2.2.10 - MIT - - -Copyright (c) 2015 Klaus Post -Copyright (c) 2020 Klaus Post -Copyright (c) 2021 Klaus Post -Copyright 2018 The Go Authors -Copyright (c) 2015- Klaus Post & Contributors - -MIT License - -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall 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. - ---------------------------------------------------------- - ---------------------------------------------------------- - -github.com/Microsoft/go-winio v0.6.2 - MIT - - -Copyright (c) 2015 Microsoft -Copyright 2013 The Go Authors - -MIT License - -Copyright (c) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall 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. - ---------------------------------------------------------- - ---------------------------------------------------------- - -github.com/mackerelio/go-osstat v0.2.7 - Apache-2.0 - - -Copyright 2017-2019 Hatena Co., Ltd. - -Licensed 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. - ---------------------------------------------------------- - ---------------------------------------------------------- - -parcel-bundler/watcher 8926bb8b281733bbfcaf69bb4e62ab7a1431c42a - MIT - - -Copyright Node.js contributors -Copyright 2012-2020 Facebook, Inc. -Copyright (c) 2017-present Devon Govett - -MIT License - -Copyright (c) 2017-present Devon Govett - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall 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. - - ---------------------------------------------------------- - diff --git a/node_modules/@typescript/typescript-linux-x64/README.md b/node_modules/@typescript/typescript-linux-x64/README.md deleted file mode 100644 index 35143f5..0000000 --- a/node_modules/@typescript/typescript-linux-x64/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `@typescript/typescript-linux-x64` - -This package provides linux-x64 support for [typescript](https://www.npmjs.com/package/typescript). diff --git a/node_modules/@typescript/typescript-linux-x64/lib/lib.d.ts b/node_modules/@typescript/typescript-linux-x64/lib/lib.d.ts deleted file mode 100644 index a80f007..0000000 --- a/node_modules/@typescript/typescript-linux-x64/lib/lib.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed 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 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABILITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - - -/// -/// -/// -/// diff --git a/node_modules/@typescript/typescript-linux-x64/lib/lib.decorators.d.ts b/node_modules/@typescript/typescript-linux-x64/lib/lib.decorators.d.ts deleted file mode 100644 index 83d82be..0000000 --- a/node_modules/@typescript/typescript-linux-x64/lib/lib.decorators.d.ts +++ /dev/null @@ -1,382 +0,0 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed 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 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABILITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - - -/** - * The decorator context types provided to class element decorators. - */ -type ClassMemberDecoratorContext = - | ClassMethodDecoratorContext - | ClassGetterDecoratorContext - | ClassSetterDecoratorContext - | ClassFieldDecoratorContext - | ClassAccessorDecoratorContext; - -/** - * The decorator context types provided to any decorator. - */ -type DecoratorContext = - | ClassDecoratorContext - | ClassMemberDecoratorContext; - -type DecoratorMetadataObject = Record & object; - -type DecoratorMetadata = typeof globalThis extends { Symbol: { readonly metadata: symbol; }; } ? DecoratorMetadataObject : DecoratorMetadataObject | undefined; - -/** - * Context provided to a class decorator. - * @template Class The type of the decorated class associated with this context. - */ -interface ClassDecoratorContext< - Class extends abstract new (...args: any) => any = abstract new (...args: any) => any, -> { - /** The kind of element that was decorated. */ - readonly kind: "class"; - - /** The name of the decorated class. */ - readonly name: string | undefined; - - /** - * Adds a callback to be invoked after the class definition has been finalized. - * - * @example - * ```ts - * function customElement(name: string): ClassDecoratorFunction { - * return (target, context) => { - * context.addInitializer(function () { - * customElements.define(name, this); - * }); - * } - * } - * - * @customElement("my-element") - * class MyElement {} - * ``` - */ - addInitializer(initializer: (this: Class) => void): void; - - readonly metadata: DecoratorMetadata; -} - -/** - * Context provided to a class method decorator. - * @template This The type on which the class element will be defined. For a static class element, this will be - * the type of the constructor. For a non-static class element, this will be the type of the instance. - * @template Value The type of the decorated class method. - */ -interface ClassMethodDecoratorContext< - This = unknown, - Value extends (this: This, ...args: any) => any = (this: This, ...args: any) => any, -> { - /** The kind of class element that was decorated. */ - readonly kind: "method"; - - /** The name of the decorated class element. */ - readonly name: string | symbol; - - /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ - readonly static: boolean; - - /** A value indicating whether the class element has a private name. */ - readonly private: boolean; - - /** An object that can be used to access the current value of the class element at runtime. */ - readonly access: { - /** - * Determines whether an object has a property with the same name as the decorated element. - */ - has(object: This): boolean; - /** - * Gets the current value of the method from the provided object. - * - * @example - * let fn = context.access.get(instance); - */ - get(object: This): Value; - }; - - /** - * Adds a callback to be invoked either after static methods are defined but before - * static initializers are run (when decorating a `static` element), or before instance - * initializers are run (when decorating a non-`static` element). - * - * @example - * ```ts - * const bound: ClassMethodDecoratorFunction = (value, context) { - * if (context.private) throw new TypeError("Not supported on private methods."); - * context.addInitializer(function () { - * this[context.name] = this[context.name].bind(this); - * }); - * } - * - * class C { - * message = "Hello"; - * - * @bound - * m() { - * console.log(this.message); - * } - * } - * ``` - */ - addInitializer(initializer: (this: This) => void): void; - - readonly metadata: DecoratorMetadata; -} - -/** - * Context provided to a class getter decorator. - * @template This The type on which the class element will be defined. For a static class element, this will be - * the type of the constructor. For a non-static class element, this will be the type of the instance. - * @template Value The property type of the decorated class getter. - */ -interface ClassGetterDecoratorContext< - This = unknown, - Value = unknown, -> { - /** The kind of class element that was decorated. */ - readonly kind: "getter"; - - /** The name of the decorated class element. */ - readonly name: string | symbol; - - /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ - readonly static: boolean; - - /** A value indicating whether the class element has a private name. */ - readonly private: boolean; - - /** An object that can be used to access the current value of the class element at runtime. */ - readonly access: { - /** - * Determines whether an object has a property with the same name as the decorated element. - */ - has(object: This): boolean; - /** - * Invokes the getter on the provided object. - * - * @example - * let value = context.access.get(instance); - */ - get(object: This): Value; - }; - - /** - * Adds a callback to be invoked either after static methods are defined but before - * static initializers are run (when decorating a `static` element), or before instance - * initializers are run (when decorating a non-`static` element). - */ - addInitializer(initializer: (this: This) => void): void; - - readonly metadata: DecoratorMetadata; -} - -/** - * Context provided to a class setter decorator. - * @template This The type on which the class element will be defined. For a static class element, this will be - * the type of the constructor. For a non-static class element, this will be the type of the instance. - * @template Value The type of the decorated class setter. - */ -interface ClassSetterDecoratorContext< - This = unknown, - Value = unknown, -> { - /** The kind of class element that was decorated. */ - readonly kind: "setter"; - - /** The name of the decorated class element. */ - readonly name: string | symbol; - - /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ - readonly static: boolean; - - /** A value indicating whether the class element has a private name. */ - readonly private: boolean; - - /** An object that can be used to access the current value of the class element at runtime. */ - readonly access: { - /** - * Determines whether an object has a property with the same name as the decorated element. - */ - has(object: This): boolean; - /** - * Invokes the setter on the provided object. - * - * @example - * context.access.set(instance, value); - */ - set(object: This, value: Value): void; - }; - - /** - * Adds a callback to be invoked either after static methods are defined but before - * static initializers are run (when decorating a `static` element), or before instance - * initializers are run (when decorating a non-`static` element). - */ - addInitializer(initializer: (this: This) => void): void; - - readonly metadata: DecoratorMetadata; -} - -/** - * Context provided to a class `accessor` field decorator. - * @template This The type on which the class element will be defined. For a static class element, this will be - * the type of the constructor. For a non-static class element, this will be the type of the instance. - * @template Value The type of decorated class field. - */ -interface ClassAccessorDecoratorContext< - This = unknown, - Value = unknown, -> { - /** The kind of class element that was decorated. */ - readonly kind: "accessor"; - - /** The name of the decorated class element. */ - readonly name: string | symbol; - - /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ - readonly static: boolean; - - /** A value indicating whether the class element has a private name. */ - readonly private: boolean; - - /** An object that can be used to access the current value of the class element at runtime. */ - readonly access: { - /** - * Determines whether an object has a property with the same name as the decorated element. - */ - has(object: This): boolean; - - /** - * Invokes the getter on the provided object. - * - * @example - * let value = context.access.get(instance); - */ - get(object: This): Value; - - /** - * Invokes the setter on the provided object. - * - * @example - * context.access.set(instance, value); - */ - set(object: This, value: Value): void; - }; - - /** - * Adds a callback to be invoked immediately after the auto `accessor` being - * decorated is initialized (regardless if the `accessor` is `static` or not). - */ - addInitializer(initializer: (this: This) => void): void; - - readonly metadata: DecoratorMetadata; -} - -/** - * Describes the target provided to class `accessor` field decorators. - * @template This The `this` type to which the target applies. - * @template Value The property type for the class `accessor` field. - */ -interface ClassAccessorDecoratorTarget { - /** - * Invokes the getter that was defined prior to decorator application. - * - * @example - * let value = target.get.call(instance); - */ - get(this: This): Value; - - /** - * Invokes the setter that was defined prior to decorator application. - * - * @example - * target.set.call(instance, value); - */ - set(this: This, value: Value): void; -} - -/** - * Describes the allowed return value from a class `accessor` field decorator. - * @template This The `this` type to which the target applies. - * @template Value The property type for the class `accessor` field. - */ -interface ClassAccessorDecoratorResult { - /** - * An optional replacement getter function. If not provided, the existing getter function is used instead. - */ - get?(this: This): Value; - - /** - * An optional replacement setter function. If not provided, the existing setter function is used instead. - */ - set?(this: This, value: Value): void; - - /** - * An optional initializer mutator that is invoked when the underlying field initializer is evaluated. - * @param value The incoming initializer value. - * @returns The replacement initializer value. - */ - init?(this: This, value: Value): Value; -} - -/** - * Context provided to a class field decorator. - * @template This The type on which the class element will be defined. For a static class element, this will be - * the type of the constructor. For a non-static class element, this will be the type of the instance. - * @template Value The type of the decorated class field. - */ -interface ClassFieldDecoratorContext< - This = unknown, - Value = unknown, -> { - /** The kind of class element that was decorated. */ - readonly kind: "field"; - - /** The name of the decorated class element. */ - readonly name: string | symbol; - - /** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */ - readonly static: boolean; - - /** A value indicating whether the class element has a private name. */ - readonly private: boolean; - - /** An object that can be used to access the current value of the class element at runtime. */ - readonly access: { - /** - * Determines whether an object has a property with the same name as the decorated element. - */ - has(object: This): boolean; - - /** - * Gets the value of the field on the provided object. - */ - get(object: This): Value; - - /** - * Sets the value of the field on the provided object. - */ - set(object: This, value: Value): void; - }; - - /** - * Adds a callback to be invoked immediately after the field being decorated - * is initialized (regardless if the field is `static` or not). - */ - addInitializer(initializer: (this: This) => void): void; - - readonly metadata: DecoratorMetadata; -} diff --git a/node_modules/@typescript/typescript-linux-x64/lib/lib.decorators.legacy.d.ts b/node_modules/@typescript/typescript-linux-x64/lib/lib.decorators.legacy.d.ts deleted file mode 100644 index 8977516..0000000 --- a/node_modules/@typescript/typescript-linux-x64/lib/lib.decorators.legacy.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed 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 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABILITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - - -declare type ClassDecorator = (target: TFunction) => TFunction | void; -declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; -declare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; -declare type ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => void; diff --git a/node_modules/@typescript/typescript-linux-x64/lib/lib.dom.asynciterable.d.ts b/node_modules/@typescript/typescript-linux-x64/lib/lib.dom.asynciterable.d.ts deleted file mode 100644 index 075563c..0000000 --- a/node_modules/@typescript/typescript-linux-x64/lib/lib.dom.asynciterable.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed 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 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABILITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - - -// This file's contents are now included in the main types file. -// The file has been left for backward compatibility. diff --git a/node_modules/@typescript/typescript-linux-x64/lib/lib.dom.d.ts b/node_modules/@typescript/typescript-linux-x64/lib/lib.dom.d.ts deleted file mode 100644 index 9e127c3..0000000 --- a/node_modules/@typescript/typescript-linux-x64/lib/lib.dom.d.ts +++ /dev/null @@ -1,45125 +0,0 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed 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 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABILITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - - -/// -/// - -///////////////////////////// -/// Window APIs -///////////////////////////// - -interface AacEncoderConfig { - format?: AacBitstreamFormat; -} - -interface AddEventListenerOptions extends EventListenerOptions { - once?: boolean; - passive?: boolean; - signal?: AbortSignal; -} - -interface AddressErrors { - addressLine?: string; - city?: string; - country?: string; - dependentLocality?: string; - organization?: string; - phone?: string; - postalCode?: string; - recipient?: string; - region?: string; - sortingCode?: string; -} - -interface AesCbcParams extends Algorithm { - iv: BufferSource; -} - -interface AesCtrParams extends Algorithm { - counter: BufferSource; - length: number; -} - -interface AesDerivedKeyParams extends Algorithm { - length: number; -} - -interface AesGcmParams extends Algorithm { - additionalData?: BufferSource; - iv: BufferSource; - tagLength?: number; -} - -interface AesKeyAlgorithm extends KeyAlgorithm { - length: number; -} - -interface AesKeyGenParams extends Algorithm { - length: number; -} - -interface Algorithm { - name: string; -} - -interface AllAcceptedCredentialsOptions { - allAcceptedCredentialIds: Base64URLString[]; - rpId: string; - userId: Base64URLString; -} - -interface AnalyserOptions extends AudioNodeOptions { - fftSize?: number; - maxDecibels?: number; - minDecibels?: number; - smoothingTimeConstant?: number; -} - -interface AnimationEventInit extends EventInit { - animationName?: string; - elapsedTime?: number; - pseudoElement?: string; -} - -interface AnimationPlaybackEventInit extends EventInit { - currentTime?: CSSNumberish | null; - timelineTime?: CSSNumberish | null; -} - -interface AssignedNodesOptions { - flatten?: boolean; -} - -interface AudioBufferOptions { - length: number; - numberOfChannels?: number; - sampleRate: number; -} - -interface AudioBufferSourceOptions { - buffer?: AudioBuffer | null; - detune?: number; - loop?: boolean; - loopEnd?: number; - loopStart?: number; - playbackRate?: number; -} - -interface AudioConfiguration { - bitrate?: number; - channels?: string; - contentType: string; - samplerate?: number; - spatialRendering?: boolean; -} - -interface AudioContextOptions { - latencyHint?: AudioContextLatencyCategory | number; - sampleRate?: number; -} - -interface AudioDataCopyToOptions { - format?: AudioSampleFormat; - frameCount?: number; - frameOffset?: number; - planeIndex: number; -} - -interface AudioDataInit { - data: BufferSource; - format: AudioSampleFormat; - numberOfChannels: number; - numberOfFrames: number; - sampleRate: number; - timestamp: number; - transfer?: ArrayBuffer[]; -} - -interface AudioDecoderConfig { - codec: string; - description?: AllowSharedBufferSource; - numberOfChannels: number; - sampleRate: number; -} - -interface AudioDecoderInit { - error: WebCodecsErrorCallback; - output: AudioDataOutputCallback; -} - -interface AudioDecoderSupport { - config?: AudioDecoderConfig; - supported?: boolean; -} - -interface AudioEncoderConfig { - aac?: AacEncoderConfig; - bitrate?: number; - bitrateMode?: BitrateMode; - codec: string; - numberOfChannels: number; - opus?: OpusEncoderConfig; - sampleRate: number; -} - -interface AudioEncoderInit { - error: WebCodecsErrorCallback; - output: EncodedAudioChunkOutputCallback; -} - -interface AudioEncoderSupport { - config?: AudioEncoderConfig; - supported?: boolean; -} - -interface AudioNodeOptions { - channelCount?: number; - channelCountMode?: ChannelCountMode; - channelInterpretation?: ChannelInterpretation; -} - -interface AudioProcessingEventInit extends EventInit { - inputBuffer: AudioBuffer; - outputBuffer: AudioBuffer; - playbackTime: number; -} - -interface AudioTimestamp { - contextTime?: number; - performanceTime?: DOMHighResTimeStamp; -} - -interface AudioWorkletNodeOptions extends AudioNodeOptions { - numberOfInputs?: number; - numberOfOutputs?: number; - outputChannelCount?: number[]; - parameterData?: Record; - processorOptions?: any; -} - -interface AuthenticationExtensionsClientInputs { - appid?: string; - credProps?: boolean; - credentialProtectionPolicy?: string; - enforceCredentialProtectionPolicy?: boolean; - hmacCreateSecret?: boolean; - largeBlob?: AuthenticationExtensionsLargeBlobInputs; - minPinLength?: boolean; - prf?: AuthenticationExtensionsPRFInputs; -} - -interface AuthenticationExtensionsClientInputsJSON { - appid?: string; - credProps?: boolean; - largeBlob?: AuthenticationExtensionsLargeBlobInputsJSON; - prf?: AuthenticationExtensionsPRFInputsJSON; -} - -interface AuthenticationExtensionsClientOutputs { - appid?: boolean; - credProps?: CredentialPropertiesOutput; - hmacCreateSecret?: boolean; - largeBlob?: AuthenticationExtensionsLargeBlobOutputs; - prf?: AuthenticationExtensionsPRFOutputs; -} - -interface AuthenticationExtensionsClientOutputsJSON { - appid?: boolean; - credProps?: CredentialPropertiesOutput; - largeBlob?: AuthenticationExtensionsLargeBlobOutputsJSON; - prf?: AuthenticationExtensionsPRFOutputsJSON; -} - -interface AuthenticationExtensionsLargeBlobInputs { - read?: boolean; - support?: string; - write?: BufferSource; -} - -interface AuthenticationExtensionsLargeBlobInputsJSON { - read?: boolean; - support?: string; - write?: Base64URLString; -} - -interface AuthenticationExtensionsLargeBlobOutputs { - blob?: ArrayBuffer; - supported?: boolean; - written?: boolean; -} - -interface AuthenticationExtensionsLargeBlobOutputsJSON { - blob?: Base64URLString; - supported?: boolean; - written?: boolean; -} - -interface AuthenticationExtensionsPRFInputs { - eval?: AuthenticationExtensionsPRFValues; - evalByCredential?: Record; -} - -interface AuthenticationExtensionsPRFInputsJSON { - eval?: AuthenticationExtensionsPRFValuesJSON; - evalByCredential?: Record; -} - -interface AuthenticationExtensionsPRFOutputs { - enabled?: boolean; - results?: AuthenticationExtensionsPRFValues; -} - -interface AuthenticationExtensionsPRFOutputsJSON { - enabled?: boolean; - results?: AuthenticationExtensionsPRFValuesJSON; -} - -interface AuthenticationExtensionsPRFValues { - first: BufferSource; - second?: BufferSource; -} - -interface AuthenticationExtensionsPRFValuesJSON { - first: Base64URLString; - second?: Base64URLString; -} - -interface AuthenticationResponseJSON { - authenticatorAttachment?: string; - clientExtensionResults: AuthenticationExtensionsClientOutputsJSON; - id: string; - rawId: Base64URLString; - response: AuthenticatorAssertionResponseJSON; - type: string; -} - -interface AuthenticatorAssertionResponseJSON { - authenticatorData: Base64URLString; - clientDataJSON: Base64URLString; - signature: Base64URLString; - userHandle?: Base64URLString; -} - -interface AuthenticatorAttestationResponseJSON { - attestationObject: Base64URLString; - authenticatorData: Base64URLString; - clientDataJSON: Base64URLString; - publicKey?: Base64URLString; - publicKeyAlgorithm: COSEAlgorithmIdentifier; - transports: string[]; -} - -interface AuthenticatorSelectionCriteria { - authenticatorAttachment?: AuthenticatorAttachment; - requireResidentKey?: boolean; - residentKey?: ResidentKeyRequirement; - userVerification?: UserVerificationRequirement; -} - -interface AvcEncoderConfig { - format?: AvcBitstreamFormat; -} - -interface BiquadFilterOptions extends AudioNodeOptions { - Q?: number; - detune?: number; - frequency?: number; - gain?: number; - type?: BiquadFilterType; -} - -interface BlobEventInit extends EventInit { - data: Blob; - timecode?: DOMHighResTimeStamp; -} - -interface BlobPropertyBag { - endings?: EndingType; - type?: string; -} - -interface CSSMatrixComponentOptions { - is2D?: boolean; -} - -interface CSSNumericType { - angle?: number; - flex?: number; - frequency?: number; - length?: number; - percent?: number; - percentHint?: CSSNumericBaseType; - resolution?: number; - time?: number; -} - -interface CSSStyleSheetInit { - baseURL?: string; - disabled?: boolean; - media?: MediaList | string; -} - -interface CacheQueryOptions { - ignoreMethod?: boolean; - ignoreSearch?: boolean; - ignoreVary?: boolean; -} - -interface CanvasRenderingContext2DSettings { - alpha?: boolean; - colorSpace?: PredefinedColorSpace; - desynchronized?: boolean; - willReadFrequently?: boolean; -} - -interface CaretPositionFromPointOptions { - shadowRoots?: ShadowRoot[]; -} - -interface ChannelMergerOptions extends AudioNodeOptions { - numberOfInputs?: number; -} - -interface ChannelSplitterOptions extends AudioNodeOptions { - numberOfOutputs?: number; -} - -interface CheckVisibilityOptions { - checkOpacity?: boolean; - checkVisibilityCSS?: boolean; - contentVisibilityAuto?: boolean; - opacityProperty?: boolean; - visibilityProperty?: boolean; -} - -interface ClientQueryOptions { - includeUncontrolled?: boolean; - type?: ClientTypes; -} - -interface ClipboardEventInit extends EventInit { - clipboardData?: DataTransfer | null; -} - -interface ClipboardItemOptions { - presentationStyle?: PresentationStyle; -} - -interface CloseEventInit extends EventInit { - code?: number; - reason?: string; - wasClean?: boolean; -} - -interface CommandEventInit extends EventInit { - command?: string; - source?: Element | null; -} - -interface CompositionEventInit extends UIEventInit { - data?: string; -} - -interface ComputedEffectTiming extends EffectTiming { - activeDuration?: CSSNumberish; - currentIteration?: number | null; - endTime?: CSSNumberish; - localTime?: CSSNumberish | null; - progress?: number | null; - startTime?: CSSNumberish; -} - -interface ComputedKeyframe { - composite: CompositeOperationOrAuto; - computedOffset: number; - easing: string; - offset: number | null; - [property: string]: string | number | null | undefined; -} - -interface ConstantSourceOptions { - offset?: number; -} - -interface ConstrainBooleanOrDOMStringParameters { - exact?: boolean | string; - ideal?: boolean | string; -} - -interface ConstrainBooleanParameters { - exact?: boolean; - ideal?: boolean; -} - -interface ConstrainDOMStringParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface ConstrainDoubleRange extends DoubleRange { - exact?: number; - ideal?: number; -} - -interface ConstrainULongRange extends ULongRange { - exact?: number; - ideal?: number; -} - -interface ContentVisibilityAutoStateChangeEventInit extends EventInit { - skipped?: boolean; -} - -interface ConvolverOptions extends AudioNodeOptions { - buffer?: AudioBuffer | null; - disableNormalization?: boolean; -} - -interface CookieChangeEventInit extends EventInit { - changed?: CookieList; - deleted?: CookieList; -} - -interface CookieInit { - domain?: string | null; - expires?: DOMHighResTimeStamp | null; - name: string; - partitioned?: boolean; - path?: string; - sameSite?: CookieSameSite; - value: string; -} - -interface CookieListItem { - name?: string; - value?: string; -} - -interface CookieStoreDeleteOptions { - domain?: string | null; - name: string; - partitioned?: boolean; - path?: string; -} - -interface CookieStoreGetOptions { - name?: string; - url?: string; -} - -interface CredentialCreationOptions { - publicKey?: PublicKeyCredentialCreationOptions; - signal?: AbortSignal; -} - -interface CredentialPropertiesOutput { - rk?: boolean; -} - -interface CredentialRequestOptions { - mediation?: CredentialMediationRequirement; - publicKey?: PublicKeyCredentialRequestOptions; - signal?: AbortSignal; -} - -interface CryptoKeyPair { - privateKey: CryptoKey; - publicKey: CryptoKey; -} - -interface CurrentUserDetailsOptions { - displayName: string; - name: string; - rpId: string; - userId: Base64URLString; -} - -interface CustomEventInit extends EventInit { - detail?: T; -} - -interface DOMMatrix2DInit { - a?: number; - b?: number; - c?: number; - d?: number; - e?: number; - f?: number; - m11?: number; - m12?: number; - m21?: number; - m22?: number; - m41?: number; - m42?: number; -} - -interface DOMMatrixInit extends DOMMatrix2DInit { - is2D?: boolean; - m13?: number; - m14?: number; - m23?: number; - m24?: number; - m31?: number; - m32?: number; - m33?: number; - m34?: number; - m43?: number; - m44?: number; -} - -interface DOMPointInit { - w?: number; - x?: number; - y?: number; - z?: number; -} - -interface DOMQuadInit { - p1?: DOMPointInit; - p2?: DOMPointInit; - p3?: DOMPointInit; - p4?: DOMPointInit; -} - -interface DOMRectInit { - height?: number; - width?: number; - x?: number; - y?: number; -} - -interface DelayOptions extends AudioNodeOptions { - delayTime?: number; - maxDelayTime?: number; -} - -interface DeviceMotionEventAccelerationInit { - x?: number | null; - y?: number | null; - z?: number | null; -} - -interface DeviceMotionEventInit extends EventInit { - acceleration?: DeviceMotionEventAccelerationInit; - accelerationIncludingGravity?: DeviceMotionEventAccelerationInit; - interval?: number; - rotationRate?: DeviceMotionEventRotationRateInit; -} - -interface DeviceMotionEventRotationRateInit { - alpha?: number | null; - beta?: number | null; - gamma?: number | null; -} - -interface DeviceOrientationEventInit extends EventInit { - absolute?: boolean; - alpha?: number | null; - beta?: number | null; - gamma?: number | null; -} - -interface DisplayMediaStreamOptions { - audio?: boolean | MediaTrackConstraints; - video?: boolean | MediaTrackConstraints; -} - -interface DocumentTimelineOptions { - originTime?: DOMHighResTimeStamp; -} - -interface DoubleRange { - max?: number; - min?: number; -} - -interface DragEventInit extends MouseEventInit { - dataTransfer?: DataTransfer | null; -} - -interface DynamicsCompressorOptions extends AudioNodeOptions { - attack?: number; - knee?: number; - ratio?: number; - release?: number; - threshold?: number; -} - -interface EcKeyAlgorithm extends KeyAlgorithm { - namedCurve: NamedCurve; -} - -interface EcKeyGenParams extends Algorithm { - namedCurve: NamedCurve; -} - -interface EcKeyImportParams extends Algorithm { - namedCurve: NamedCurve; -} - -interface EcdhKeyDeriveParams extends Algorithm { - public: CryptoKey; -} - -interface EcdsaParams extends Algorithm { - hash: HashAlgorithmIdentifier; -} - -interface EffectTiming { - delay?: number; - direction?: PlaybackDirection; - duration?: number | CSSNumericValue | string; - easing?: string; - endDelay?: number; - fill?: FillMode; - iterationStart?: number; - iterations?: number; - playbackRate?: number; -} - -interface ElementCreationOptions { - customElementRegistry?: CustomElementRegistry | null; - is?: string; -} - -interface ElementDefinitionOptions { - extends?: string; -} - -interface EncodedAudioChunkInit { - data: AllowSharedBufferSource; - duration?: number; - timestamp: number; - transfer?: ArrayBuffer[]; - type: EncodedAudioChunkType; -} - -interface EncodedAudioChunkMetadata { - decoderConfig?: AudioDecoderConfig; -} - -interface EncodedVideoChunkInit { - data: AllowSharedBufferSource; - duration?: number; - timestamp: number; - type: EncodedVideoChunkType; -} - -interface EncodedVideoChunkMetadata { - decoderConfig?: VideoDecoderConfig; - svc?: SvcOutputMetadata; -} - -interface ErrorEventInit extends EventInit { - colno?: number; - error?: any; - filename?: string; - lineno?: number; - message?: string; -} - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} - -interface EventListenerOptions { - capture?: boolean; -} - -interface EventModifierInit extends UIEventInit { - altKey?: boolean; - ctrlKey?: boolean; - metaKey?: boolean; - modifierAltGraph?: boolean; - modifierCapsLock?: boolean; - modifierFn?: boolean; - modifierFnLock?: boolean; - modifierHyper?: boolean; - modifierNumLock?: boolean; - modifierScrollLock?: boolean; - modifierSuper?: boolean; - modifierSymbol?: boolean; - modifierSymbolLock?: boolean; - shiftKey?: boolean; -} - -interface EventSourceInit { - withCredentials?: boolean; -} - -interface FilePropertyBag extends BlobPropertyBag { - lastModified?: number; -} - -interface FileSystemCreateWritableOptions { - keepExistingData?: boolean; -} - -interface FileSystemFlags { - create?: boolean; - exclusive?: boolean; -} - -interface FileSystemGetDirectoryOptions { - create?: boolean; -} - -interface FileSystemGetFileOptions { - create?: boolean; -} - -interface FileSystemRemoveOptions { - recursive?: boolean; -} - -interface FocusEventInit extends UIEventInit { - relatedTarget?: EventTarget | null; -} - -interface FocusOptions { - focusVisible?: boolean; - preventScroll?: boolean; -} - -interface FontFaceDescriptors { - ascentOverride?: string; - descentOverride?: string; - display?: FontDisplay; - featureSettings?: string; - lineGapOverride?: string; - stretch?: string; - style?: string; - unicodeRange?: string; - variationSettings?: string; - weight?: string; -} - -interface FontFaceSetLoadEventInit extends EventInit { - fontfaces?: FontFace[]; -} - -interface FormDataEventInit extends EventInit { - formData: FormData; -} - -interface FullscreenOptions { - navigationUI?: FullscreenNavigationUI; -} - -interface GPUBindGroupDescriptor extends GPUObjectDescriptorBase { - entries: GPUBindGroupEntry[]; - layout: GPUBindGroupLayout; -} - -interface GPUBindGroupEntry { - binding: GPUIndex32; - resource: GPUBindingResource; -} - -interface GPUBindGroupLayoutDescriptor extends GPUObjectDescriptorBase { - entries: GPUBindGroupLayoutEntry[]; -} - -interface GPUBindGroupLayoutEntry { - binding: GPUIndex32; - buffer?: GPUBufferBindingLayout; - externalTexture?: GPUExternalTextureBindingLayout; - sampler?: GPUSamplerBindingLayout; - storageTexture?: GPUStorageTextureBindingLayout; - texture?: GPUTextureBindingLayout; - visibility: GPUShaderStageFlags; -} - -interface GPUBlendComponent { - dstFactor?: GPUBlendFactor; - operation?: GPUBlendOperation; - srcFactor?: GPUBlendFactor; -} - -interface GPUBlendState { - alpha: GPUBlendComponent; - color: GPUBlendComponent; -} - -interface GPUBufferBinding { - buffer: GPUBuffer; - offset?: GPUSize64; - size?: GPUSize64; -} - -interface GPUBufferBindingLayout { - hasDynamicOffset?: boolean; - minBindingSize?: GPUSize64; - type?: GPUBufferBindingType; -} - -interface GPUBufferDescriptor extends GPUObjectDescriptorBase { - mappedAtCreation?: boolean; - size: GPUSize64; - usage: GPUBufferUsageFlags; -} - -interface GPUCanvasConfiguration { - alphaMode?: GPUCanvasAlphaMode; - colorSpace?: PredefinedColorSpace; - device: GPUDevice; - format: GPUTextureFormat; - toneMapping?: GPUCanvasToneMapping; - usage?: GPUTextureUsageFlags; - viewFormats?: GPUTextureFormat[]; -} - -interface GPUCanvasToneMapping { - mode?: GPUCanvasToneMappingMode; -} - -interface GPUColorDict { - a: number; - b: number; - g: number; - r: number; -} - -interface GPUColorTargetState { - blend?: GPUBlendState; - format: GPUTextureFormat; - writeMask?: GPUColorWriteFlags; -} - -interface GPUCommandBufferDescriptor extends GPUObjectDescriptorBase { -} - -interface GPUCommandEncoderDescriptor extends GPUObjectDescriptorBase { -} - -interface GPUComputePassDescriptor extends GPUObjectDescriptorBase { - timestampWrites?: GPUComputePassTimestampWrites; -} - -interface GPUComputePassTimestampWrites { - beginningOfPassWriteIndex?: GPUSize32; - endOfPassWriteIndex?: GPUSize32; - querySet: GPUQuerySet; -} - -interface GPUComputePipelineDescriptor extends GPUPipelineDescriptorBase { - compute: GPUProgrammableStage; -} - -interface GPUCopyExternalImageDestInfo extends GPUTexelCopyTextureInfo { - colorSpace?: PredefinedColorSpace; - premultipliedAlpha?: boolean; -} - -interface GPUCopyExternalImageSourceInfo { - flipY?: boolean; - origin?: GPUOrigin2D; - source: GPUCopyExternalImageSource; -} - -interface GPUDepthStencilState { - depthBias?: GPUDepthBias; - depthBiasClamp?: number; - depthBiasSlopeScale?: number; - depthCompare?: GPUCompareFunction; - depthWriteEnabled?: boolean; - format: GPUTextureFormat; - stencilBack?: GPUStencilFaceState; - stencilFront?: GPUStencilFaceState; - stencilReadMask?: GPUStencilValue; - stencilWriteMask?: GPUStencilValue; -} - -interface GPUDeviceDescriptor extends GPUObjectDescriptorBase { - defaultQueue?: GPUQueueDescriptor; - requiredFeatures?: GPUFeatureName[]; - requiredLimits?: Record; -} - -interface GPUExtent3DDict { - depthOrArrayLayers?: GPUIntegerCoordinate; - height?: GPUIntegerCoordinate; - width: GPUIntegerCoordinate; -} - -interface GPUExternalTextureBindingLayout { -} - -interface GPUExternalTextureDescriptor extends GPUObjectDescriptorBase { - colorSpace?: PredefinedColorSpace; - source: HTMLVideoElement | VideoFrame; -} - -interface GPUFragmentState extends GPUProgrammableStage { - targets: (GPUColorTargetState | null)[]; -} - -interface GPUMultisampleState { - alphaToCoverageEnabled?: boolean; - count?: GPUSize32; - mask?: GPUSampleMask; -} - -interface GPUObjectDescriptorBase { - label?: string; -} - -interface GPUOrigin2DDict { - x?: GPUIntegerCoordinate; - y?: GPUIntegerCoordinate; -} - -interface GPUOrigin3DDict { - x?: GPUIntegerCoordinate; - y?: GPUIntegerCoordinate; - z?: GPUIntegerCoordinate; -} - -interface GPUPipelineDescriptorBase extends GPUObjectDescriptorBase { - layout: GPUPipelineLayout | GPUAutoLayoutMode; -} - -interface GPUPipelineErrorInit { - reason: GPUPipelineErrorReason; -} - -interface GPUPipelineLayoutDescriptor extends GPUObjectDescriptorBase { - bindGroupLayouts: (GPUBindGroupLayout | null)[]; -} - -interface GPUPrimitiveState { - cullMode?: GPUCullMode; - frontFace?: GPUFrontFace; - stripIndexFormat?: GPUIndexFormat; - topology?: GPUPrimitiveTopology; - unclippedDepth?: boolean; -} - -interface GPUProgrammableStage { - constants?: Record; - entryPoint?: string; - module: GPUShaderModule; -} - -interface GPUQuerySetDescriptor extends GPUObjectDescriptorBase { - count: GPUSize32; - type: GPUQueryType; -} - -interface GPUQueueDescriptor extends GPUObjectDescriptorBase { -} - -interface GPURenderBundleDescriptor extends GPUObjectDescriptorBase { -} - -interface GPURenderBundleEncoderDescriptor extends GPURenderPassLayout { - depthReadOnly?: boolean; - stencilReadOnly?: boolean; -} - -interface GPURenderPassColorAttachment { - clearValue?: GPUColor; - depthSlice?: GPUIntegerCoordinate; - loadOp: GPULoadOp; - resolveTarget?: GPUTexture | GPUTextureView; - storeOp: GPUStoreOp; - view: GPUTexture | GPUTextureView; -} - -interface GPURenderPassDepthStencilAttachment { - depthClearValue?: number; - depthLoadOp?: GPULoadOp; - depthReadOnly?: boolean; - depthStoreOp?: GPUStoreOp; - stencilClearValue?: GPUStencilValue; - stencilLoadOp?: GPULoadOp; - stencilReadOnly?: boolean; - stencilStoreOp?: GPUStoreOp; - view: GPUTexture | GPUTextureView; -} - -interface GPURenderPassDescriptor extends GPUObjectDescriptorBase { - colorAttachments: (GPURenderPassColorAttachment | null)[]; - depthStencilAttachment?: GPURenderPassDepthStencilAttachment; - maxDrawCount?: GPUSize64; - occlusionQuerySet?: GPUQuerySet; - timestampWrites?: GPURenderPassTimestampWrites; -} - -interface GPURenderPassLayout extends GPUObjectDescriptorBase { - colorFormats: (GPUTextureFormat | null)[]; - depthStencilFormat?: GPUTextureFormat; - sampleCount?: GPUSize32; -} - -interface GPURenderPassTimestampWrites { - beginningOfPassWriteIndex?: GPUSize32; - endOfPassWriteIndex?: GPUSize32; - querySet: GPUQuerySet; -} - -interface GPURenderPipelineDescriptor extends GPUPipelineDescriptorBase { - depthStencil?: GPUDepthStencilState; - fragment?: GPUFragmentState; - multisample?: GPUMultisampleState; - primitive?: GPUPrimitiveState; - vertex: GPUVertexState; -} - -interface GPURequestAdapterOptions { - forceFallbackAdapter?: boolean; - powerPreference?: GPUPowerPreference; -} - -interface GPUSamplerBindingLayout { - type?: GPUSamplerBindingType; -} - -interface GPUSamplerDescriptor extends GPUObjectDescriptorBase { - addressModeU?: GPUAddressMode; - addressModeV?: GPUAddressMode; - addressModeW?: GPUAddressMode; - compare?: GPUCompareFunction; - lodMaxClamp?: number; - lodMinClamp?: number; - magFilter?: GPUFilterMode; - maxAnisotropy?: number; - minFilter?: GPUFilterMode; - mipmapFilter?: GPUMipmapFilterMode; -} - -interface GPUShaderModuleDescriptor extends GPUObjectDescriptorBase { - code: string; -} - -interface GPUStencilFaceState { - compare?: GPUCompareFunction; - depthFailOp?: GPUStencilOperation; - failOp?: GPUStencilOperation; - passOp?: GPUStencilOperation; -} - -interface GPUStorageTextureBindingLayout { - access?: GPUStorageTextureAccess; - format: GPUTextureFormat; - viewDimension?: GPUTextureViewDimension; -} - -interface GPUTexelCopyBufferInfo extends GPUTexelCopyBufferLayout { - buffer: GPUBuffer; -} - -interface GPUTexelCopyBufferLayout { - bytesPerRow?: GPUSize32; - offset?: GPUSize64; - rowsPerImage?: GPUSize32; -} - -interface GPUTexelCopyTextureInfo { - aspect?: GPUTextureAspect; - mipLevel?: GPUIntegerCoordinate; - origin?: GPUOrigin3D; - texture: GPUTexture; -} - -interface GPUTextureBindingLayout { - multisampled?: boolean; - sampleType?: GPUTextureSampleType; - viewDimension?: GPUTextureViewDimension; -} - -interface GPUTextureDescriptor extends GPUObjectDescriptorBase { - dimension?: GPUTextureDimension; - format: GPUTextureFormat; - mipLevelCount?: GPUIntegerCoordinate; - sampleCount?: GPUSize32; - size: GPUExtent3D; - usage: GPUTextureUsageFlags; - viewFormats?: GPUTextureFormat[]; -} - -interface GPUTextureViewDescriptor extends GPUObjectDescriptorBase { - arrayLayerCount?: GPUIntegerCoordinate; - aspect?: GPUTextureAspect; - baseArrayLayer?: GPUIntegerCoordinate; - baseMipLevel?: GPUIntegerCoordinate; - dimension?: GPUTextureViewDimension; - format?: GPUTextureFormat; - mipLevelCount?: GPUIntegerCoordinate; - usage?: GPUTextureUsageFlags; -} - -interface GPUUncapturedErrorEventInit extends EventInit { - error: GPUError; -} - -interface GPUVertexAttribute { - format: GPUVertexFormat; - offset: GPUSize64; - shaderLocation: GPUIndex32; -} - -interface GPUVertexBufferLayout { - arrayStride: GPUSize64; - attributes: GPUVertexAttribute[]; - stepMode?: GPUVertexStepMode; -} - -interface GPUVertexState extends GPUProgrammableStage { - buffers?: (GPUVertexBufferLayout | null)[]; -} - -interface GainOptions extends AudioNodeOptions { - gain?: number; -} - -interface GamepadEffectParameters { - duration?: number; - leftTrigger?: number; - rightTrigger?: number; - startDelay?: number; - strongMagnitude?: number; - weakMagnitude?: number; -} - -interface GamepadEventInit extends EventInit { - gamepad?: Gamepad | null; -} - -interface GetAnimationsOptions { - subtree?: boolean; -} - -interface GetComposedRangesOptions { - shadowRoots?: ShadowRoot[]; -} - -interface GetHTMLOptions { - serializableShadowRoots?: boolean; - shadowRoots?: ShadowRoot[]; -} - -interface GetNotificationOptions { - tag?: string; -} - -interface GetRootNodeOptions { - composed?: boolean; -} - -interface HashChangeEventInit extends EventInit { - newURL?: string; - oldURL?: string; -} - -interface HkdfParams extends Algorithm { - hash: HashAlgorithmIdentifier; - info: BufferSource; - salt: BufferSource; -} - -interface HmacImportParams extends Algorithm { - hash: HashAlgorithmIdentifier; - length?: number; -} - -interface HmacKeyAlgorithm extends KeyAlgorithm { - hash: KeyAlgorithm; - length: number; -} - -interface HmacKeyGenParams extends Algorithm { - hash: HashAlgorithmIdentifier; - length?: number; -} - -interface IDBDatabaseInfo { - name?: string; - version?: number; -} - -interface IDBIndexParameters { - multiEntry?: boolean; - unique?: boolean; -} - -interface IDBObjectStoreParameters { - autoIncrement?: boolean; - keyPath?: string | string[] | null; -} - -interface IDBTransactionOptions { - durability?: IDBTransactionDurability; -} - -interface IDBVersionChangeEventInit extends EventInit { - newVersion?: number | null; - oldVersion?: number; -} - -interface IIRFilterOptions extends AudioNodeOptions { - feedback: number[]; - feedforward: number[]; -} - -interface IdleRequestOptions { - timeout?: number; -} - -interface ImageBitmapOptions { - colorSpaceConversion?: ColorSpaceConversion; - imageOrientation?: ImageOrientation; - premultiplyAlpha?: PremultiplyAlpha; - resizeHeight?: number; - resizeQuality?: ResizeQuality; - resizeWidth?: number; -} - -interface ImageBitmapRenderingContextSettings { - alpha?: boolean; -} - -interface ImageDataSettings { - colorSpace?: PredefinedColorSpace; - pixelFormat?: ImageDataPixelFormat; -} - -interface ImageDecodeOptions { - completeFramesOnly?: boolean; - frameIndex?: number; -} - -interface ImageDecodeResult { - complete: boolean; - image: VideoFrame; -} - -interface ImageDecoderInit { - colorSpaceConversion?: ColorSpaceConversion; - data: ImageBufferSource; - desiredHeight?: number; - desiredWidth?: number; - preferAnimation?: boolean; - transfer?: ArrayBuffer[]; - type: string; -} - -interface ImageEncodeOptions { - quality?: number; - type?: string; -} - -interface ImportNodeOptions { - customElementRegistry?: CustomElementRegistry; - selfOnly?: boolean; -} - -interface InputEventInit extends UIEventInit { - data?: string | null; - dataTransfer?: DataTransfer | null; - inputType?: string; - isComposing?: boolean; - targetRanges?: StaticRange[]; -} - -interface IntersectionObserverInit { - root?: Element | Document | null; - rootMargin?: string; - scrollMargin?: string; - threshold?: number | number[]; -} - -interface JsonWebKey { - alg?: string; - crv?: string; - d?: string; - dp?: string; - dq?: string; - e?: string; - ext?: boolean; - k?: string; - key_ops?: string[]; - kty?: string; - n?: string; - oth?: RsaOtherPrimesInfo[]; - p?: string; - q?: string; - qi?: string; - use?: string; - x?: string; - y?: string; -} - -interface KeyAlgorithm { - name: string; -} - -interface KeySystemTrackConfiguration { - robustness?: string; -} - -interface KeyboardEventInit extends EventModifierInit { - /** @deprecated `charCode` is inconsistent across environments, consider using `key` instead. */ - charCode?: number; - code?: string; - isComposing?: boolean; - key?: string; - /** @deprecated `keyCode` is inconsistent across environments, consider using `key` instead. */ - keyCode?: number; - location?: number; - repeat?: boolean; -} - -interface Keyframe { - composite?: CompositeOperationOrAuto; - easing?: string; - offset?: number | null; - [property: string]: string | number | null | undefined; -} - -interface KeyframeAnimationOptions extends KeyframeEffectOptions { - id?: string; - rangeEnd?: TimelineRangeOffset | CSSNumericValue | CSSKeywordValue | string; - rangeStart?: TimelineRangeOffset | CSSNumericValue | CSSKeywordValue | string; - timeline?: AnimationTimeline | null; -} - -interface KeyframeEffectOptions extends EffectTiming { - composite?: CompositeOperation; - iterationComposite?: IterationCompositeOperation; - pseudoElement?: string | null; -} - -interface LockInfo { - clientId?: string; - mode?: LockMode; - name?: string; -} - -interface LockManagerSnapshot { - held?: LockInfo[]; - pending?: LockInfo[]; -} - -interface LockOptions { - ifAvailable?: boolean; - mode?: LockMode; - signal?: AbortSignal; - steal?: boolean; -} - -interface MIDIConnectionEventInit extends EventInit { - port?: MIDIPort; -} - -interface MIDIMessageEventInit extends EventInit { - data?: Uint8Array; -} - -interface MIDIOptions { - software?: boolean; - sysex?: boolean; -} - -interface MediaCapabilitiesDecodingInfo extends MediaCapabilitiesInfo { - keySystemAccess: MediaKeySystemAccess | null; -} - -interface MediaCapabilitiesEncodingInfo extends MediaCapabilitiesInfo { -} - -interface MediaCapabilitiesInfo { - powerEfficient: boolean; - smooth: boolean; - supported: boolean; -} - -interface MediaCapabilitiesKeySystemConfiguration { - audio?: KeySystemTrackConfiguration; - distinctiveIdentifier?: MediaKeysRequirement; - initDataType?: string; - keySystem: string; - persistentState?: MediaKeysRequirement; - sessionTypes?: string[]; - video?: KeySystemTrackConfiguration; -} - -interface MediaConfiguration { - audio?: AudioConfiguration; - video?: VideoConfiguration; -} - -interface MediaDecodingConfiguration extends MediaConfiguration { - keySystemConfiguration?: MediaCapabilitiesKeySystemConfiguration; - type: MediaDecodingType; -} - -interface MediaElementAudioSourceOptions { - mediaElement: HTMLMediaElement; -} - -interface MediaEncodingConfiguration extends MediaConfiguration { - type: MediaEncodingType; -} - -interface MediaEncryptedEventInit extends EventInit { - initData?: ArrayBuffer | null; - initDataType?: string; -} - -interface MediaImage { - sizes?: string; - src: string; - type?: string; -} - -interface MediaKeyMessageEventInit extends EventInit { - message: ArrayBuffer; - messageType: MediaKeyMessageType; -} - -interface MediaKeySystemConfiguration { - audioCapabilities?: MediaKeySystemMediaCapability[]; - distinctiveIdentifier?: MediaKeysRequirement; - initDataTypes?: string[]; - label?: string; - persistentState?: MediaKeysRequirement; - sessionTypes?: string[]; - videoCapabilities?: MediaKeySystemMediaCapability[]; -} - -interface MediaKeySystemMediaCapability { - contentType?: string; - encryptionScheme?: string | null; - robustness?: string; -} - -interface MediaKeysPolicy { - minHdcpVersion?: string; -} - -interface MediaMetadataInit { - album?: string; - artist?: string; - artwork?: MediaImage[]; - title?: string; -} - -interface MediaPositionState { - duration?: number; - playbackRate?: number; - position?: number; -} - -interface MediaQueryListEventInit extends EventInit { - matches?: boolean; - media?: string; -} - -interface MediaRecorderOptions { - audioBitsPerSecond?: number; - bitsPerSecond?: number; - mimeType?: string; - videoBitsPerSecond?: number; -} - -interface MediaSessionActionDetails { - action: MediaSessionAction; - fastSeek?: boolean; - seekOffset?: number; - seekTime?: number; -} - -interface MediaSettingsRange { - max?: number; - min?: number; - step?: number; -} - -interface MediaStreamAudioSourceOptions { - mediaStream: MediaStream; -} - -interface MediaStreamConstraints { - audio?: boolean | MediaTrackConstraints; - peerIdentity?: string; - preferCurrentTab?: boolean; - video?: boolean | MediaTrackConstraints; -} - -interface MediaStreamTrackEventInit extends EventInit { - track: MediaStreamTrack; -} - -interface MediaTrackCapabilities { - aspectRatio?: DoubleRange; - autoGainControl?: boolean[]; - backgroundBlur?: boolean[]; - channelCount?: ULongRange; - deviceId?: string; - displaySurface?: string; - echoCancellation?: (boolean | string)[]; - facingMode?: string[]; - frameRate?: DoubleRange; - groupId?: string; - height?: ULongRange; - noiseSuppression?: boolean[]; - sampleRate?: ULongRange; - sampleSize?: ULongRange; - width?: ULongRange; -} - -interface MediaTrackConstraintSet { - aspectRatio?: ConstrainDouble; - autoGainControl?: ConstrainBoolean; - backgroundBlur?: ConstrainBoolean; - channelCount?: ConstrainULong; - deviceId?: ConstrainDOMString; - displaySurface?: ConstrainDOMString; - echoCancellation?: ConstrainBooleanOrDOMString; - facingMode?: ConstrainDOMString; - frameRate?: ConstrainDouble; - groupId?: ConstrainDOMString; - height?: ConstrainULong; - noiseSuppression?: ConstrainBoolean; - sampleRate?: ConstrainULong; - sampleSize?: ConstrainULong; - width?: ConstrainULong; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackSettings { - aspectRatio?: number; - autoGainControl?: boolean; - backgroundBlur?: boolean; - channelCount?: number; - deviceId?: string; - displaySurface?: string; - echoCancellation?: boolean | string; - facingMode?: string; - frameRate?: number; - groupId?: string; - height?: number; - noiseSuppression?: boolean; - sampleRate?: number; - sampleSize?: number; - torch?: boolean; - whiteBalanceMode?: string; - width?: number; - zoom?: number; -} - -interface MediaTrackSupportedConstraints { - aspectRatio?: boolean; - autoGainControl?: boolean; - backgroundBlur?: boolean; - channelCount?: boolean; - deviceId?: boolean; - displaySurface?: boolean; - echoCancellation?: boolean; - facingMode?: boolean; - frameRate?: boolean; - groupId?: boolean; - height?: boolean; - noiseSuppression?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - width?: boolean; -} - -interface MessageEventInit extends EventInit { - data?: T; - lastEventId?: string; - origin?: string; - ports?: MessagePort[]; - source?: MessageEventSource | null; -} - -interface MouseEventInit extends EventModifierInit { - button?: number; - buttons?: number; - clientX?: number; - clientY?: number; - movementX?: number; - movementY?: number; - relatedTarget?: EventTarget | null; - screenX?: number; - screenY?: number; -} - -interface MultiCacheQueryOptions extends CacheQueryOptions { - cacheName?: string; -} - -interface MutationObserverInit { - /** Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed and attributes is true or omitted. */ - attributeFilter?: string[]; - /** Set to true if attributes is true or omitted and target's attribute value before the mutation needs to be recorded. */ - attributeOldValue?: boolean; - /** Set to true if mutations to target's attributes are to be observed. Can be omitted if attributeOldValue or attributeFilter is specified. */ - attributes?: boolean; - /** Set to true if mutations to target's data are to be observed. Can be omitted if characterDataOldValue is specified. */ - characterData?: boolean; - /** Set to true if characterData is set to true or omitted and target's data before the mutation needs to be recorded. */ - characterDataOldValue?: boolean; - /** Set to true if mutations to target's children are to be observed. */ - childList?: boolean; - /** Set to true if mutations to not just target, but also target's descendants are to be observed. */ - subtree?: boolean; -} - -interface NavigateEventInit extends EventInit { - canIntercept?: boolean; - destination: NavigationDestination; - downloadRequest?: string | null; - formData?: FormData | null; - hasUAVisualTransition?: boolean; - hashChange?: boolean; - info?: any; - navigationType?: NavigationType; - signal: AbortSignal; - sourceElement?: Element | null; - userInitiated?: boolean; -} - -interface NavigationCurrentEntryChangeEventInit extends EventInit { - from: NavigationHistoryEntry; - navigationType?: NavigationType | null; -} - -interface NavigationInterceptOptions { - focusReset?: NavigationFocusReset; - handler?: NavigationInterceptHandler; - precommitHandler?: NavigationPrecommitHandler; - scroll?: NavigationScrollBehavior; -} - -interface NavigationNavigateOptions extends NavigationOptions { - history?: NavigationHistoryBehavior; - state?: any; -} - -interface NavigationOptions { - info?: any; -} - -interface NavigationPreloadState { - enabled?: boolean; - headerValue?: string; -} - -interface NavigationReloadOptions extends NavigationOptions { - state?: any; -} - -interface NavigationResult { - committed?: Promise; - finished?: Promise; -} - -interface NavigationUpdateCurrentEntryOptions { - state: any; -} - -interface NotificationOptions { - badge?: string; - body?: string; - data?: any; - dir?: NotificationDirection; - icon?: string; - lang?: string; - requireInteraction?: boolean; - silent?: boolean | null; - tag?: string; -} - -interface OfflineAudioCompletionEventInit extends EventInit { - renderedBuffer: AudioBuffer; -} - -interface OfflineAudioContextOptions { - length: number; - numberOfChannels?: number; - sampleRate: number; -} - -interface OptionalEffectTiming { - delay?: number; - direction?: PlaybackDirection; - duration?: number | string; - easing?: string; - endDelay?: number; - fill?: FillMode; - iterationStart?: number; - iterations?: number; - playbackRate?: number; -} - -interface OpusEncoderConfig { - complexity?: number; - format?: OpusBitstreamFormat; - frameDuration?: number; - packetlossperc?: number; - usedtx?: boolean; - useinbandfec?: boolean; -} - -interface OscillatorOptions extends AudioNodeOptions { - detune?: number; - frequency?: number; - periodicWave?: PeriodicWave; - type?: OscillatorType; -} - -interface PageRevealEventInit extends EventInit { - viewTransition?: ViewTransition | null; -} - -interface PageSwapEventInit extends EventInit { - activation?: NavigationActivation | null; - viewTransition?: ViewTransition | null; -} - -interface PageTransitionEventInit extends EventInit { - persisted?: boolean; -} - -interface PannerOptions extends AudioNodeOptions { - coneInnerAngle?: number; - coneOuterAngle?: number; - coneOuterGain?: number; - distanceModel?: DistanceModelType; - maxDistance?: number; - orientationX?: number; - orientationY?: number; - orientationZ?: number; - panningModel?: PanningModelType; - positionX?: number; - positionY?: number; - positionZ?: number; - refDistance?: number; - rolloffFactor?: number; -} - -interface PayerErrors { - email?: string; - name?: string; - phone?: string; -} - -interface PaymentCurrencyAmount { - currency: string; - value: string; -} - -interface PaymentDetailsBase { - displayItems?: PaymentItem[]; - modifiers?: PaymentDetailsModifier[]; - shippingOptions?: PaymentShippingOption[]; -} - -interface PaymentDetailsInit extends PaymentDetailsBase { - id?: string; - total: PaymentItem; -} - -interface PaymentDetailsModifier { - additionalDisplayItems?: PaymentItem[]; - data?: any; - supportedMethods: string; - total?: PaymentItem; -} - -interface PaymentDetailsUpdate extends PaymentDetailsBase { - error?: string; - paymentMethodErrors?: any; - shippingAddressErrors?: AddressErrors; - total?: PaymentItem; -} - -interface PaymentItem { - amount: PaymentCurrencyAmount; - label: string; - pending?: boolean; -} - -interface PaymentMethodChangeEventInit extends PaymentRequestUpdateEventInit { - methodDetails?: any; - methodName?: string; -} - -interface PaymentMethodData { - data?: any; - supportedMethods: string; -} - -interface PaymentOptions { - requestPayerEmail?: boolean; - requestPayerName?: boolean; - requestPayerPhone?: boolean; - requestShipping?: boolean; - shippingType?: PaymentShippingType; -} - -interface PaymentRequestUpdateEventInit extends EventInit { -} - -interface PaymentShippingOption { - amount: PaymentCurrencyAmount; - id: string; - label: string; - selected?: boolean; -} - -interface PaymentValidationErrors { - error?: string; - payer?: PayerErrors; - shippingAddress?: AddressErrors; -} - -interface Pbkdf2Params extends Algorithm { - hash: HashAlgorithmIdentifier; - iterations: number; - salt: BufferSource; -} - -interface PerformanceMarkOptions { - detail?: any; - startTime?: DOMHighResTimeStamp; -} - -interface PerformanceMeasureOptions { - detail?: any; - duration?: DOMHighResTimeStamp; - end?: string | DOMHighResTimeStamp; - start?: string | DOMHighResTimeStamp; -} - -interface PerformanceObserverInit { - buffered?: boolean; - entryTypes?: string[]; - type?: string; -} - -interface PeriodicWaveConstraints { - disableNormalization?: boolean; -} - -interface PeriodicWaveOptions extends PeriodicWaveConstraints { - imag?: number[] | Float32Array; - real?: number[] | Float32Array; -} - -interface PermissionDescriptor { - name: PermissionName; -} - -interface PhotoCapabilities { - fillLightMode?: FillLightMode[]; - imageHeight?: MediaSettingsRange; - imageWidth?: MediaSettingsRange; - redEyeReduction?: RedEyeReduction; -} - -interface PhotoSettings { - fillLightMode?: FillLightMode; - imageHeight?: number; - imageWidth?: number; - redEyeReduction?: boolean; -} - -interface PictureInPictureEventInit extends EventInit { - pictureInPictureWindow: PictureInPictureWindow; -} - -interface PlaneLayout { - offset: number; - stride: number; -} - -interface PointerEventInit extends MouseEventInit { - altitudeAngle?: number; - azimuthAngle?: number; - coalescedEvents?: PointerEvent[]; - height?: number; - isPrimary?: boolean; - pointerId?: number; - pointerType?: string; - predictedEvents?: PointerEvent[]; - pressure?: number; - tangentialPressure?: number; - tiltX?: number; - tiltY?: number; - twist?: number; - width?: number; -} - -interface PointerLockOptions { - unadjustedMovement?: boolean; -} - -interface PopStateEventInit extends EventInit { - hasUAVisualTransition?: boolean; - state?: any; -} - -interface PositionOptions { - enableHighAccuracy?: boolean; - maximumAge?: number; - timeout?: number; -} - -interface ProgressEventInit extends EventInit { - lengthComputable?: boolean; - loaded?: number; - total?: number; -} - -interface PromiseRejectionEventInit extends EventInit { - promise: Promise; - reason?: any; -} - -interface PropertyDefinition { - inherits: boolean; - initialValue?: string; - name: string; - syntax?: string; -} - -interface PropertyIndexedKeyframes { - composite?: CompositeOperationOrAuto | CompositeOperationOrAuto[]; - easing?: string | string[]; - offset?: number | (number | null)[]; - [property: string]: string | string[] | number | null | (number | null)[] | undefined; -} - -interface PublicKeyCredentialCreationOptions { - attestation?: AttestationConveyancePreference; - authenticatorSelection?: AuthenticatorSelectionCriteria; - challenge: BufferSource; - excludeCredentials?: PublicKeyCredentialDescriptor[]; - extensions?: AuthenticationExtensionsClientInputs; - pubKeyCredParams: PublicKeyCredentialParameters[]; - rp: PublicKeyCredentialRpEntity; - timeout?: number; - user: PublicKeyCredentialUserEntity; -} - -interface PublicKeyCredentialCreationOptionsJSON { - attestation?: string; - authenticatorSelection?: AuthenticatorSelectionCriteria; - challenge: Base64URLString; - excludeCredentials?: PublicKeyCredentialDescriptorJSON[]; - extensions?: AuthenticationExtensionsClientInputsJSON; - hints?: string[]; - pubKeyCredParams: PublicKeyCredentialParameters[]; - rp: PublicKeyCredentialRpEntity; - timeout?: number; - user: PublicKeyCredentialUserEntityJSON; -} - -interface PublicKeyCredentialDescriptor { - id: BufferSource; - transports?: AuthenticatorTransport[]; - type: PublicKeyCredentialType; -} - -interface PublicKeyCredentialDescriptorJSON { - id: Base64URLString; - transports?: string[]; - type: string; -} - -interface PublicKeyCredentialEntity { - name: string; -} - -interface PublicKeyCredentialParameters { - alg: COSEAlgorithmIdentifier; - type: PublicKeyCredentialType; -} - -interface PublicKeyCredentialRequestOptions { - allowCredentials?: PublicKeyCredentialDescriptor[]; - challenge: BufferSource; - extensions?: AuthenticationExtensionsClientInputs; - rpId?: string; - timeout?: number; - userVerification?: UserVerificationRequirement; -} - -interface PublicKeyCredentialRequestOptionsJSON { - allowCredentials?: PublicKeyCredentialDescriptorJSON[]; - challenge: Base64URLString; - extensions?: AuthenticationExtensionsClientInputsJSON; - hints?: string[]; - rpId?: string; - timeout?: number; - userVerification?: string; -} - -interface PublicKeyCredentialRpEntity extends PublicKeyCredentialEntity { - id?: string; -} - -interface PublicKeyCredentialUserEntity extends PublicKeyCredentialEntity { - displayName: string; - id: BufferSource; -} - -interface PublicKeyCredentialUserEntityJSON { - displayName: string; - id: Base64URLString; - name: string; -} - -interface PushSubscriptionJSON { - endpoint?: string; - expirationTime?: EpochTimeStamp | null; - keys?: Record; -} - -interface PushSubscriptionOptionsInit { - applicationServerKey?: BufferSource | string | null; - userVisibleOnly?: boolean; -} - -interface QueuingStrategy { - highWaterMark?: number; - size?: QueuingStrategySize; -} - -interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; -} - -interface RTCAnswerOptions extends RTCOfferAnswerOptions { -} - -interface RTCCertificateExpiration { - expires?: number; -} - -interface RTCConfiguration { - bundlePolicy?: RTCBundlePolicy; - certificates?: RTCCertificate[]; - iceCandidatePoolSize?: number; - iceServers?: RTCIceServer[]; - iceTransportPolicy?: RTCIceTransportPolicy; - rtcpMuxPolicy?: RTCRtcpMuxPolicy; -} - -interface RTCDTMFToneChangeEventInit extends EventInit { - tone?: string; -} - -interface RTCDataChannelEventInit extends EventInit { - channel: RTCDataChannel; -} - -interface RTCDataChannelInit { - id?: number; - maxPacketLifeTime?: number; - maxRetransmits?: number; - negotiated?: boolean; - ordered?: boolean; - protocol?: string; -} - -interface RTCDtlsFingerprint { - algorithm?: string; - value?: string; -} - -interface RTCEncodedAudioFrameMetadata extends RTCEncodedFrameMetadata { - sequenceNumber?: number; -} - -interface RTCEncodedFrameMetadata { - contributingSources?: number[]; - mimeType?: string; - payloadType?: number; - rtpTimestamp?: number; - synchronizationSource?: number; -} - -interface RTCEncodedVideoFrameMetadata extends RTCEncodedFrameMetadata { - dependencies?: number[]; - frameId?: number; - height?: number; - spatialIndex?: number; - temporalIndex?: number; - timestamp?: number; - width?: number; -} - -interface RTCErrorEventInit extends EventInit { - error: RTCError; -} - -interface RTCErrorInit { - errorDetail: RTCErrorDetailType; - httpRequestStatusCode?: number; - receivedAlert?: number; - sctpCauseCode?: number; - sdpLineNumber?: number; - sentAlert?: number; -} - -interface RTCIceCandidateInit { - candidate?: string; - sdpMLineIndex?: number | null; - sdpMid?: string | null; - usernameFragment?: string | null; -} - -interface RTCIceCandidatePairStats extends RTCStats { - availableIncomingBitrate?: number; - availableOutgoingBitrate?: number; - bytesDiscardedOnSend?: number; - bytesReceived?: number; - bytesSent?: number; - consentRequestsSent?: number; - currentRoundTripTime?: number; - lastPacketReceivedTimestamp?: DOMHighResTimeStamp; - lastPacketSentTimestamp?: DOMHighResTimeStamp; - localCandidateId: string; - nominated?: boolean; - packetsDiscardedOnSend?: number; - packetsReceived?: number; - packetsSent?: number; - remoteCandidateId: string; - requestsReceived?: number; - requestsSent?: number; - responsesReceived?: number; - responsesSent?: number; - state: RTCStatsIceCandidatePairState; - totalRoundTripTime?: number; - transportId: string; -} - -interface RTCIceServer { - credential?: string; - urls: string | string[]; - username?: string; -} - -interface RTCInboundRtpStreamStats extends RTCReceivedRtpStreamStats { - audioLevel?: number; - bytesReceived?: number; - concealedSamples?: number; - concealmentEvents?: number; - decoderImplementation?: string; - estimatedPlayoutTimestamp?: DOMHighResTimeStamp; - fecBytesReceived?: number; - fecPacketsDiscarded?: number; - fecPacketsReceived?: number; - fecSsrc?: number; - firCount?: number; - frameHeight?: number; - frameWidth?: number; - framesAssembledFromMultiplePackets?: number; - framesDecoded?: number; - framesDropped?: number; - framesPerSecond?: number; - framesReceived?: number; - framesRendered?: number; - freezeCount?: number; - headerBytesReceived?: number; - insertedSamplesForDeceleration?: number; - jitterBufferDelay?: number; - jitterBufferEmittedCount?: number; - jitterBufferMinimumDelay?: number; - jitterBufferTargetDelay?: number; - keyFramesDecoded?: number; - lastPacketReceivedTimestamp?: DOMHighResTimeStamp; - mid?: string; - nackCount?: number; - packetsDiscarded?: number; - pauseCount?: number; - playoutId?: string; - pliCount?: number; - qpSum?: number; - remoteId?: string; - removedSamplesForAcceleration?: number; - retransmittedBytesReceived?: number; - retransmittedPacketsReceived?: number; - rtxSsrc?: number; - silentConcealedSamples?: number; - totalAssemblyTime?: number; - totalAudioEnergy?: number; - totalDecodeTime?: number; - totalFreezesDuration?: number; - totalInterFrameDelay?: number; - totalPausesDuration?: number; - totalProcessingDelay?: number; - totalSamplesDuration?: number; - totalSamplesReceived?: number; - totalSquaredInterFrameDelay?: number; - trackIdentifier: string; -} - -interface RTCLocalIceCandidateInit extends RTCIceCandidateInit { -} - -interface RTCLocalSessionDescriptionInit { - sdp?: string; - type?: RTCSdpType; -} - -interface RTCOfferAnswerOptions { -} - -interface RTCOfferOptions extends RTCOfferAnswerOptions { - iceRestart?: boolean; - offerToReceiveAudio?: boolean; - offerToReceiveVideo?: boolean; -} - -interface RTCOutboundRtpStreamStats extends RTCSentRtpStreamStats { - active?: boolean; - firCount?: number; - frameHeight?: number; - frameWidth?: number; - framesEncoded?: number; - framesPerSecond?: number; - framesSent?: number; - headerBytesSent?: number; - hugeFramesSent?: number; - keyFramesEncoded?: number; - mediaSourceId?: string; - mid?: string; - nackCount?: number; - pliCount?: number; - qpSum?: number; - qualityLimitationDurations?: Record; - qualityLimitationReason?: RTCQualityLimitationReason; - qualityLimitationResolutionChanges?: number; - remoteId?: string; - retransmittedBytesSent?: number; - retransmittedPacketsSent?: number; - rid?: string; - rtxSsrc?: number; - scalabilityMode?: string; - targetBitrate?: number; - totalEncodeTime?: number; - totalEncodedBytesTarget?: number; - totalPacketSendDelay?: number; -} - -interface RTCPeerConnectionIceErrorEventInit extends EventInit { - address?: string | null; - errorCode: number; - errorText?: string; - port?: number | null; - url?: string; -} - -interface RTCPeerConnectionIceEventInit extends EventInit { - candidate?: RTCIceCandidate | null; -} - -interface RTCReceivedRtpStreamStats extends RTCRtpStreamStats { - jitter?: number; - packetsLost?: number; - packetsReceived?: number; -} - -interface RTCRtcpParameters { - cname?: string; - reducedSize?: boolean; -} - -interface RTCRtpCapabilities { - codecs: RTCRtpCodec[]; - headerExtensions: RTCRtpHeaderExtensionCapability[]; -} - -interface RTCRtpCodec { - channels?: number; - clockRate: number; - mimeType: string; - sdpFmtpLine?: string; -} - -interface RTCRtpCodecParameters extends RTCRtpCodec { - payloadType: number; -} - -interface RTCRtpCodingParameters { - rid?: string; -} - -interface RTCRtpContributingSource { - audioLevel?: number; - rtpTimestamp: number; - source: number; - timestamp: DOMHighResTimeStamp; -} - -interface RTCRtpEncodingParameters extends RTCRtpCodingParameters { - active?: boolean; - maxBitrate?: number; - maxFramerate?: number; - networkPriority?: RTCPriorityType; - priority?: RTCPriorityType; - scaleResolutionDownBy?: number; -} - -interface RTCRtpHeaderExtensionCapability { - uri: string; -} - -interface RTCRtpHeaderExtensionParameters { - encrypted?: boolean; - id: number; - uri: string; -} - -interface RTCRtpParameters { - codecs: RTCRtpCodecParameters[]; - headerExtensions: RTCRtpHeaderExtensionParameters[]; - rtcp: RTCRtcpParameters; -} - -interface RTCRtpReceiveParameters extends RTCRtpParameters { -} - -interface RTCRtpSendParameters extends RTCRtpParameters { - degradationPreference?: RTCDegradationPreference; - encodings: RTCRtpEncodingParameters[]; - transactionId: string; -} - -interface RTCRtpStreamStats extends RTCStats { - codecId?: string; - kind: string; - ssrc: number; - transportId?: string; -} - -interface RTCRtpSynchronizationSource extends RTCRtpContributingSource { -} - -interface RTCRtpTransceiverInit { - direction?: RTCRtpTransceiverDirection; - sendEncodings?: RTCRtpEncodingParameters[]; - streams?: MediaStream[]; -} - -interface RTCSentRtpStreamStats extends RTCRtpStreamStats { - bytesSent?: number; - packetsSent?: number; -} - -interface RTCSessionDescriptionInit { - sdp?: string; - type: RTCSdpType; -} - -interface RTCSetParameterOptions { -} - -interface RTCStats { - id: string; - timestamp: DOMHighResTimeStamp; - type: RTCStatsType; -} - -interface RTCTrackEventInit extends EventInit { - receiver: RTCRtpReceiver; - streams?: MediaStream[]; - track: MediaStreamTrack; - transceiver: RTCRtpTransceiver; -} - -interface RTCTransportStats extends RTCStats { - bytesReceived?: number; - bytesSent?: number; - dtlsCipher?: string; - dtlsRole?: RTCDtlsRole; - dtlsState: RTCDtlsTransportState; - iceLocalUsernameFragment?: string; - iceRole?: RTCIceRole; - iceState?: RTCIceTransportState; - localCertificateId?: string; - packetsReceived?: number; - packetsSent?: number; - remoteCertificateId?: string; - selectedCandidatePairChanges?: number; - selectedCandidatePairId?: string; - srtpCipher?: string; - tlsVersion?: string; -} - -interface ReadableStreamBYOBReaderReadOptions { - min?: number; -} - -interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode?: ReadableStreamReaderMode; -} - -interface ReadableStreamIteratorOptions { - /** - * Asynchronously iterates over the chunks in the stream's internal queue. - * - * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. The lock will be released if the async iterator's return() method is called, e.g. by breaking out of the loop. - * - * By default, calling the async iterator's return() method will also cancel the stream. To prevent this, use the stream's values() method, passing true for the preventCancel option. - */ - preventCancel?: boolean; -} - -interface ReadableStreamReadDoneResult { - done: true; - value: T | undefined; -} - -interface ReadableStreamReadValueResult { - done: false; - value: T; -} - -interface ReadableWritablePair { - readable: ReadableStream; - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream; -} - -interface RegistrationOptions { - scope?: string; - type?: WorkerType; - updateViaCache?: ServiceWorkerUpdateViaCache; -} - -interface RegistrationResponseJSON { - authenticatorAttachment?: string; - clientExtensionResults: AuthenticationExtensionsClientOutputsJSON; - id: string; - rawId: Base64URLString; - response: AuthenticatorAttestationResponseJSON; - type: string; -} - -interface Report { - body?: ReportBody | null; - type?: string; - url?: string; -} - -interface ReportBody { -} - -interface ReportingObserverOptions { - buffered?: boolean; - types?: string[]; -} - -interface RequestInit { - /** A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /** A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: RequestCache; - /** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */ - credentials?: RequestCredentials; - /** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string; - /** A boolean to set request's keepalive. */ - keepalive?: boolean; - /** A string to set request's method. */ - method?: string; - /** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */ - mode?: RequestMode; - priority?: RequestPriority; - /** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: RequestRedirect; - /** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */ - referrer?: string; - /** A referrer policy to set request's referrerPolicy. */ - referrerPolicy?: ReferrerPolicy; - /** An AbortSignal to set request's signal. */ - signal?: AbortSignal | null; - /** Can only be null. Used to disassociate request from any Window. */ - window?: null; -} - -interface ResizeObserverOptions { - box?: ResizeObserverBoxOptions; -} - -interface ResponseInit { - headers?: HeadersInit; - status?: number; - statusText?: string; -} - -interface RsaHashedImportParams extends Algorithm { - hash: HashAlgorithmIdentifier; -} - -interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { - hash: KeyAlgorithm; -} - -interface RsaHashedKeyGenParams extends RsaKeyGenParams { - hash: HashAlgorithmIdentifier; -} - -interface RsaKeyAlgorithm extends KeyAlgorithm { - modulusLength: number; - publicExponent: BigInteger; -} - -interface RsaKeyGenParams extends Algorithm { - modulusLength: number; - publicExponent: BigInteger; -} - -interface RsaOaepParams extends Algorithm { - label?: BufferSource; -} - -interface RsaOtherPrimesInfo { - d?: string; - r?: string; - t?: string; -} - -interface RsaPssParams extends Algorithm { - saltLength: number; -} - -interface SVGBoundingBoxOptions { - clipped?: boolean; - fill?: boolean; - markers?: boolean; - stroke?: boolean; -} - -interface SanitizerAttributeNamespace { - name: string; - namespace?: string | null; -} - -interface SanitizerConfig { - attributes?: SanitizerAttribute[]; - comments?: boolean; - dataAttributes?: boolean; - elements?: SanitizerElementWithAttributes[]; - removeAttributes?: SanitizerAttribute[]; - removeElements?: SanitizerElement[]; - replaceWithChildrenElements?: SanitizerElement[]; -} - -interface SanitizerElementNamespace { - name: string; - namespace?: string | null; -} - -interface SanitizerElementNamespaceWithAttributes extends SanitizerElementNamespace { - attributes?: SanitizerAttribute[]; - removeAttributes?: SanitizerAttribute[]; -} - -interface SchedulerPostTaskOptions { - delay?: number; - priority?: TaskPriority; - signal?: AbortSignal; -} - -interface ScrollIntoViewOptions extends ScrollOptions { - block?: ScrollLogicalPosition; - inline?: ScrollLogicalPosition; -} - -interface ScrollOptions { - behavior?: ScrollBehavior; -} - -interface ScrollTimelineOptions { - axis?: ScrollAxis; - source?: Element | null; -} - -interface ScrollToOptions extends ScrollOptions { - left?: number; - top?: number; -} - -interface SecurityPolicyViolationEventInit extends EventInit { - blockedURI?: string; - columnNumber?: number; - disposition?: SecurityPolicyViolationEventDisposition; - documentURI?: string; - effectiveDirective?: string; - lineNumber?: number; - originalPolicy?: string; - referrer?: string; - sample?: string; - sourceFile?: string; - statusCode?: number; - violatedDirective?: string; -} - -interface ShadowRootInit { - clonable?: boolean; - customElementRegistry?: CustomElementRegistry | null; - delegatesFocus?: boolean; - mode: ShadowRootMode; - serializable?: boolean; - slotAssignment?: SlotAssignmentMode; -} - -interface ShareData { - files?: File[]; - text?: string; - title?: string; - url?: string; -} - -interface ShowPopoverOptions { - source?: HTMLElement; -} - -interface SpeechRecognitionErrorEventInit extends EventInit { - error: SpeechRecognitionErrorCode; - message?: string; -} - -interface SpeechRecognitionEventInit extends EventInit { - resultIndex?: number; - results: SpeechRecognitionResultList; -} - -interface SpeechSynthesisErrorEventInit extends SpeechSynthesisEventInit { - error: SpeechSynthesisErrorCode; -} - -interface SpeechSynthesisEventInit extends EventInit { - charIndex?: number; - charLength?: number; - elapsedTime?: number; - name?: string; - utterance: SpeechSynthesisUtterance; -} - -interface StartViewTransitionOptions { - types?: string[] | null; - update?: ViewTransitionUpdateCallback | null; -} - -interface StaticRangeInit { - endContainer: Node; - endOffset: number; - startContainer: Node; - startOffset: number; -} - -interface StereoPannerOptions extends AudioNodeOptions { - pan?: number; -} - -interface StorageEstimate { - quota?: number; - usage?: number; -} - -interface StorageEventInit extends EventInit { - key?: string | null; - newValue?: string | null; - oldValue?: string | null; - storageArea?: Storage | null; - url?: string; -} - -interface StreamPipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - signal?: AbortSignal; -} - -interface StructuredSerializeOptions { - transfer?: Transferable[]; -} - -interface SubmitEventInit extends EventInit { - submitter?: HTMLElement | null; -} - -interface SvcOutputMetadata { - temporalLayerId?: number; -} - -interface TaskControllerInit { - priority?: TaskPriority; -} - -interface TaskPriorityChangeEventInit extends EventInit { - previousPriority: TaskPriority; -} - -interface TaskSignalAnyInit { - priority?: TaskPriority | TaskSignal; -} - -interface TextDecodeOptions { - stream?: boolean; -} - -interface TextDecoderOptions { - fatal?: boolean; - ignoreBOM?: boolean; -} - -interface TextEncoderEncodeIntoResult { - read: number; - written: number; -} - -interface TimelineRangeOffset { - offset?: CSSNumericValue; - rangeName?: string | null; -} - -interface ToggleEventInit extends EventInit { - newState?: string; - oldState?: string; - source?: Element | null; -} - -interface TogglePopoverOptions extends ShowPopoverOptions { - force?: boolean; -} - -interface TouchEventInit extends EventModifierInit { - changedTouches?: Touch[]; - targetTouches?: Touch[]; - touches?: Touch[]; -} - -interface TouchInit { - altitudeAngle?: number; - azimuthAngle?: number; - clientX?: number; - clientY?: number; - force?: number; - identifier: number; - pageX?: number; - pageY?: number; - radiusX?: number; - radiusY?: number; - rotationAngle?: number; - screenX?: number; - screenY?: number; - target: EventTarget; - touchType?: TouchType; -} - -interface TrackEventInit extends EventInit { - track?: TextTrack | null; -} - -interface Transformer { - flush?: TransformerFlushCallback; - readableType?: undefined; - start?: TransformerStartCallback; - transform?: TransformerTransformCallback; - writableType?: undefined; -} - -interface TransitionEventInit extends EventInit { - elapsedTime?: number; - propertyName?: string; - pseudoElement?: string; -} - -interface UIEventInit extends EventInit { - detail?: number; - view?: Window | null; - /** @deprecated */ - which?: number; -} - -interface ULongRange { - max?: number; - min?: number; -} - -interface URLPatternComponentResult { - groups: Record; - input: string; -} - -interface URLPatternInit { - baseURL?: string; - hash?: string; - hostname?: string; - password?: string; - pathname?: string; - port?: string; - protocol?: string; - search?: string; - username?: string; -} - -interface URLPatternOptions { - ignoreCase?: boolean; -} - -interface URLPatternResult { - hash: URLPatternComponentResult; - hostname: URLPatternComponentResult; - inputs: URLPatternInput[]; - password: URLPatternComponentResult; - pathname: URLPatternComponentResult; - port: URLPatternComponentResult; - protocol: URLPatternComponentResult; - search: URLPatternComponentResult; - username: URLPatternComponentResult; -} - -interface UnderlyingByteSource { - autoAllocateChunkSize?: number; - cancel?: UnderlyingSourceCancelCallback; - pull?: (controller: ReadableByteStreamController) => void | PromiseLike; - start?: (controller: ReadableByteStreamController) => any; - type: "bytes"; -} - -interface UnderlyingDefaultSource { - cancel?: UnderlyingSourceCancelCallback; - pull?: (controller: ReadableStreamDefaultController) => void | PromiseLike; - start?: (controller: ReadableStreamDefaultController) => any; - type?: undefined; -} - -interface UnderlyingSink { - abort?: UnderlyingSinkAbortCallback; - close?: UnderlyingSinkCloseCallback; - start?: UnderlyingSinkStartCallback; - type?: undefined; - write?: UnderlyingSinkWriteCallback; -} - -interface UnderlyingSource { - autoAllocateChunkSize?: number; - cancel?: UnderlyingSourceCancelCallback; - pull?: UnderlyingSourcePullCallback; - start?: UnderlyingSourceStartCallback; - type?: ReadableStreamType; -} - -interface UnknownCredentialOptions { - credentialId: Base64URLString; - rpId: string; -} - -interface ValidityStateFlags { - badInput?: boolean; - customError?: boolean; - patternMismatch?: boolean; - rangeOverflow?: boolean; - rangeUnderflow?: boolean; - stepMismatch?: boolean; - tooLong?: boolean; - tooShort?: boolean; - typeMismatch?: boolean; - valueMissing?: boolean; -} - -interface VideoColorSpaceInit { - fullRange?: boolean | null; - matrix?: VideoMatrixCoefficients | null; - primaries?: VideoColorPrimaries | null; - transfer?: VideoTransferCharacteristics | null; -} - -interface VideoConfiguration { - bitrate: number; - colorGamut?: ColorGamut; - contentType: string; - framerate: number; - hasAlphaChannel?: boolean; - hdrMetadataType?: HdrMetadataType; - height: number; - scalabilityMode?: string; - transferFunction?: TransferFunction; - width: number; -} - -interface VideoDecoderConfig { - codec: string; - codedHeight?: number; - codedWidth?: number; - colorSpace?: VideoColorSpaceInit; - description?: AllowSharedBufferSource; - displayAspectHeight?: number; - displayAspectWidth?: number; - hardwareAcceleration?: HardwareAcceleration; - optimizeForLatency?: boolean; -} - -interface VideoDecoderInit { - error: WebCodecsErrorCallback; - output: VideoFrameOutputCallback; -} - -interface VideoDecoderSupport { - config?: VideoDecoderConfig; - supported?: boolean; -} - -interface VideoEncoderConfig { - alpha?: AlphaOption; - avc?: AvcEncoderConfig; - bitrate?: number; - bitrateMode?: VideoEncoderBitrateMode; - codec: string; - contentHint?: string; - displayHeight?: number; - displayWidth?: number; - framerate?: number; - hardwareAcceleration?: HardwareAcceleration; - height: number; - latencyMode?: LatencyMode; - scalabilityMode?: string; - width: number; -} - -interface VideoEncoderEncodeOptions { - avc?: VideoEncoderEncodeOptionsForAvc; - keyFrame?: boolean; -} - -interface VideoEncoderEncodeOptionsForAvc { - quantizer?: number | null; -} - -interface VideoEncoderInit { - error: WebCodecsErrorCallback; - output: EncodedVideoChunkOutputCallback; -} - -interface VideoEncoderSupport { - config?: VideoEncoderConfig; - supported?: boolean; -} - -interface VideoFrameBufferInit { - codedHeight: number; - codedWidth: number; - colorSpace?: VideoColorSpaceInit; - displayHeight?: number; - displayWidth?: number; - duration?: number; - format: VideoPixelFormat; - layout?: PlaneLayout[]; - timestamp: number; - visibleRect?: DOMRectInit; -} - -interface VideoFrameCallbackMetadata { - captureTime?: DOMHighResTimeStamp; - expectedDisplayTime: DOMHighResTimeStamp; - height: number; - mediaTime: number; - presentationTime: DOMHighResTimeStamp; - presentedFrames: number; - processingDuration?: number; - receiveTime?: DOMHighResTimeStamp; - rtpTimestamp?: number; - width: number; -} - -interface VideoFrameCopyToOptions { - colorSpace?: PredefinedColorSpace; - format?: VideoPixelFormat; - layout?: PlaneLayout[]; - rect?: DOMRectInit; -} - -interface VideoFrameInit { - alpha?: AlphaOption; - displayHeight?: number; - displayWidth?: number; - duration?: number; - timestamp?: number; - visibleRect?: DOMRectInit; -} - -interface ViewTimelineOptions { - axis?: ScrollAxis; - inset?: string | (CSSNumericValue | CSSKeywordValue)[]; - subject?: Element; -} - -interface WaveShaperOptions extends AudioNodeOptions { - curve?: number[] | Float32Array; - oversample?: OverSampleType; -} - -interface WebGLContextAttributes { - alpha?: boolean; - antialias?: boolean; - depth?: boolean; - desynchronized?: boolean; - failIfMajorPerformanceCaveat?: boolean; - powerPreference?: WebGLPowerPreference; - premultipliedAlpha?: boolean; - preserveDrawingBuffer?: boolean; - stencil?: boolean; - xrCompatible?: boolean; -} - -interface WebGLContextEventInit extends EventInit { - statusMessage?: string; -} - -interface WebTransportCloseInfo { - closeCode?: number; - reason?: string; -} - -interface WebTransportErrorOptions { - source?: WebTransportErrorSource; - streamErrorCode?: number | null; -} - -interface WebTransportHash { - algorithm: string; - value: BufferSource; -} - -interface WebTransportOptions { - allowPooling?: boolean; - congestionControl?: WebTransportCongestionControl; - protocols?: string[]; - requireUnreliable?: boolean; - serverCertificateHashes?: WebTransportHash[]; -} - -interface WebTransportSendOptions { - sendOrder?: number; -} - -interface WebTransportSendStreamOptions extends WebTransportSendOptions { -} - -interface WheelEventInit extends MouseEventInit { - deltaMode?: number; - deltaX?: number; - deltaY?: number; - deltaZ?: number; -} - -interface WindowPostMessageOptions extends StructuredSerializeOptions { - targetOrigin?: string; -} - -interface WorkerOptions { - credentials?: RequestCredentials; - name?: string; - type?: WorkerType; -} - -interface WorkletOptions { - credentials?: RequestCredentials; -} - -interface WriteParams { - data?: BufferSource | Blob | string | null; - position?: number | null; - size?: number | null; - type: WriteCommandType; -} - -type NodeFilter = ((node: Node) => number) | { acceptNode(node: Node): number; }; - -declare var NodeFilter: { - readonly FILTER_ACCEPT: 1; - readonly FILTER_REJECT: 2; - readonly FILTER_SKIP: 3; - readonly SHOW_ALL: 0xFFFFFFFF; - readonly SHOW_ELEMENT: 0x1; - readonly SHOW_ATTRIBUTE: 0x2; - readonly SHOW_TEXT: 0x4; - readonly SHOW_CDATA_SECTION: 0x8; - readonly SHOW_ENTITY_REFERENCE: 0x10; - readonly SHOW_ENTITY: 0x20; - readonly SHOW_PROCESSING_INSTRUCTION: 0x40; - readonly SHOW_COMMENT: 0x80; - readonly SHOW_DOCUMENT: 0x100; - readonly SHOW_DOCUMENT_TYPE: 0x200; - readonly SHOW_DOCUMENT_FRAGMENT: 0x400; - readonly SHOW_NOTATION: 0x800; -}; - -type XPathNSResolver = ((prefix: string | null) => string | null) | { lookupNamespaceURI(prefix: string | null): string | null; }; - -/** - * The **`ANGLE_instanced_arrays`** extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays) - */ -interface ANGLE_instanced_arrays { - /** - * The **`ANGLE_instanced_arrays.drawArraysInstancedANGLE()`** method of the WebGL API renders primitives from array data like the gl.drawArrays() method. In addition, it can execute multiple instances of the range of elements. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays/drawArraysInstancedANGLE) - */ - drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; - /** - * The **`ANGLE_instanced_arrays.drawElementsInstancedANGLE()`** method of the WebGL API renders primitives from array data like the gl.drawElements() method. In addition, it can execute multiple instances of a set of elements. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays/drawElementsInstancedANGLE) - */ - drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; - /** - * The **`ANGLE_instanced_arrays.vertexAttribDivisorANGLE()`** method of the WebGL API modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with ext.drawArraysInstancedANGLE() and ext.drawElementsInstancedANGLE(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ANGLE_instanced_arrays/vertexAttribDivisorANGLE) - */ - vertexAttribDivisorANGLE(index: GLuint, divisor: GLuint): void; - readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: 0x88FE; -} - -interface ARIAMixin { - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaActiveDescendantElement) */ - ariaActiveDescendantElement: Element | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaAtomic) */ - ariaAtomic: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaAutoComplete) */ - ariaAutoComplete: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaBrailleLabel) */ - ariaBrailleLabel: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaBrailleRoleDescription) */ - ariaBrailleRoleDescription: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaBusy) */ - ariaBusy: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaChecked) */ - ariaChecked: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColCount) */ - ariaColCount: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColIndex) */ - ariaColIndex: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColIndexText) */ - ariaColIndexText: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColSpan) */ - ariaColSpan: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaControlsElements) */ - ariaControlsElements: ReadonlyArray | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaCurrent) */ - ariaCurrent: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaDescribedByElements) */ - ariaDescribedByElements: ReadonlyArray | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaDescription) */ - ariaDescription: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaDetailsElements) */ - ariaDetailsElements: ReadonlyArray | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaDisabled) */ - ariaDisabled: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaErrorMessageElements) */ - ariaErrorMessageElements: ReadonlyArray | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaExpanded) */ - ariaExpanded: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaFlowToElements) */ - ariaFlowToElements: ReadonlyArray | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaHasPopup) */ - ariaHasPopup: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaHidden) */ - ariaHidden: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaInvalid) */ - ariaInvalid: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaKeyShortcuts) */ - ariaKeyShortcuts: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaLabel) */ - ariaLabel: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaLabelledByElements) */ - ariaLabelledByElements: ReadonlyArray | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaLevel) */ - ariaLevel: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaLive) */ - ariaLive: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaModal) */ - ariaModal: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaMultiLine) */ - ariaMultiLine: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaMultiSelectable) */ - ariaMultiSelectable: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaOrientation) */ - ariaOrientation: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaOwnsElements) */ - ariaOwnsElements: ReadonlyArray | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaPlaceholder) */ - ariaPlaceholder: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaPosInSet) */ - ariaPosInSet: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaPressed) */ - ariaPressed: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaReadOnly) */ - ariaReadOnly: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRelevant) */ - ariaRelevant: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRequired) */ - ariaRequired: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRoleDescription) */ - ariaRoleDescription: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowCount) */ - ariaRowCount: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowIndex) */ - ariaRowIndex: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowIndexText) */ - ariaRowIndexText: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowSpan) */ - ariaRowSpan: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaSelected) */ - ariaSelected: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaSetSize) */ - ariaSetSize: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaSort) */ - ariaSort: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueMax) */ - ariaValueMax: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueMin) */ - ariaValueMin: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueNow) */ - ariaValueNow: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaValueText) */ - ariaValueText: string | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/role) */ - role: string | null; -} - -/** - * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) - */ -interface AbortController { - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - readonly signal: AbortSignal; - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. This is able to abort fetch requests, the consumption of any response bodies, or streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void; -} - -declare var AbortController: { - prototype: AbortController; - new(): AbortController; -}; - -interface AbortSignalEventMap { - "abort": Event; -} - -/** - * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) - */ -interface AbortSignal extends EventTarget { - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (true) or not (false). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - readonly aborted: boolean; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - onabort: ((this: AbortSignal, ev: Event) => any) | null; - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - readonly reason: any; - /** - * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; - addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var AbortSignal: { - prototype: AbortSignal; - new(): AbortSignal; - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - abort(reason?: any): AbortSignal; - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. The returned abort signal is aborted when any of the input iterable abort signals are aborted. The abort reason will be set to the reason of the first signal that is aborted. If any of the given abort signals are already aborted then so will be the returned AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - any(signals: AbortSignal[]): AbortSignal; - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - timeout(milliseconds: number): AbortSignal; -}; - -/** - * The **`AbstractRange`** abstract interface is the base class upon which all DOM range types are defined. A range is an object that indicates the start and end points of a section of content within the document. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange) - */ -interface AbstractRange { - /** - * The read-only **`collapsed`** property of the AbstractRange interface returns true if the range's start position and end position are the same. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/collapsed) - */ - readonly collapsed: boolean; - /** - * The read-only **`endContainer`** property of the AbstractRange interface returns the Node in which the end of the range is located. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/endContainer) - */ - readonly endContainer: Node; - /** - * The **`endOffset`** property of the AbstractRange interface returns the offset into the end node of the range's end position. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/endOffset) - */ - readonly endOffset: number; - /** - * The read-only **`startContainer`** property of the AbstractRange interface returns the Node in which the start of the range is located. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/startContainer) - */ - readonly startContainer: Node; - /** - * The read-only **`startOffset`** property of the AbstractRange interface returns the offset into the start node of the range's start position. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbstractRange/startOffset) - */ - readonly startOffset: number; -} - -declare var AbstractRange: { - prototype: AbstractRange; - new(): AbstractRange; -}; - -interface AbstractWorkerEventMap { - "error": ErrorEvent; -} - -interface AbstractWorker { - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorker/error_event) */ - onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; - addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -/** - * The **`AnalyserNode`** interface represents a node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode) - */ -interface AnalyserNode extends AudioNode { - /** - * The **`fftSize`** property of the AnalyserNode interface is an unsigned long value and represents the window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/fftSize) - */ - fftSize: number; - /** - * The **`frequencyBinCount`** read-only property of the AnalyserNode interface contains the total number of data points available to AudioContext sampleRate. This is half of the value of the AnalyserNode.fftSize. The two methods' indices have a linear relationship with the frequencies they represent, between 0 and the Nyquist frequency. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/frequencyBinCount) - */ - readonly frequencyBinCount: number; - /** - * The **`maxDecibels`** property of the AnalyserNode interface is a double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using getByteFrequencyData(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/maxDecibels) - */ - maxDecibels: number; - /** - * The **`minDecibels`** property of the AnalyserNode interface is a double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using getByteFrequencyData(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/minDecibels) - */ - minDecibels: number; - /** - * The **`smoothingTimeConstant`** property of the AnalyserNode interface is a double value representing the averaging constant with the last analysis frame. It's basically an average between the current buffer and the last buffer the AnalyserNode processed, and results in a much smoother set of value changes over time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/smoothingTimeConstant) - */ - smoothingTimeConstant: number; - /** - * The **`getByteFrequencyData()`** method of the AnalyserNode interface copies the current frequency data into a Uint8Array (unsigned byte array) passed into it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getByteFrequencyData) - */ - getByteFrequencyData(array: Uint8Array): void; - /** - * The **`getByteTimeDomainData()`** method of the AnalyserNode Interface copies the current waveform, or time-domain, data into a Uint8Array (unsigned byte array) passed into it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getByteTimeDomainData) - */ - getByteTimeDomainData(array: Uint8Array): void; - /** - * The **`getFloatFrequencyData()`** method of the AnalyserNode Interface copies the current frequency data into a Float32Array array passed into it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getFloatFrequencyData) - */ - getFloatFrequencyData(array: Float32Array): void; - /** - * The **`getFloatTimeDomainData()`** method of the AnalyserNode Interface copies the current waveform, or time-domain, data into a Float32Array array passed into it. Each array value is a sample, the magnitude of the signal at a particular time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnalyserNode/getFloatTimeDomainData) - */ - getFloatTimeDomainData(array: Float32Array): void; -} - -declare var AnalyserNode: { - prototype: AnalyserNode; - new(context: BaseAudioContext, options?: AnalyserOptions): AnalyserNode; -}; - -interface Animatable { - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animate) */ - animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/getAnimations) */ - getAnimations(options?: GetAnimationsOptions): Animation[]; -} - -interface AnimationEventMap { - "cancel": AnimationPlaybackEvent; - "finish": AnimationPlaybackEvent; - "remove": AnimationPlaybackEvent; -} - -/** - * The **`Animation`** interface of the Web Animations API represents a single animation player and provides playback controls and a timeline for an animation node or source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation) - */ -interface Animation extends EventTarget { - /** - * The **`Animation.currentTime`** property of the Web Animations API returns and sets the current time value of the animation in milliseconds, whether running or paused. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/currentTime) - */ - currentTime: CSSNumberish | null; - /** - * The **`Animation.effect`** property of the Web Animations API gets and sets the target effect of an animation. The target effect may be either an effect object of a type based on AnimationEffect, such as KeyframeEffect, or null. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/effect) - */ - effect: AnimationEffect | null; - /** - * The **`Animation.finished`** read-only property of the Web Animations API returns a Promise which resolves once the animation has finished playing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/finished) - */ - readonly finished: Promise; - /** - * The **`Animation.id`** property of the Web Animations API returns or sets a string used to identify the animation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/id) - */ - id: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/cancel_event) */ - oncancel: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/finish_event) */ - onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/remove_event) */ - onremove: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; - /** - * The **`overallProgress`** read-only property of the Animation interface returns a number between 0 and 1 indicating the animation's overall progress towards its finished state. This is the overall progress across all of the animation's iterations, not each individual iteration. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/overallProgress) - */ - readonly overallProgress: number | null; - /** - * The read-only **`Animation.pending`** property of the Web Animations API indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/pending) - */ - readonly pending: boolean; - /** - * The read-only **`Animation.playState`** property of the Web Animations API returns an enumerated value describing the playback state of an animation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/playState) - */ - readonly playState: AnimationPlayState; - /** - * The **`Animation.playbackRate`** property of the Web Animations API returns or sets the playback rate of the animation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/playbackRate) - */ - playbackRate: number; - /** - * The read-only **`Animation.ready`** property of the Web Animations API returns a Promise which resolves when the animation is ready to play. A new promise is created every time the animation enters the "pending" play state as well as when the animation is canceled, since in both of those scenarios, the animation is ready to be started again. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/ready) - */ - readonly ready: Promise; - /** - * The read-only **`Animation.replaceState`** property of the Web Animations API indicates whether the animation has been removed by the browser automatically after being replaced by another animation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/replaceState) - */ - readonly replaceState: AnimationReplaceState; - /** - * The **`Animation.startTime`** property of the Animation interface is a double-precision floating-point value which indicates the scheduled time when an animation's playback should begin. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/startTime) - */ - startTime: CSSNumberish | null; - /** - * The **`Animation.timeline`** property of the Animation interface returns or sets the timeline associated with this animation. A timeline is a source of time values for synchronization purposes, and is an AnimationTimeline-based object. By default, the animation's timeline and the Document's timeline are the same. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/timeline) - */ - timeline: AnimationTimeline | null; - /** - * The Web Animations API's **`cancel()`** method of the Animation interface clears all KeyframeEffects caused by this animation and aborts its playback. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/cancel) - */ - cancel(): void; - /** - * The **`commitStyles()`** method of the Web Animations API's Animation interface writes the computed values of the animation's current styles into its target element's style attribute. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/commitStyles) - */ - commitStyles(): void; - /** - * The **`finish()`** method of the Web Animations API's Animation Interface sets the current playback time to the end of the animation corresponding to the current playback direction. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/finish) - */ - finish(): void; - /** - * The **`pause()`** method of the Web Animations API's Animation interface suspends playback of the animation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/pause) - */ - pause(): void; - /** - * The **`persist()`** method of the Web Animations API's Animation interface explicitly persists an animation, preventing it from being automatically removed when it is replaced by another animation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/persist) - */ - persist(): void; - /** - * The **`play()`** method of the Web Animations API's Animation Interface starts or resumes playing of an animation. If the animation is finished, calling play() restarts the animation, playing it from the beginning. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/play) - */ - play(): void; - /** - * The **`Animation.reverse()`** method of the Animation Interface reverses the playback direction, meaning the animation ends at its beginning. If called on an unplayed animation, the whole animation is played backwards. If called on a paused animation, the animation will continue in reverse. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/reverse) - */ - reverse(): void; - /** - * The **`updatePlaybackRate()`** method of the Web Animations API's Animation Interface sets the speed of an animation after first synchronizing its playback position. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/updatePlaybackRate) - */ - updatePlaybackRate(playbackRate: number): void; - addEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var Animation: { - prototype: Animation; - new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation; -}; - -/** - * The **`AnimationEffect`** interface of the Web Animations API is an interface representing animation effects. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect) - */ -interface AnimationEffect { - /** - * The **`getComputedTiming()`** method of the AnimationEffect interface returns the calculated timing properties for this animation effect. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect/getComputedTiming) - */ - getComputedTiming(): ComputedEffectTiming; - /** - * The **`AnimationEffect.getTiming()`** method of the AnimationEffect interface returns an object containing the timing properties for the Animation Effect. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect/getTiming) - */ - getTiming(): EffectTiming; - /** - * The **`updateTiming()`** method of the AnimationEffect interface updates the specified timing properties for an animation effect. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEffect/updateTiming) - */ - updateTiming(timing?: OptionalEffectTiming): void; -} - -declare var AnimationEffect: { - prototype: AnimationEffect; - new(): AnimationEffect; -}; - -/** - * The **`AnimationEvent`** interface represents events providing information related to animations. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent) - */ -interface AnimationEvent extends Event { - /** - * The **`AnimationEvent.animationName`** read-only property is a string containing the value of the animation-name CSS property associated with the transition. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent/animationName) - */ - readonly animationName: string; - /** - * The **`AnimationEvent.elapsedTime`** read-only property is a float giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an animationstart event, elapsedTime is 0.0 unless there was a negative value for animation-delay, in which case the event will be fired with elapsedTime containing (-1 * delay). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent/elapsedTime) - */ - readonly elapsedTime: number; - /** - * The **`AnimationEvent.pseudoElement`** read-only property is a string, starting with '::', containing the name of the pseudo-element the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: ''. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationEvent/pseudoElement) - */ - readonly pseudoElement: string; -} - -declare var AnimationEvent: { - prototype: AnimationEvent; - new(type: string, animationEventInitDict?: AnimationEventInit): AnimationEvent; -}; - -interface AnimationFrameProvider { - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/cancelAnimationFrame) */ - cancelAnimationFrame(handle: number): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/requestAnimationFrame) */ - requestAnimationFrame(callback: FrameRequestCallback): number; -} - -/** - * The **`AnimationPlaybackEvent`** interface of the Web Animations API represents animation events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationPlaybackEvent) - */ -interface AnimationPlaybackEvent extends Event { - /** - * The **`currentTime`** read-only property of the AnimationPlaybackEvent interface represents the current time of the animation that generated the event at the moment the event is queued. This will be unresolved if the animation was idle at the time the event was generated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationPlaybackEvent/currentTime) - */ - readonly currentTime: CSSNumberish | null; - /** - * The **`timelineTime`** read-only property of the AnimationPlaybackEvent interface represents the time value of the animation's timeline at the moment the event is queued. This will be unresolved if the animation was not associated with a timeline at the time the event was generated or if the associated timeline was inactive. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationPlaybackEvent/timelineTime) - */ - readonly timelineTime: CSSNumberish | null; -} - -declare var AnimationPlaybackEvent: { - prototype: AnimationPlaybackEvent; - new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; -}; - -/** - * The **`AnimationTimeline`** interface of the Web Animations API represents the timeline of an animation. This interface exists to define timeline features, inherited by other timeline types: - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationTimeline) - */ -interface AnimationTimeline { - /** - * The **`currentTime`** read-only property of the Web Animations API's AnimationTimeline interface returns the timeline's current time in milliseconds, or null if the timeline is inactive. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationTimeline/currentTime) - */ - readonly currentTime: CSSNumberish | null; - /** - * The **`duration`** read-only property of the Web Animations API's AnimationTimeline interface returns the maximum value for this timeline or null. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AnimationTimeline/duration) - */ - readonly duration: CSSNumberish | null; -} - -declare var AnimationTimeline: { - prototype: AnimationTimeline; - new(): AnimationTimeline; -}; - -/** - * The **`Attr`** interface represents one of an element's attributes as an object. In most situations, you will directly retrieve the attribute value as a string (e.g., Element.getAttribute()), but some cases may require interacting with Attr instances (e.g., Element.getAttributeNode()). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr) - */ -interface Attr extends Node { - /** - * The read-only **`localName`** property of the Attr interface returns the local part of the qualified name of an attribute, that is the name of the attribute, stripped from any namespace in front of it. For example, if the qualified name is xml:lang, the returned local name is lang, if the element supports that namespace. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/localName) - */ - readonly localName: string; - /** - * The read-only **`name`** property of the Attr interface returns the qualified name of an attribute, that is the name of the attribute, with the namespace prefix, if any, in front of it. For example, if the local name is lang and the namespace prefix is xml, the returned qualified name is xml:lang. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/name) - */ - readonly name: string; - /** - * The read-only **`namespaceURI`** property of the Attr interface returns the namespace URI of the attribute, or null if the element is not in a namespace. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/namespaceURI) - */ - readonly namespaceURI: string | null; - readonly ownerDocument: Document; - /** - * The read-only **`ownerElement`** property of the Attr interface returns the Element the attribute belongs to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/ownerElement) - */ - readonly ownerElement: Element | null; - /** - * The read-only **`prefix`** property of the Attr returns the namespace prefix of the attribute, or null if no prefix is specified. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/prefix) - */ - readonly prefix: string | null; - /** - * The read-only **`specified`** property of the Attr interface always returns true. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/specified) - */ - readonly specified: boolean; - /** - * The **`value`** property of the Attr interface contains the value of the attribute. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Attr/value) - */ - value: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/textContent) */ - get textContent(): string; - set textContent(value: string | null); -} - -declare var Attr: { - prototype: Attr; - new(): Attr; -}; - -/** - * The **`AudioBuffer`** interface represents a short audio asset residing in memory, created from an audio file using the AudioContext.decodeAudioData() method, or from raw data using AudioContext.createBuffer(). Once put into an AudioBuffer, the audio can then be played by being passed into an AudioBufferSourceNode. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer) - */ -interface AudioBuffer { - /** - * The **`duration`** property of the AudioBuffer interface returns a double representing the duration, in seconds, of the PCM data stored in the buffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/duration) - */ - readonly duration: number; - /** - * The **`length`** property of the AudioBuffer interface returns an integer representing the length, in sample-frames, of the PCM data stored in the buffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/length) - */ - readonly length: number; - /** - * The **`numberOfChannels`** property of the AudioBuffer interface returns an integer representing the number of discrete audio channels described by the PCM data stored in the buffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/numberOfChannels) - */ - readonly numberOfChannels: number; - /** - * The **`sampleRate`** property of the AudioBuffer interface returns a float representing the sample rate, in samples per second, of the PCM data stored in the buffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/sampleRate) - */ - readonly sampleRate: number; - /** - * The **`copyFromChannel()`** method of the AudioBuffer interface copies the audio sample data from the specified channel of the AudioBuffer to a specified Float32Array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/copyFromChannel) - */ - copyFromChannel(destination: Float32Array, channelNumber: number, bufferOffset?: number): void; - /** - * The **`copyToChannel()`** method of the AudioBuffer interface copies the samples to the specified channel of the AudioBuffer, from the source array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/copyToChannel) - */ - copyToChannel(source: Float32Array, channelNumber: number, bufferOffset?: number): void; - /** - * The **`getChannelData()`** method of the AudioBuffer Interface returns a Float32Array containing the PCM data associated with the channel, defined by the channel parameter (with 0 representing the first channel). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBuffer/getChannelData) - */ - getChannelData(channel: number): Float32Array; -} - -declare var AudioBuffer: { - prototype: AudioBuffer; - new(options: AudioBufferOptions): AudioBuffer; -}; - -/** - * The **`AudioBufferSourceNode`** interface is an AudioScheduledSourceNode which represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode) - */ -interface AudioBufferSourceNode extends AudioScheduledSourceNode { - /** - * The **`buffer`** property of the AudioBufferSourceNode interface provides the ability to play back audio using an AudioBuffer as the source of the sound data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/buffer) - */ - buffer: AudioBuffer | null; - /** - * The **`detune`** property of the AudioBufferSourceNode interface is a k-rate AudioParam representing detuning of oscillation in cents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/detune) - */ - readonly detune: AudioParam; - /** - * The **`loop`** property of the AudioBufferSourceNode interface is a Boolean indicating if the audio asset must be replayed when the end of the AudioBuffer is reached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/loop) - */ - loop: boolean; - /** - * The **`loopEnd`** property of the AudioBufferSourceNode interface specifies is a floating point number specifying, in seconds, at what offset into playing the AudioBuffer playback should loop back to the time indicated by the loopStart property. This is only used if the loop property is true. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/loopEnd) - */ - loopEnd: number; - /** - * The **`loopStart`** property of the AudioBufferSourceNode interface is a floating-point value indicating, in seconds, where in the AudioBuffer the restart of the play must happen. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/loopStart) - */ - loopStart: number; - /** - * The **`playbackRate`** property of the AudioBufferSourceNode interface Is a k-rate AudioParam that defines the speed at which the audio asset will be played. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/playbackRate) - */ - readonly playbackRate: AudioParam; - /** - * The **`start()`** method of the AudioBufferSourceNode Interface is used to schedule playback of the audio data contained in the buffer, or to begin playback immediately. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode/start) - */ - start(when?: number, offset?: number, duration?: number): void; - addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; - removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; -} - -declare var AudioBufferSourceNode: { - prototype: AudioBufferSourceNode; - new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode; -}; - -/** - * The **`AudioContext`** interface represents an audio-processing graph built from audio modules linked together, each represented by an AudioNode. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext) - */ -interface AudioContext extends BaseAudioContext { - /** - * The **`baseLatency`** read-only property of the AudioContext interface returns a double that represents the number of seconds of processing latency incurred by the AudioContext passing an audio buffer from the AudioDestinationNode — i.e., the end of the audio graph — into the host system's audio subsystem ready for playing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/baseLatency) - */ - readonly baseLatency: number; - /** - * The **`outputLatency`** read-only property of the AudioContext Interface provides an estimation of the output latency of the current audio context. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/outputLatency) - */ - readonly outputLatency: number; - /** - * The **`close()`** method of the AudioContext Interface closes the audio context, releasing any system audio resources that it uses. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioContext/close) - */ - close(): Promise; - /** - * The **`createMediaElementSource()`** method of the AudioContext Interface is used to create a new MediaElementAudioSourceNode object, given an existing HTML