Skip to content

Commit

Permalink
feat: migrate to ES5 compatible loader
Browse files Browse the repository at this point in the history
  • Loading branch information
CAMOBAP committed Jun 26, 2024
1 parent 6c8d7e3 commit 7f421f0
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 31 deletions.
18 changes: 12 additions & 6 deletions sdk/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ plugins {
}

ext {
hcaptchaLoaderVersion = "1.1.3"
hcaptchaLoaderVersion = "1.2.3"
}

android {
Expand Down Expand Up @@ -117,14 +117,20 @@ project.afterEvaluate {
}
}

long MAX_AAR_SIZE_KB = 200
long MAX_AAR_SIZE_KB = 250

tasks.register('downloadHCaptchaLoaderJs', Download) {
src "https://www.unpkg.com/@hcaptcha/loader@${hcaptchaLoaderVersion}/dist/index.mjs"
dest layout.buildDirectory.file("generated/assets/hcaptcha/loader.mjs")
tasks.register('downloadPolyfillsJs', Download) {
src "https://www.unpkg.com/@hcaptcha/loader@${hcaptchaLoaderVersion}/dist/polyfills.js"
dest layout.buildDirectory.file("generated/assets/hcaptcha/polyfills.js")
onlyIfModified true
}

tasks.register('downloadHCaptchaLoaderJs', Download) {
src "https://www.unpkg.com/@hcaptcha/loader@${hcaptchaLoaderVersion}/dist/index.es5.js"
dest layout.buildDirectory.file("generated/assets/hcaptcha/loader.js")
onlyIfModified true
}.get().dependsOn('downloadPolyfillsJs')

android.sourceSets.main.assets.srcDirs += [layout.buildDirectory.file("generated/assets")]

android.libraryVariants.all { variant ->
Expand All @@ -150,7 +156,7 @@ android.libraryVariants.all { variant ->
var aarFile = variant.packageLibraryProvider.get().archiveFile.get().getAsFile()
long aarSizeKb = aarFile.length() / 1024
if (aarSizeKb > MAX_AAR_SIZE_KB) {
throw new GradleException("${aarPath} size exceeded! ${aarSizeKb}Kbyte > ${MAX_AAR_SIZE_KB}Kbyte")
throw new GradleException("${aarFile} size exceeded! ${aarSizeKb}Kbyte > ${MAX_AAR_SIZE_KB}Kbyte")
}
}
})
Expand Down
33 changes: 16 additions & 17 deletions sdk/src/main/html/hcaptcha.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
window.sysDebug = JSON.parse(window.JSDI.getSysDebug());
}
</script>
<script type="module">
import { hCaptchaLoader } from 'https://www.unpkg.com/@hcaptcha/loader@@LOADER_VERSION@/dist/index.mjs';

