@tokamakdev/platform-android-arm64 0.1.1-beta.127 → 0.1.1-beta.129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,355 @@
1
+ package com.tokamak.runtime
2
+
3
+ import kotlin.reflect.KClass
4
+ import kotlin.reflect.KType
5
+ import kotlin.reflect.full.findAnnotation
6
+ import kotlin.reflect.full.starProjectedType
7
+ import kotlin.reflect.full.withNullability
8
+ import org.json.JSONArray
9
+ import org.json.JSONObject
10
+
11
+ /**
12
+ * The Kotlin dispatch of [plugin]'s [exports] and [events]: the `<Plugin>Dispatch` class the app's
13
+ * registry creates, with a decoder and an encoder of each data class and sealed type they use.
14
+ */
15
+ internal fun dispatch(plugin: KClass<*>, exports: List<Export>, events: List<Event>): String {
16
+ val code = Code(plugin.java.packageName)
17
+ val takesBody = { export: Export -> export.parameters.lastOrNull()?.type?.classifier == TokamakPluginBody::class }
18
+ val calls = exports.filter { it.kind == "call" }
19
+ val requests = listOf(
20
+ code.function(
21
+ "override fun callBytes(method: String, payload: ByteArray, reply: TokamakPluginBytesReply): (() -> Unit)? {",
22
+ calls.filterNot(takesBody),
23
+ "is not supported",
24
+ ),
25
+ code.function(
26
+ "override fun callBytes(method: String, payload: ByteArray, body: TokamakPluginBody, reply: TokamakPluginBytesReply): (() -> Unit)? {",
27
+ calls.filter(takesBody),
28
+ "does not take a body",
29
+ ),
30
+ code.function(
31
+ "override fun subscribeBytes(method: String, payload: ByteArray, reply: TokamakPluginBytesReply): () -> Unit {",
32
+ exports.filter { it.kind != "call" },
33
+ "is not supported",
34
+ ),
35
+ code.events(events),
36
+ code.replies(events),
37
+ )
38
+ val results = exports.filter { it.kind != "resource" }.map { if (it.kind == "stream") it.returns.arguments.single().type!! else it.returns }
39
+ val parameters = exports.flatMap { export -> export.parameters.map { it.type } }
40
+ val classes = jsonClasses(parameters + results + events.flatMap { listOfNotNull(it.type, it.reply) })
41
+ val functions = (requests + code.values(classes)).filter { it.isNotEmpty() }
42
+ val name = code.name(plugin)
43
+ // Conversions are members, so the file declares only the class, whose name is the plugin's.
44
+ val conversions = classes.sortedBy { it.simpleName }
45
+ .flatMap { type -> code.decoder(type) + code.encoder(type) }
46
+ .map { if (it.isEmpty()) it else " $it" }
47
+ val emits = if (events.isEmpty()) "" else ", and encodes the events it emits"
48
+ val dispatch = listOf(
49
+ "/** Routes the Worker's requests to the methods [$name] exports$emits. */",
50
+ "class ${name}Dispatch(host: TokamakHost) : TokamakDispatch<$name>($name(host), host) {",
51
+ ) + functions.flatMap { listOf("") + it }.drop(1) + conversions + "}"
52
+ val header = listOf("// Generated by `tok plugin generate android`. Do not edit.", "package ${code.packageName}", "")
53
+ return (header + code.imports() + "" + dispatch).joinToString("\n") + "\n"
54
+ }
55
+
56
+ /** Kotlin generated in [packageName], and the imports it uses. */
57
+ private class Code(val packageName: String) {
58
+ private val imports = sortedSetOf(
59
+ "com.tokamak.runtime.TokamakDispatch",
60
+ "com.tokamak.runtime.TokamakHost",
61
+ "com.tokamak.runtime.TokamakPluginBytesReply",
62
+ "com.tokamak.runtime.TokamakPluginError",
63
+ )
64
+
65
+ fun imports(): List<String> = imports.map { "import $it" }
66
+
67
+ /** [type]'s name in the generated code: without its package in Kotlin's or the plugin's. */
68
+ fun name(type: KClass<*>): String {
69
+ val qualified = type.qualifiedName ?: throw DescribeError("$type has no name")
70
+ return when {
71
+ qualified.startsWith("kotlin.") -> qualified.substringAfterLast('.')
72
+ type.java.packageName == packageName -> qualified.removePrefix("$packageName.")
73
+ else -> qualified
74
+ }
75
+ }
76
+
77
+ /** A request function that switches on the method, or nothing without methods. */
78
+ fun function(signature: String, exports: List<Export>, unsupported: String): List<String> {
79
+ if (exports.isEmpty()) return emptyList()
80
+ if ("TokamakPluginBody" in signature) imports += "com.tokamak.runtime.TokamakPluginBody"
81
+ val decodes = exports.any { export -> export.parameters.any { it.type.classifier !in RAW } }
82
+ // Only the request's serial executor reads the arguments.
83
+ val arguments = if (decodes) listOf(" val arguments by lazy(LazyThreadSafetyMode.NONE) { TokamakValue.arguments(payload) }") else emptyList()
84
+ if (decodes) imports += "com.tokamak.runtime.TokamakValue"
85
+ return listOf(" $signature") + arguments + " return when (method) {" +
86
+ exports.flatMap { branch(it) }.map { " $it" } +
87
+ " else -> throw TokamakPluginError.notSupported(\"\$id.\$method $unsupported\")" +
88
+ " }" + " }"
89
+ }
90
+
91
+ /** The encoding of the events' payloads, or nothing without events. */
92
+ fun events(events: List<Event>): List<String> {
93
+ if (events.isEmpty()) return emptyList()
94
+ val branches = events.map { event ->
95
+ val type = event.type.classifier as KClass<*>
96
+ "\"${event.name}\" -> encodeEvent(name, event, ${name(type)}::class) { ${encode(event.type, "it")} }"
97
+ }
98
+ return switch("override fun eventPayload(name: String, event: Any): ByteArray =", branches, "super.eventPayload(name, event)")
99
+ }
100
+
101
+ /** The decoding of the events' replies, or nothing when no event takes one. */
102
+ fun replies(events: List<Event>): List<String> {
103
+ val branches = events.mapNotNull { event -> event.reply?.let { "\"${event.name}\" -> ${decode(it, "reply")}" } }
104
+ if (branches.isEmpty()) return emptyList()
105
+ imports += "com.tokamak.runtime.TokamakValue"
106
+ return switch("override fun eventReply(name: String, reply: TokamakValue): Any =", branches, "super.eventReply(name, reply)")
107
+ }
108
+
109
+ /**
110
+ * The conversions of the [classes] to and from JSON, which `host.json` and `host.fromJson`
111
+ * call. A sealed type's data class form encodes as the sealed type does, with its tag.
112
+ */
113
+ fun values(classes: Set<KClass<*>>): List<List<String>> {
114
+ if (classes.isEmpty()) return emptyList()
115
+ imports += listOf("com.tokamak.runtime.TokamakValue", "kotlin.reflect.KClass")
116
+ val sorted = classes.sortedBy { it.simpleName }
117
+ val forms = classes.filter { it.isSealed }.flatMap { forms(it).map(Form::type) }.toSet()
118
+ val encodes = sorted.filter { it !in forms }.map { "is ${name(it)} -> json(value)" }
119
+ return listOf(
120
+ switch("override fun encodeValue(value: Any): Any =", "value", encodes, "super.encodeValue(value)"),
121
+ switch("override fun decodeValue(json: TokamakValue, type: KClass<*>): Any =", "type", sorted.map { "${name(it)}::class -> json.as${it.simpleName}()" }, "super.decodeValue(json, type)"),
122
+ )
123
+ }
124
+
125
+ /** A function whose body switches on the event's name, leaving others to [otherwise]. */
126
+ private fun switch(signature: String, branches: List<String>, otherwise: String): List<String> = switch(signature, "name", branches, otherwise)
127
+
128
+ private fun switch(signature: String, subject: String, branches: List<String>, otherwise: String): List<String> =
129
+ listOf(" $signature", " when ($subject) {") + branches.map { " $it" } +
130
+ " else -> $otherwise" + " }"
131
+
132
+ /** Calls the export with its decoded arguments, and replies. */
133
+ private fun branch(export: Export): List<String> {
134
+ val label = "\"${export.name}\" ->"
135
+ val call = call(export)
136
+ return when {
137
+ export.kind == "call" -> {
138
+ val start = if (export.suspends) "launch(method, reply)" else "respond(reply)"
139
+ lambda(label, start, call) { encode(export.returns, it) }
140
+ }
141
+ export.kind == "stream" -> {
142
+ val encoded = encode(export.returns.arguments.single().type!!, "it")
143
+ val each = if (encoded == "it") "" else " { $encoded }"
144
+ use(label, call) { "collect(method, reply, $it)$each" }
145
+ }
146
+ export.suspends -> lambda(label, "retain(method, reply)", call) { it }
147
+ else -> use(label, call) { "retain(reply, $it)" }
148
+ }
149
+ }
150
+
151
+ /** `start { call }`, replying with the call's result as [encode] encodes it. */
152
+ private fun lambda(label: String, start: String, call: List<String>, encode: (String) -> String): List<String> =
153
+ when {
154
+ call.size == 1 -> listOf("$label $start { ${encode(call.single())} }")
155
+ encode("result") == "result" -> listOf("$label $start {") + call.map { " $it" } + "}"
156
+ else -> listOf("$label $start {", " val result = ${call.first()}") + call.drop(1).map { " $it" } + " ${encode("result")}" + "}"
157
+ }
158
+
159
+ /** What [use] makes of the call's result, called on the request's executor. */
160
+ private fun use(label: String, call: List<String>, use: (String) -> String): List<String> =
161
+ if (call.size == 1) {
162
+ listOf("$label ${use(call.single())}")
163
+ } else {
164
+ listOf("$label {", " val result = ${call.first()}") + call.drop(1).map { " $it" } + " ${use("result")}" + "}"
165
+ }
166
+
167
+ /** The plugin method's call: on one line when it is short, and otherwise one argument per line. */
168
+ private fun call(export: Export): List<String> {
169
+ val arguments = export.parameters.map { parameter ->
170
+ val value = when (parameter.type.classifier) {
171
+ TokamakPluginBody::class -> "body"
172
+ ByteArray::class -> "payload"
173
+ else -> decode(parameter.type, "arguments[\"${parameter.name}\"]")
174
+ }
175
+ "${parameter.name} = $value"
176
+ }
177
+ val line = "plugin.${export.name}(${arguments.joinToString()})"
178
+ return if (line.length <= 60) listOf(line) else listOf("plugin.${export.name}(") + arguments.map { " $it," } + ")"
179
+ }
180
+
181
+ /** Reads [type] from the JSON value [value]. */
182
+ fun decode(type: KType, value: String): String {
183
+ if (type.isMarkedNullable) return "$value.nullable { ${decode(type.withNullability(false), "it")} }"
184
+ val classifier = type.classifier as KClass<*>
185
+ val argument = { index: Int -> type.arguments[index].type!! }
186
+ return when (classifier) {
187
+ String::class -> "$value.string()"
188
+ Boolean::class -> "$value.boolean()"
189
+ Int::class -> "$value.int()"
190
+ Long::class -> "$value.long()"
191
+ Short::class -> "$value.short()"
192
+ Byte::class -> "$value.byte()"
193
+ Double::class -> "$value.double()"
194
+ Float::class -> "$value.float()"
195
+ Any::class -> "$value.any()"
196
+ JSONObject::class -> "$value.jsonObject()"
197
+ JSONArray::class -> "$value.jsonArray()"
198
+ List::class -> "$value.list { ${decode(argument(0), "it")} }"
199
+ Map::class -> "$value.map { ${decode(argument(1), "it")} }"
200
+ TokamakReference::class -> "$value.reference(host.resources, ${name(argument(0).classifier as KClass<*>)}::class.java)"
201
+ else -> if (classifier.java.isEnum) "$value.enum(${name(classifier)}.entries)" else "$value.as${classifier.simpleName}()"
202
+ }
203
+ }
204
+
205
+ /** [value] of [type] as JSON: itself when it is a string, boolean, number, bytes or nothing. */
206
+ fun encode(type: KType, value: String): String {
207
+ if (type.classifier in SCALARS) return value
208
+ val classifier = type.classifier as KClass<*>
209
+ if (type.isMarkedNullable) {
210
+ return if (classifier.java.isEnum) "$value?.name" else "$value?.let { ${encode(type.withNullability(false), "it")} }"
211
+ }
212
+ return when {
213
+ classifier == List::class -> {
214
+ imports += "org.json.JSONArray"
215
+ val element = encode(type.arguments[0].type!!, "it")
216
+ if (element == "it") "JSONArray($value)" else "JSONArray($value.map { $element })"
217
+ }
218
+ classifier == Map::class -> {
219
+ imports += "org.json.JSONObject"
220
+ val entry = encode(type.arguments[1].type!!, "it.value")
221
+ if (entry == "it.value") "JSONObject($value)" else "JSONObject($value.mapValues { $entry })"
222
+ }
223
+ classifier.java.isEnum -> "$value.name"
224
+ else -> "json($value)"
225
+ }
226
+ }
227
+
228
+ /** The decoder of the data class or sealed type [type]. */
229
+ fun decoder(type: KClass<*>): List<String> {
230
+ val name = name(type)
231
+ if (type.isSealed) return formDecoder(type)
232
+ return listOf("", "private fun TokamakValue.as${type.simpleName}(): $name =", " $name(") +
233
+ fields(type).map { " ${it.name} = ${decode(it.type, "this[\"${it.name}\"]")}," } + " )"
234
+ }
235
+
236
+ /** The encoder of the data class or sealed type [type]. */
237
+ fun encoder(type: KClass<*>): List<String> {
238
+ if (type.isSealed) return formEncoder(type)
239
+ imports += "org.json.JSONObject"
240
+ return listOf("", "private fun json(value: ${name(type)}): JSONObject =", " JSONObject()") +
241
+ fields(type).map { field ->
242
+ val put = if (field.type.isMarkedNullable) "putOpt" else "put"
243
+ " .$put(\"${field.name}\", ${encode(field.type, "value.${field.name}")})"
244
+ }
245
+ }
246
+
247
+ /**
248
+ * The decoder of the sealed type [type], which chooses a form by the value's tag, or else by its
249
+ * JSON: its kind, a string's value, and a key only one data class form's objects have.
250
+ */
251
+ private fun formDecoder(type: KClass<*>): List<String> {
252
+ val forms = forms(type)
253
+ val tag = type.findAnnotation<TokamakTag>()?.field
254
+ val objects = forms.filter { !it.isName && it.value == null }
255
+ val branches = forms.map { form ->
256
+ val value = form.value
257
+ val decoded = when {
258
+ form.isName -> name(form.type)
259
+ value != null -> "${name(form.type)}(${decode(value.type, "this")})"
260
+ else -> "as${form.type.simpleName}()"
261
+ }
262
+ val condition = when {
263
+ tag != null -> "\"${form.name}\""
264
+ form.isName -> "json == \"${form.name}\""
265
+ value != null -> kind(value.type)
266
+ objects.size > 1 -> "${isObject()} && json.has(\"${key(form, objects)}\")"
267
+ else -> isObject()
268
+ }
269
+ "$condition -> $decoded"
270
+ }
271
+ val signature = "private fun TokamakValue.as${type.simpleName}(): ${name(type)}"
272
+ val mismatch = "else -> throw mismatch(\"${type.simpleName}\")"
273
+ if (tag != null) {
274
+ return listOf("", "$signature =", " when (this[\"$tag\"].string()) {") + branches.map { " $it" } + " $mismatch" + " }"
275
+ }
276
+ return listOf("", "$signature {", " val json = json()", " return when {") + branches.map { " $it" } + " $mismatch" + " }" + "}"
277
+ }
278
+
279
+ /** The condition that the JSON `json` is an object. */
280
+ private fun isObject(): String {
281
+ imports += "org.json.JSONObject"
282
+ return "json is JSONObject"
283
+ }
284
+
285
+ /** The condition that the JSON `json` is a value class form's value of [type]. */
286
+ private fun kind(type: KType): String {
287
+ val classifier = type.classifier as KClass<*>
288
+ return when {
289
+ classifier == String::class -> "json is String"
290
+ classifier == Boolean::class -> "json is Boolean"
291
+ classifier in NUMBERS -> "json is Number"
292
+ classifier.java.isEnum -> {
293
+ val values = classifier.java.enumConstants.joinToString { "\"${(it as Enum<*>).name}\"" }
294
+ "json is String && json in setOf($values)"
295
+ }
296
+ classifier == List::class || classifier == JSONArray::class -> {
297
+ imports += "org.json.JSONArray"
298
+ "json is JSONArray"
299
+ }
300
+ // A map or JSONObject: a value class holds no data class, which is a form itself.
301
+ else -> isObject()
302
+ }
303
+ }
304
+
305
+ /** The encoder of the sealed type [type]: each form's name, value, or data class, with its tag. */
306
+ private fun formEncoder(type: KClass<*>): List<String> {
307
+ val tag = type.findAnnotation<TokamakTag>()?.field
308
+ if (tag != null) imports += "org.json.JSONObject"
309
+ val tagged = { form: Form -> tag?.let { ".put(\"$it\", \"${form.name}\")" } ?: "" }
310
+ val branches = forms(type).map { form ->
311
+ val value = form.value
312
+ when {
313
+ form.isName && tag != null -> "${name(form.type)} -> JSONObject()${tagged(form)}"
314
+ form.isName -> "${name(form.type)} -> \"${form.name}\""
315
+ value != null -> "is ${name(form.type)} -> ${encode(value.type, "value.${value.name}")}"
316
+ else -> "is ${name(form.type)} -> json(value)${tagged(form)}"
317
+ }
318
+ }
319
+ val returns = if (tag != null) "JSONObject" else "Any"
320
+ return listOf("", "private fun json(value: ${name(type)}): $returns =", " when (value) {") + branches.map { " $it" } + " }"
321
+ }
322
+ }
323
+
324
+ /** The first required field of the data class [form] that none of the other [objects] has. */
325
+ private fun key(form: Form, objects: List<Form>): String {
326
+ val others = objects.filter { it != form }.flatMap { fields(it.type) }.map { it.name }.toSet()
327
+ return fields(form.type).firstOrNull { !it.type.isMarkedNullable && it.name !in others }?.name.orEmpty()
328
+ }
329
+
330
+ /** The data classes and sealed types [types] use, directly, through fields, or as forms, which convert to and from JSON. */
331
+ private fun jsonClasses(types: List<KType>): Set<KClass<*>> {
332
+ val found = mutableSetOf<KClass<*>>()
333
+ fun visit(type: KType) {
334
+ type.arguments.forEach { argument -> argument.type?.let(::visit) }
335
+ val classifier = type.classifier as? KClass<*> ?: return
336
+ if (classifier.isSealed && found.add(classifier)) {
337
+ for (form in forms(classifier)) visit(form.value?.type ?: form.type.starProjectedType)
338
+ }
339
+ if (classifier.isData && classifier.objectInstance == null && found.add(classifier)) fields(classifier).forEach { visit(it.type) }
340
+ }
341
+ types.forEach(::visit)
342
+ return found
343
+ }
344
+
345
+ /** Parameters the request carries apart from its JSON arguments. */
346
+ private val RAW = setOf(TokamakPluginBody::class, ByteArray::class)
347
+
348
+ /** Kotlin's numeric types, which are JSON numbers. */
349
+ private val NUMBERS = setOf(Int::class, Long::class, Short::class, Byte::class, Double::class, Float::class)
350
+
351
+ /** The types whose values are JSON, or bytes, as they are. */
352
+ private val SCALARS = setOf(
353
+ String::class, Boolean::class, Int::class, Long::class, Short::class, Byte::class, Double::class, Float::class, Unit::class, ByteArray::class,
354
+ Any::class, JSONObject::class, JSONArray::class,
355
+ )
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/android-arm64/lib/TokamakRuntime/libtokamak.a
3
- size: 35458546 bytes
4
- sha256: 1cf17a7e8886ad2d0dfac148fec4194bb35fe874ddbc044fc8be8e9496467880
3
+ size: 35458610 bytes
4
+ sha256: 72638789b6a8c0191de333e13157fc4cf302854384d97011f5d724d5ed8d211e
@@ -12,6 +12,7 @@ import androidx.lifecycle.LifecycleOwner
12
12
  import androidx.lifecycle.ProcessLifecycleOwner
