Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package com.shopify.checkoutkit.androiddemo.e2e

import java.net.URI
import java.net.URISyntaxException
import java.net.URLDecoder

enum class E2EBuyerIdentityMode(val parameterValue: String) {
GUEST("guest"),
HARDCODED("hardcoded"),
CUSTOMER_ACCOUNT("customerAccount"),
;

companion object {
fun from(parameterValue: String) = entries.firstOrNull { it.parameterValue == parameterValue }
}
}

sealed interface E2EControlLink {
data object Reset : E2EControlLink

data class Cart(
val variantId: String? = null,
val productIndex: Int? = null,
val quantity: Int = 1,
val buyerIdentityMode: E2EBuyerIdentityMode? = null,
) : E2EControlLink

data class SignIn(val email: String? = null) : E2EControlLink

companion object {
const val HOST = "e2e"

private const val SCHEME_SEPARATOR = "://"
private const val PARSE_ORIGIN_SCHEME = "https://"

private val RESET_PARAMETERS = emptySet<String>()
private val CART_PARAMETERS = setOf("variantId", "productIndex", "quantity", "buyerIdentityMode")
private val SIGN_IN_PARAMETERS = setOf("email")

fun parse(url: String): E2EControlLink? {
val separatorIndex = url.indexOf(SCHEME_SEPARATOR)

if (separatorIndex < 0) {
return null
}

val authorityAndPath = url.substring(separatorIndex + SCHEME_SEPARATOR.length)
val uri = try {
URI(PARSE_ORIGIN_SCHEME + authorityAndPath)
} catch (error: URISyntaxException) {
return null

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we reserve null for non-E2E links and throw for malformed E2E URLs instead? Might be stricter than we need today, but it would keep those cases distinct if we need clearer control-link diagnostics later.

If we do want that distinction, it’s probably worth keeping the Android, Swift, and React Native parsers aligned.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'll leave it to later if the time comes we need that

}

if (uri.host != HOST) {
return null
}

val parameters = parameters(uri.rawQuery)

return when (uri.path.orEmpty().trim('/')) {
"reset" -> {
rejectUnknownParameters("reset", parameters, RESET_PARAMETERS)

Reset
}

"cart" -> {
rejectUnknownParameters("cart", parameters, CART_PARAMETERS)

cart(parameters)
}

"signIn" -> {
rejectUnknownParameters("signIn", parameters, SIGN_IN_PARAMETERS)

SignIn(email = signInEmail(parameters))
}

else -> throw IllegalArgumentException("Unsupported e2e command")
}
}

private fun rejectUnknownParameters(
command: String,
parameters: Map<String, String>,
allowed: Set<String>,
) {
val unknown = parameters.keys.filterNot { allowed.contains(it) }.sorted()

require(unknown.isEmpty()) { "Unknown $command parameters: ${unknown.joinToString(", ")}" }
}

private fun cart(parameters: Map<String, String>): Cart {
require(parameters.isNotEmpty()) { "Missing variantId or productIndex" }

val quantity = quantity(parameters)
val buyerIdentityMode = buyerIdentityMode(parameters)
val variantId = parameters["variantId"]
val productIndexParameter = parameters["productIndex"]

require(variantId == null || productIndexParameter == null) {
"Use variantId or productIndex, not both"
}

if (variantId != null) {
require(variantId.isNotEmpty()) { "variantId must not be blank" }

return Cart(variantId = variantId, quantity = quantity, buyerIdentityMode = buyerIdentityMode)
}

requireNotNull(productIndexParameter) { "Missing variantId or productIndex" }

val productIndex = productIndexParameter.toIntOrNull()

require(productIndex != null && productIndex >= 0) { "productIndex must be a non-negative integer" }

return Cart(productIndex = productIndex, quantity = quantity, buyerIdentityMode = buyerIdentityMode)
}

private fun quantity(parameters: Map<String, String>): Int {
val parameter = parameters["quantity"] ?: return 1
val quantity = parameter.toIntOrNull()

require(quantity != null && quantity >= 1) { "quantity must be a positive integer" }

return quantity
}

private fun buyerIdentityMode(parameters: Map<String, String>): E2EBuyerIdentityMode? {
val parameter = parameters["buyerIdentityMode"] ?: return null

return requireNotNull(E2EBuyerIdentityMode.from(parameter)) {
"buyerIdentityMode must be guest, hardcoded, or customerAccount"
}
}

private fun signInEmail(parameters: Map<String, String>): String? {
val email = parameters["email"] ?: return null

require(email.isNotEmpty()) { "email must not be blank" }

return email
}

private fun parameters(rawQuery: String?): Map<String, String> {
if (rawQuery.isNullOrEmpty()) {
return emptyMap()
}

return rawQuery
.split("&")
.filter { it.isNotEmpty() }
.associate { pair ->
val separatorIndex = pair.indexOf('=')

if (separatorIndex < 0) {
decode(pair) to ""
} else {
decode(pair.substring(0, separatorIndex)) to decode(pair.substring(separatorIndex + 1))
}
}
}

private fun decode(value: String) = URLDecoder.decode(value, "UTF-8").trim()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package com.shopify.checkoutkit.androiddemo.e2e

import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test

class E2EControlLinkTest {
private val rejectedNumbers =
listOf("", "1.5", "abc", "1e3", "0x10", "0b11", "0o17", "2147483648", "99999999999999999999")

@Test
fun `returns null when the link is not a control link`() {
assertThat(E2EControlLink.parse("https://example.com/cart")).isNull()
assertThat(E2EControlLink.parse("com.shopify.checkoutkit.androiddemo://products/1")).isNull()
assertThat(E2EControlLink.parse("not a url")).isNull()
}

@Test
fun `parses every app scheme`() {
val expected = E2EControlLink.Cart(productIndex = 0)

assertThat(E2EControlLink.parse("com.shopify.checkoutkit.androiddemo://e2e/cart?productIndex=0")).isEqualTo(expected)
assertThat(E2EControlLink.parse("com.shopify.checkoutkit.swiftdemo://e2e/cart?productIndex=0")).isEqualTo(expected)
}

@Test
fun `parses the reset command`() {
assertThat(parse("/reset")).isEqualTo(E2EControlLink.Reset)
}

@Test
fun `rejects unknown parameters`() {
assertRejects("/reset?productIndex=0", "Unknown reset parameters: productIndex")
assertRejects("/cart?productIndex=0&quantitiy=5", "Unknown cart parameters: quantitiy")
assertRejects("/cart?productIndx=0", "Unknown cart parameters: productIndx")
assertRejects("/cart?productIndex=0&foo=1&bar=2", "Unknown cart parameters: bar, foo")
assertRejects("/signIn?emial=shopper@example.com", "Unknown signIn parameters: emial")
}

@Test
fun `rejects unknown commands`() {
assertRejects("", "Unsupported e2e command")
assertRejects("/", "Unsupported e2e command")
assertRejects("/teleport?productIndex=0", "Unsupported e2e command")
assertRejects("/cart/extra?productIndex=0", "Unsupported e2e command")
}

@Test
fun `rejects cart commands without a product selector`() {
assertRejects("/cart", "Missing variantId or productIndex")
assertRejects("/cart?", "Missing variantId or productIndex")
assertRejects("/cart?quantity=2", "Missing variantId or productIndex")
}

@Test
fun `rejects cart commands with both product selectors`() {
assertRejects(
"/cart?variantId=gid://shopify/ProductVariant/1&productIndex=0",
"Use variantId or productIndex, not both",
)
}

@Test
fun `rejects a blank variant id`() {
assertRejects("/cart?variantId=", "variantId must not be blank")
assertRejects("/cart?variantId=%20", "variantId must not be blank")
assertRejects("/cart?variantId=%0A", "variantId must not be blank")
}

@Test
fun `rejects invalid quantities`() {
(rejectedNumbers + listOf("0", "-1")).forEach { quantity ->
assertRejects("/cart?productIndex=0&quantity=$quantity", "quantity must be a positive integer")
}
}

@Test
fun `rejects invalid product indexes`() {
(rejectedNumbers + "-1").forEach { productIndex ->
assertRejects("/cart?productIndex=$productIndex", "productIndex must be a non-negative integer")
}
}

@Test
fun `rejects invalid buyer identity modes`() {
listOf("", "member").forEach { buyerIdentityMode ->
assertRejects(
"/cart?productIndex=0&buyerIdentityMode=$buyerIdentityMode",
"buyerIdentityMode must be guest, hardcoded, or customerAccount",
)
}
}

@Test
fun `parses a cart command with a variant id`() {
val link = parse("/cart?variantId=gid://shopify/ProductVariant/1&quantity=2&buyerIdentityMode=guest")

assertThat(link).isEqualTo(
E2EControlLink.Cart(
variantId = "gid://shopify/ProductVariant/1",
quantity = 2,
buyerIdentityMode = E2EBuyerIdentityMode.GUEST,
),
)
}

@Test
fun `parses a cart command with a product index and the default quantity`() {
val link = parse("/cart?productIndex=3&buyerIdentityMode=hardcoded")

assertThat(link).isEqualTo(
E2EControlLink.Cart(productIndex = 3, quantity = 1, buyerIdentityMode = E2EBuyerIdentityMode.HARDCODED),
)
}

@Test
fun `parses a cart command with a trailing slash`() {
assertThat(parse("/cart/?productIndex=3")).isEqualTo(E2EControlLink.Cart(productIndex = 3))
}

@Test
fun `parses a sign in command without an email`() {
assertThat(parse("/signIn")).isEqualTo(E2EControlLink.SignIn())
}

@Test
fun `parses a sign in command with an email`() {
assertThat(parse("/signIn?email=shopper%2Be2e@example.com"))
.isEqualTo(E2EControlLink.SignIn(email = "shopper+e2e@example.com"))
}

@Test
fun `decodes a literal plus in a query value as a space`() {
assertThat(parse("/signIn?email=shopper+e2e@example.com"))
.isEqualTo(E2EControlLink.SignIn(email = "shopper e2e@example.com"))
}

@Test
fun `rejects a blank sign in email`() {
assertRejects("/signIn?email=", "email must not be blank")
assertRejects("/signIn?email=%20", "email must not be blank")
assertRejects("/signIn?email=%0A", "email must not be blank")
}

private fun parse(path: String) = E2EControlLink.parse("com.shopify.checkoutkit.androiddemo://e2e$path")

private fun assertRejects(path: String, message: String) {
assertThatThrownBy { parse(path) }
.describedAs(path)
.isInstanceOf(IllegalArgumentException::class.java)
.hasMessage(message)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data android:scheme="com.shopify.checkoutkit.reactnativedemo" android:host="cart" />
<!-- E2E control link. Sample apps only; not part of the merchant integration. -->
<data android:scheme="com.shopify.checkoutkit.reactnativedemo" android:host="e2e" />
</intent-filter>
</activity>
</application>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {readFileSync} from 'fs';
import {join} from 'path';
import {CONTROL_LINK_HOST} from '../controlLink';

const APP_SCHEME = 'com.shopify.checkoutkit.reactnativedemo';
const TEMPLATE_PATH = join(
__dirname,
'../../../android/app/src/main/AndroidManifest.template.xml',
);

describe('AndroidManifest.template.xml', () => {
it('registers the control link host that the parser accepts', () => {
const template = readFileSync(TEMPLATE_PATH, 'utf8');
const filter = new RegExp(
`<data android:scheme="${APP_SCHEME}" android:host="([^"]+)" />`,
);

expect(template.match(filter)?.[1]).toBe(CONTROL_LINK_HOST);
});
});
Loading
Loading