<script type="text/javascript" src="https://unpkg.com/@hcaptcha/loader@@LOADER_VERSION@/dist/polyfills.js"></script>
<script type="text/javascript" src="https://unpkg.com/@hcaptcha/loader@@LOADER_VERSION@/dist/index.es5.js"></script>
<script>
// Android will inject this bridge object as `JSInterface`
// Browser is missing it, so we mock it
var BridgeObject = window.JSInterface || {
Expand Down Expand Up @@ -75,9 +75,9 @@
/**
* Called programmatically from HCaptchaWebViewHelper.
*/
async function resetAndExecute() {
function resetAndExecute() {
hcaptcha.reset();
await execute();
execute();
}
window.resetAndExecute = resetAndExecute;
function reset() {
Expand Down Expand Up @@ -175,17 +175,16 @@
BridgeObject.onError(30);
}
});
async function execute() {
try {
var { response } = await hcaptcha.execute(getScriptParams(bridgeConfig));
function execute() {
hcaptcha.execute(getScriptParams(bridgeConfig)).then(function(result) {
var response = result.response;
BridgeObject.onPass(response);
} catch (error) {
}).catch(function(error) {
errorCallback(error);
}
});
}
async function loadApi(config) {
try {
window.hcaptcha = await hCaptchaLoader(getLoaderParams(config));
function loadApi(config) {
hCaptchaLoader(getLoaderParams(config)).then(function(hcaptcha) {
var renderConfig = getRenderConfig(config);
hcaptcha.render("hcaptcha-container", renderConfig);
BridgeObject.onLoaded();
Expand All @@ -197,12 +196,12 @@
// We want to auto execute in case of `invisible` checkbox.
// But not in case of `hideDialog` since verification process
// might be desired to happen at a later time.
await execute();
execute();
}
} catch (e) {
console.error("loadApi error", e);
}).catch(function(error) {
console.error("loadApi error", error);
BridgeObject.onError(29);
}
});
}
loadApi(bridgeConfig);
</script>
Expand Down
17 changes: 11 additions & 6 deletions sdk/src/main/java/com/hcaptcha/sdk/HCaptchaWebViewHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

final class HCaptchaWebViewHelper {
Expand Down Expand Up @@ -124,15 +126,17 @@ public boolean shouldRetry(HCaptchaException exception) {

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private class HCaptchaWebClient extends WebViewClient {
private final Uri loaderUri = Uri.parse(
"https://www.unpkg.com/@hcaptcha/loader@" + BuildConfig.LOADER_VERSION + "/dist/index.mjs"
);
private final Map<Uri, String> assetsCache = new HashMap<>();

@NonNull
private final Handler handler;

HCaptchaWebClient(@NonNull Handler handler) {
this.handler = handler;

final String baseUrl = "https://unpkg.com/@hcaptcha/loader@" + BuildConfig.LOADER_VERSION + "/dist";
assetsCache.put(Uri.parse(baseUrl + "/index.es5.js"), "hcaptcha/loader.js");
assetsCache.put(Uri.parse(baseUrl + "/polyfills.js"), "hcaptcha/polyfills.js");
}

private String stripUrl(String url) {
Expand All @@ -142,7 +146,8 @@ private String stripUrl(String url) {
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, final WebResourceRequest request) {
final Uri requestUri = request.getUrl();
if (loaderUri.equals(requestUri)) {
final String assetPath = assetsCache.get(requestUri);
if (assetPath != null) {
try {
return new WebResourceResponse(
"application/javascript",
Expand All @@ -151,10 +156,10 @@ public WebResourceResponse shouldInterceptRequest (final WebView view, final Web
"OK",
Collections.singletonMap("Access-Control-Allow-Origin",
Objects.toString(config.getHost(), "null")),
view.getContext().getAssets().open("hcaptcha/loader.mjs")
view.getContext().getAssets().open(assetPath)
);
} catch (IOException e) {
HCaptchaLog.w("WebViewHelper wasn't able to load loader.mjs from assets");
HCaptchaLog.w("WebViewHelper wasn't able to load " + assetPath + " from assets");
}
} else if (requestUri != null && requestUri.getScheme() != null && requestUri.getScheme().equals("http")) {
handler.post(() -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
import static org.mockito.Mockito.mock;

import android.content.Context;
import android.content.res.AssetManager;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import androidx.test.core.app.ActivityScenario;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.platform.app.InstrumentationRegistry;

Expand All @@ -22,6 +24,7 @@
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -95,7 +98,19 @@ public void onFailure(HCaptchaException e) {

@Test
public void testLoaderJsAssetPresence() throws IOException {
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertNotNull(appContext.getAssets().open("hcaptcha/loader.mjs"));
AssetManager assets = InstrumentationRegistry
.getInstrumentation()
.getTargetContext()
.getAssets();
assertNotNull(assets.open("hcaptcha/loader.js"));
}

@Test
public void testPolyfillsJsAssetPresence() throws IOException {
AssetManager assets = InstrumentationRegistry
.getInstrumentation()
.getTargetContext()
.getAssets();
assertNotNull(assets.open("hcaptcha/polyfills.js"));
}
}

0 comments on commit 7f421f0

Please sign in to comment.