13
13
  import java.io.File
14
14
  import java.util.concurrent.Executors
15
+ import kotlin.reflect.KClass
15
16
 
16
17
  private const val HOST_METADATA = "tokamak.host"
17
18
  private const val DEV_ENDPOINT_METADATA = "tokamak.dev.endpoint"
@@ -89,9 +90,9 @@ class TokamakApplication : Application(), TokamakPlugins {
89
90
  )
90
91
  }
91
92
 
92
- override fun plugin(id: String): TokamakPlugin? = plugins[id]
93
+ override fun plugin(id: String): TokamakPlugin? = plugins[id].let { (it as? TokamakDispatch<*>)?.plugin ?: it }
93
94
 
94
- /** The host the plugin [id] sees, whose events the Worker's listeners receive as `<id>.<name>`. */
95
+ /** The host the plugin [id] sees, whose events the Worker's listeners receive as `<id>.android.<name>`. */
95
96
  internal fun host(id: String): TokamakHost =
96
97
  object : TokamakHost {
97
98
  override val context: Context
@@ -118,7 +119,24 @@ class TokamakApplication : Application(), TokamakPlugins {
118
119
  ) = permissionRequests.request(permissions, callback)
119
120
 
120
121
  override fun emitBytes(name: String, payload: ByteArray, timeoutMillis: Long): ByteArray =
121
- emitEvent("$id.$name", payload, timeoutMillis)
122
+ emitEvent("$id.android.$name", payload, timeoutMillis)
123
+
124
+ override fun emit(name: String, event: Any, timeoutMillis: Long) {
125
+ dispatch { TokamakPluginError.unlistedEvent(name) }.emit(name, event, timeoutMillis)
126
+ }
127
+
128
+ override fun <R : Any> emit(name: String, event: Any, reply: KClass<R>, timeoutMillis: Long): R? =
129
+ dispatch { TokamakPluginError.unlistedEvent(name) }.emit(name, event, reply, timeoutMillis)
130
+
131
+ override fun json(value: Any): Any = dispatch(::unregistered).encodeValue(value)
132
+
133
+ override fun <T : Any> fromJson(json: Any?, type: KClass<T>): T = dispatch(::unregistered).fromJson(json, type)
134
+
135
+ /** The plugin's generated dispatch, or else the error [missing] gives. */
136
+ private fun dispatch(missing: () -> TokamakPluginError): TokamakDispatch<*> =
137
+ plugins[id] as? TokamakDispatch<*> ?: throw missing()
138
+
139
+ private fun unregistered() = TokamakPluginError.typeError("$id has no android/Exports.kt")
122
140
 
123
141
  override fun fetch(path: String, timeoutMillis: Long): ByteArray {
124
142
  val deadline = SystemClock.elapsedRealtime() + timeoutMillis
@@ -11,19 +11,14 @@ internal class TokamakCorePlugin(private val app: TokamakApplication) : TokamakP
11
11
  override val id = "tokamak"
12
12
  private val executor = Executors.newSingleThreadExecutor()
13
13
 
14
- /** WebView operations and the activity run on the main thread, which WebView and activities require. */
14
+ /** WebView operations run on the main thread, which WebView requires. */
15
15
  override fun executor(method: String): Executor =
16
- if (method.startsWith("webview.") || method == "resource.root") super.executor(method) else executor
16
+ if (method.startsWith("webview.")) super.executor(method) else executor
17
17
 
18
18
  override fun call(method: String, arguments: Any?, reply: TokamakPluginReply): (() -> Unit)? {
19
19
  val view = (app.activity as? TokamakActivity)?.webView
20
20
  when (method) {
21
21
  "resource.read" -> reply(Result.success(app.resources.get(arguments, ByteArray::class.java)))
22
- "resource.release" -> {
23
- app.resources.release(arguments)
24
- reply(Result.success(null))
25
- }
26
- "resource.root" -> reply(Result.success(root(arguments as JSONObject)))
27
22
  "webview.getCurrentPage" -> reply(Result.success(view?.url))
28
23
  "webview.navigate" -> {
29
24
  if (view == null) throw noView()
@@ -49,24 +44,6 @@ internal class TokamakCorePlugin(private val app: TokamakApplication) : TokamakP
49
44
  return null
50
45
  }
51
46
 
52
- /** `resource.scope` opens a scope for the objects an invocation receives, which ends with the subscription. */
53
- override fun subscribe(method: String, arguments: Any?, reply: TokamakPluginReply): () -> Unit {
54
- if (method != "resource.scope") throw TokamakPluginError.notSupported("$id.$method is not supported")
55
- val scope = app.resources.open()
56
- reply(Result.success(scope))
57
- return { app.resources.end(scope) }
58
- }
59
-
60
- /** Retains the app object [arguments] names in its scope and returns its ID: the application `context` or the foreground `activity`. */
61
- private fun root(arguments: JSONObject): String {
62
- val root: Any = when (arguments.getString("name")) {
63
- "context" -> app
64
- "activity" -> app.requireForegroundActivity()
65
- else -> throw TokamakPluginError.notSupported("$id.resource.root has no such object")
66
- }
67
- return app.resources.retain(root, arguments.getString("scope"))
68
- }
69
-
70
47
  private fun noView() = TokamakPluginError("InvalidStateError", "The app has no WebView")
71
48
 
72
49
  private fun notAppUrl() = TokamakPluginError.typeError("Navigation requires an app URL")