@tokamakdev/platform-android-arm64 0.1.1-beta.128 → 0.1.1-beta.130

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.
@@ -1,13 +1,130 @@
1
1
  #!/usr/bin/env bash
2
2
  set -euo pipefail
3
3
 
4
+ # The CLI runs the entrypoint from the pack root.
5
+ pack=$PWD
6
+
7
+ # The build tools of apps and of describing plugins. Coroutines are the version
8
+ # androidx.lifecycle brings, so plugins' coroutines add no code.
9
+ agp_version=8.7.3
10
+ kotlin_version=2.1.0
11
+ coroutines_version=1.9.0
12
+
13
+ # Describes the methods PLUGIN/android/Exports.kt exports into
14
+ # OUTPUT/description.json, with the dispatch that serves them,
15
+ # OUTPUT/Exports.generated.kt. A JVM unit test of the plugin, compiled with
16
+ # the plugin API and its dependencies, runs the registration and reflects on
17
+ # the methods it lists.
18
+ describe() {
19
+ local plugin=$1 output=$2
20
+ if [[ $# -ne 3 || $3 != android ]]; then
21
+ echo "Android plugins run on android, not ${*:3}" >&2
22
+ exit 2
23
+ fi
24
+ local sdk=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}
25
+ if ! command -v gradle > /dev/null || ! command -v java > /dev/null || [[ ! -d "$sdk/platforms" ]]; then
26
+ echo "Describing an Android plugin needs Gradle, Java and the Android SDK" >&2
27
+ exit 69
28
+ fi
29
+ # Global, for the exit trap.
30
+ temporary=$(mktemp -d "${TMPDIR:-/tmp}/tokamak-describe.XXXXXX")
31
+ trap 'rm -rf "$temporary"' EXIT
32
+ local module=$temporary/plugin
33
+ mkdir -p "$module"
34
+ cat > "$temporary/settings.gradle" <<'EOF'
35
+ pluginManagement {
36
+ repositories {
37
+ google()
38
+ mavenCentral()
39
+ gradlePluginPortal()
40
+ }
41
+ }
42
+ dependencyResolutionManagement {
43
+ repositories {
44
+ google()
45
+ mavenCentral()
46
+ }
47
+ }
48
+ rootProject.name = 'tokamak-describe'
49
+ include ':plugin'
50
+ EOF
51
+ cat > "$temporary/build.gradle" <<EOF
52
+ plugins {
53
+ id 'com.android.library' version '$agp_version' apply false
54
+ id 'org.jetbrains.kotlin.android' version '$kotlin_version' apply false
55
+ }
56
+ EOF
57
+ printf '%s\n' 'android.useAndroidX=true' > "$temporary/gradle.properties"
58
+ cat > "$module/build.gradle" <<EOF
59
+ plugins {
60
+ id 'com.android.library'
61
+ id 'org.jetbrains.kotlin.android'
62
+ }
63
+
64
+ android {
65
+ namespace 'tokamak.describe'
66
+ compileSdk 35
67
+ // The plugin's own files, so compiler errors name them.
68
+ sourceSets {
69
+ main.kotlin.srcDirs = ['$pack/native-shell/plugin', '$plugin/android']
70
+ test.kotlin.srcDirs = ['$pack/describer']
71
+ }
72
+ defaultConfig {
73
+ minSdk $(<"$pack/build/min-sdk")
74
+ }
75
+ compileOptions {
76
+ sourceCompatibility JavaVersion.VERSION_17
77
+ targetCompatibility JavaVersion.VERSION_17
78
+ }
79
+ testOptions {
80
+ unitTests.returnDefaultValues = true
81
+ unitTests.all {
82
+ systemProperty 'tokamak.output', '$output'
83
+ systemProperty 'tokamak.classes', layout.buildDirectory.dir('tmp/kotlin-classes/debug').get().asFile.path
84
+ outputs.upToDateWhen { false }
85
+ }
86
+ }
87
+ }
88
+
89
+ kotlin {
90
+ jvmToolchain(17)
91
+ compilerOptions {
92
+ freeCompilerArgs.add('-Xjvm-default=all')
93
+ }
94
+ }
95
+
96
+ // The dispatch describing regenerates.
97
+ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
98
+ exclude '**/Exports.generated.kt'
99
+ }
100
+
101
+ def manifest = new groovy.json.JsonSlurper().parse(file('$plugin/tokamak-plugin.json'))
102
+ dependencies {
103
+ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version'
104
+ (manifest.platforms?.android?.dependencies ?: []).each { implementation it }
105
+ testImplementation 'junit:junit:4.13.2'
106
+ testImplementation 'org.jetbrains.kotlin:kotlin-reflect:$kotlin_version'
107
+ // android.jar's org.json is stubs; the describer writes JSON with the reference implementation.
108
+ testImplementation 'org.json:json:20250517'
109
+ }
110
+ EOF
111
+ gradle --quiet --project-dir "$temporary" :plugin:testDebugUnitTest
112
+ if [[ -f "$output/error" ]]; then
113
+ cat "$output/error" >&2
114
+ rm "$output/error"
115
+ exit 1
116
+ fi
117
+ }
118
+ if [[ $# -ge 1 && $1 == describe ]]; then
119
+ describe "${@:2}"
120
+ exit
121
+ fi
122
+
4
123
  if [[ $# -ne 3 || $1 != build ]]; then
5
- echo "usage: entrypoint build INPUT OUTPUT" >&2
124
+ echo "usage: entrypoint build INPUT OUTPUT | entrypoint describe PLUGIN OUTPUT android" >&2
6
125
  exit 2
7
126
  fi
8
127
 
9
- # The CLI runs the entrypoint from the pack root.
10
- pack=$PWD
11
128
  input=$2
12
129
  output=$3
13
130
  metadata=$input/metadata
@@ -147,7 +264,7 @@ cp -R "$input/app/." "$assets/"
147
264
  link_runtime
148
265
  cp -R "$pack/native-shell/app/." "$kotlin/"
149
266
  cp -R "$pack/native-shell/plugin/." "$plugin_api/src/main/kotlin/"
150
- cat > "$plugin_api/build.gradle" <<'EOF'
267
+ cat > "$plugin_api/build.gradle" <<EOF
151
268
  plugins {
152
269
  id 'com.android.library'
153
270
  id 'org.jetbrains.kotlin.android'
@@ -156,6 +273,10 @@ plugins {
156
273
  android {
157
274
  namespace 'com.tokamak.runtime.plugin'
158
275
  }
276
+
277
+ dependencies {
278
+ api 'org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version'
279
+ }
159
280
  EOF
160
281
 
161
282
  has_icon=false
@@ -186,20 +307,20 @@ for plugin in "$input/plugins"/*/; do
186
307
  echo "plugin '$plugin_id' has invalid android class '$class'" >&2
187
308
  exit 1
188
309
  fi
310
+ # A plugin that exports methods runs behind the dispatch generated for it.
311
+ if [[ -f "$plugin/native/Exports.kt" ]]; then
312
+ class=${class}Dispatch
313
+ fi
189
314
  printf ' %s(app.host("%s")),\n' "$class" "$plugin_id" >> "$registry"
190
315
  module=$plugin_modules/$plugin_id
191
316
  mkdir -p "$module/src/main/kotlin"
192
- for source in "$plugin/sources"/*; do
193
- case "$source" in
194
- *.kt)
195
- cp "$source" "$module/src/main/kotlin/$(basename "$source")"
196
- ;;
197
- *)
198
- echo "Android plugin source must be Kotlin: $source" >&2
199
- exit 1
200
- ;;
201
- esac
202
- done
317
+ if [[ -d "$plugin/native" ]]; then
318
+ while IFS= read -r -d '' source; do
319
+ relative=${source#"$plugin/native/"}
320
+ mkdir -p "$module/src/main/kotlin/$(dirname "$relative")"
321
+ cp "$source" "$module/src/main/kotlin/$relative"
322
+ done < <(find "$plugin/native" -name '*.kt' -print0)
323
+ fi
203
324
  if [[ -f "$plugin/manifest" ]]; then
204
325
  cp "$plugin/manifest" "$module/src/main/AndroidManifest.xml"
205
326
  fi
@@ -261,9 +382,9 @@ done
261
382
 
262
383
  cat > "$project/build.gradle" <<EOF
263
384
  plugins {
264
- id 'com.android.application' version '8.7.3' apply false
265
- id 'com.android.library' version '8.7.3' apply false
266
- id 'org.jetbrains.kotlin.android' version '2.1.0' apply false
385
+ id 'com.android.application' version '$agp_version' apply false
386
+ id 'com.android.library' version '$agp_version' apply false
387
+ id 'org.jetbrains.kotlin.android' version '$kotlin_version' apply false
267
388
  }
268
389
 
269
390
  subprojects {
@@ -0,0 +1,221 @@
1
+ package com.tokamak.runtime
2
+
3
+ import java.io.File
4
+ import kotlin.reflect.KClass
5
+ import kotlin.reflect.KParameter
6
+ import kotlin.reflect.KType
7
+ import kotlin.reflect.full.allSupertypes
8
+ import kotlin.reflect.full.findAnnotation
9
+ import kotlin.reflect.full.primaryConstructor
10
+ import kotlin.reflect.full.starProjectedType
11
+ import kotlinx.coroutines.flow.Flow
12
+ import org.json.JSONArray
13
+ import org.json.JSONObject
14
+ import org.junit.Test
15
+
16
+ /** A failure to describe the plugin, which the message explains. */
17
+ class DescribeError(message: String) : Exception(message)
18
+
19
+ /**
20
+ * Runs the plugin's registration, which the compiled classes in `tokamak.classes` include, and
21
+ * describes the methods it exports and the events it emits into `tokamak.output`:
22
+ * `description.json`, and the dispatch that serves them, `Exports.generated.kt`. A failure's
23
+ * message goes to `error` there.
24
+ */
25
+ class Describe {
26
+ @Test
27
+ @Suppress("UNCHECKED_CAST")
28
+ fun describe() {
29
+ val output = File(System.getProperty("tokamak.output"))
30
+ try {
31
+ val registration = registration(File(System.getProperty("tokamak.classes")))
32
+ val plugin = registration::class.allSupertypes.first { it.classifier == TokamakExports::class }
33
+ .arguments.single().type?.classifier as KClass<*>
34
+ val exporter = TokamakExporter<TokamakPlugin>()
35
+ (registration as TokamakExports<TokamakPlugin>).exports(exporter)
36
+ val exports = exports(exporter, plugin)
37
+ val events = exporter.events.map { Event(it.name, it.doc, it.type.starProjectedType, it.reply?.starProjectedType) }
38
+ output.resolve("description.json").writeText(description(exports, events, Types()))
39
+ output.resolve("Exports.generated.kt").writeText(dispatch(plugin, exports, events))
40
+ } catch (error: DescribeError) {
41
+ output.resolve("error").writeText(error.message ?: "")
42
+ }
43
+ }
44
+ }
45
+
46
+ /** An exported method as the registration lists it and Kotlin declares it. */
47
+ internal class Export(
48
+ val kind: String,
49
+ val name: String,
50
+ val doc: String,
51
+ val overflow: TokamakOverflow,
52
+ val parameters: List<KParameter>,
53
+ val returns: KType,
54
+ val suspends: Boolean,
55
+ )
56
+
57
+ /** An event as the registration lists it, with the types its listeners receive and reply with. */
58
+ internal class Event(val name: String, val doc: String, val type: KType, val reply: KType?)
59
+
60
+ /** The one object in [classes] that implements [TokamakExports]. */
61
+ private fun registration(classes: File): TokamakExports<*> {
62
+ val loader = Describe::class.java.classLoader
63
+ val registrations = classes.walk()
64
+ .filter { it.extension == "class" }
65
+ .map { it.relativeTo(classes).path.removeSuffix(".class").replace(File.separatorChar, '.') }
66
+ .mapNotNull { name -> runCatching { Class.forName(name, false, loader) }.getOrNull() }
67
+ .filter { TokamakExports::class.java.isAssignableFrom(it) && !it.isInterface }
68
+ .toList()
69
+ val registration = registrations.singleOrNull()
70
+ ?: throw DescribeError("android/Exports.kt declares one object that implements TokamakExports, not ${registrations.size}")
71
+ return registration.kotlin.objectInstance as? TokamakExports<*>
72
+ ?: throw DescribeError("${registration.simpleName} is an object")
73
+ }
74
+
75
+ /** The methods [exporter] lists, which are [plugin]'s. */
76
+ private fun exports(exporter: TokamakExporter<TokamakPlugin>, plugin: KClass<*>): List<Export> =
77
+ exporter.exports.map { export ->
78
+ val method = export.method
79
+ val receiver = method.parameters.firstOrNull()
80
+ if (receiver?.kind != KParameter.Kind.INSTANCE || receiver.type.classifier != plugin) {
81
+ throw DescribeError("${method.name} is not a method of ${plugin.simpleName}")
82
+ }
83
+ if (export.kind == "stream" && method.isSuspend) {
84
+ throw DescribeError("${plugin.simpleName}.${method.name} returns its Flow without suspending")
85
+ }
86
+ Export(export.kind, method.name, export.doc, export.overflow, method.parameters.drop(1), method.returnType, method.isSuspend)
87
+ }
88
+
89
+ /** The description of [exports] and [events], which records the data classes and enums they use in [types]. */
90
+ private fun description(exports: List<Export>, events: List<Event>, types: Types): String {
91
+ val methods = exports.map { export ->
92
+ val context = "${export.name}:"
93
+ buildMap {
94
+ put("name", export.name)
95
+ put("kind", export.kind)
96
+ if (export.doc.isNotEmpty()) put("doc", export.doc)
97
+ if (export.parameters.isNotEmpty()) {
98
+ put("parameters", export.parameters.map { mapOf("name" to it.name, "type" to types.describe(it.type, "$context ${it.name}")) })
99
+ }
100
+ when (export.kind) {
101
+ "call" -> put("returns", types.describe(export.returns, "$context result"))
102
+ "stream" -> put("returns", types.describe(element(export.returns, context), "$context values"))
103
+ }
104
+ if (export.overflow == TokamakOverflow.DROP_OLDEST) put("overflow", "dropOldest")
105
+ }
106
+ }
107
+ val described = events.map { event ->
108
+ val context = "event ${event.name}:"
109
+ buildMap {
110
+ put("name", event.name)
111
+ if (event.doc.isNotEmpty()) put("doc", event.doc)
112
+ put("type", types.describe(event.type, context))
113
+ event.reply?.let { put("reply", types.describe(it, "$context reply")) }
114
+ }
115
+ }
116
+ val description = buildMap {
117
+ put("methods", methods)
118
+ if (described.isNotEmpty()) put("events", described)
119
+ put("types", types.described.values.toList())
120
+ }
121
+ return JSONObject(description).toString() + "\n"
122
+ }
123
+
124
+ /** The data classes and enums the description names. */
125
+ private class Types {
126
+ private val classes = mutableMapOf<String, KClass<*>>()
127
+
128
+ /** The descriptions of the named types, by name. */
129
+ val described = sortedMapOf<String, Any>()
130
+
131
+ /** The JSON description of [type], whose [context] errors name. Placement rules are tok's to check. */
132
+ fun describe(type: KType, context: String): Any {
133
+ val classifier = type.classifier as? KClass<*> ?: throw DescribeError("$context $type is not a type the Worker can pass")
134
+ val argument = { index: Int -> type.arguments[index].type ?: throw DescribeError("$context $type has a star projection") }
135
+ val value: Any = when (classifier) {
136
+ String::class -> "string"
137
+ Boolean::class -> "boolean"
138
+ Int::class, Long::class, Short::class, Byte::class, Double::class, Float::class -> "number"
139
+ Unit::class -> "void"
140
+ ByteArray::class -> "bytes"
141
+ Any::class -> "json"
142
+ JSONObject::class -> mapOf("record" to "json")
143
+ JSONArray::class -> mapOf("array" to "json")
144
+ TokamakPluginBody::class -> "body"
145
+ TokamakReference::class -> "reference"
146
+ List::class -> mapOf("array" to describe(argument(0), context))
147
+ Map::class -> {
148
+ if (argument(0).classifier != String::class) throw DescribeError("$context maps the Worker passes have String keys")
149
+ mapOf("record" to describe(argument(1), context))
150
+ }
151
+ else -> mapOf("named" to named(classifier, context))
152
+ }
153
+ return if (type.isMarkedNullable) mapOf("optional" to value) else value
154
+ }
155
+
156
+ /** The name of [type], which the first use describes; recording it first ends recursion. */
157
+ private fun named(type: KClass<*>, context: String): String {
158
+ val name = type.simpleName ?: throw DescribeError("$context $type has no name")
159
+ if (!type.java.isEnum && !type.isData && !type.isSealed) {
160
+ throw DescribeError("$context ${type.qualifiedName} is not a data class, an enum class or a sealed type")
161
+ }
162
+ val existing = classes.putIfAbsent(name, type)
163
+ if (existing == null) {
164
+ described[name] = declaration(type, name)
165
+ } else if (existing != type) {
166
+ throw DescribeError("two types the Worker passes are named $name")
167
+ }
168
+ return name
169
+ }
170
+
171
+ private fun declaration(type: KClass<*>, name: String): Any =
172
+ when {
173
+ type.java.isEnum -> mapOf("name" to name, "values" to constants(type))
174
+ type.isSealed -> buildMap {
175
+ put("name", name)
176
+ put("alternatives", forms(type).map { alternative(it, "$name.${it.name}:") })
177
+ type.findAnnotation<TokamakTag>()?.let { put("tag", it.field) }
178
+ }
179
+ else -> mapOf("name" to name, "fields" to fields(type).map { mapOf("name" to it.name, "type" to describe(it.type, "$name.${it.name}:")) })
180
+ }
181
+
182
+ /** The [form]'s name, and the type of its value: a value class's value, or a data class. */
183
+ private fun alternative(form: Form, context: String): Map<String, Any> {
184
+ val value = form.value
185
+ return when {
186
+ form.isName -> mapOf("name" to form.name)
187
+ value != null && (value.type.classifier as? KClass<*>)?.isData == true ->
188
+ throw DescribeError("$context a data class is a form itself, not a value class's value")
189
+ value != null -> mapOf("name" to form.name, "type" to describe(value.type, context))
190
+ form.type.isData -> mapOf("name" to form.name, "type" to mapOf("named" to named(form.type, context)))
191
+ else -> throw DescribeError("$context ${form.type.qualifiedName} is not an object, a data class or a value class")
192
+ }
193
+ }
194
+ }
195
+
196
+ /** A form of a sealed type: a subclass, named with a lowercase first letter. */
197
+ internal class Form(val name: String, val type: KClass<*>) {
198
+ /** Whether the form is an object, whose JSON is its name. */
199
+ val isName = type.objectInstance != null
200
+
201
+ /** A value class's value, which is the form's JSON. */
202
+ val value: KParameter? = if (type.isValue) fields(type).single() else null
203
+ }
204
+
205
+ /** The forms of the sealed type [type], by name, as reflection lists no declaration order. */
206
+ internal fun forms(type: KClass<*>): List<Form> =
207
+ type.sealedSubclasses.map { subclass ->
208
+ val name = subclass.simpleName ?: throw DescribeError("${type.simpleName} has a form without a name")
209
+ Form(name.replaceFirstChar { it.lowercase() }, subclass)
210
+ }.sortedBy { it.name }
211
+
212
+ /** A data class's properties: its primary constructor's parameters. */
213
+ internal fun fields(type: KClass<*>): List<KParameter> = type.primaryConstructor?.parameters.orEmpty()
214
+
215
+ /** An enum class's constants, read without running its initializer. */
216
+ private fun constants(type: KClass<*>): List<String> = type.java.declaredFields.filter { it.isEnumConstant }.map { it.name }
217
+
218
+ private fun element(type: KType, context: String): KType {
219
+ if (type.classifier != Flow::class) throw DescribeError("$context a stream returns a Flow")
220
+ return type.arguments.single().type ?: throw DescribeError("$context $type has a star projection")
221
+ }
@@ -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
@@ -0,0 +1,291 @@
1
+ package com.tokamak.runtime
2
+
3
+ import kotlin.coroutines.cancellation.CancellationException
4
+ import kotlin.enums.EnumEntries
5
+ import kotlin.reflect.KClass
6
+ import kotlin.reflect.KFunction
7
+ import kotlinx.coroutines.CoroutineScope
8
+ import kotlinx.coroutines.CoroutineStart
9
+ import kotlinx.coroutines.Job
10
+ import kotlinx.coroutines.asCoroutineDispatcher
11
+ import kotlinx.coroutines.channels.BufferOverflow
12
+ import kotlinx.coroutines.flow.Flow
13
+ import kotlinx.coroutines.flow.MutableSharedFlow
14
+ import kotlinx.coroutines.flow.onSubscription
15
+ import kotlinx.coroutines.launch
16
+ import org.json.JSONArray
17
+ import org.json.JSONObject
18
+
19
+ /**
20
+ * The methods a plugin's `android/Exports.kt` lists for the Worker to call, and the events the Worker
21
+ * receives. `tok plugin generate android` runs [exports] to write the plugin's dispatch and
22
+ * TypeScript API; the app never does.
23
+ */
24
+ interface TokamakExports<P : TokamakPlugin> {
25
+ fun exports(e: TokamakExporter<P>)
26
+ }
27
+
28
+ /** What a stream does with values a slow reader has not taken. */
29
+ enum class TokamakOverflow {
30
+ /** Ends the stream with `QuotaExceededError`. */
31
+ ERROR,
32
+
33
+ /** Drops the oldest values, for samples where only recent ones matter. */
34
+ DROP_OLDEST,
35
+ }
36
+
37
+ /** Records the methods a plugin exports, with their options, and the events it emits. */
38
+ class TokamakExporter<P : TokamakPlugin> internal constructor() {
39
+ internal class Export(val kind: String, val method: KFunction<*>, val doc: String, val overflow: TokamakOverflow)
40
+
41
+ internal class Event(val name: String, val type: KClass<*>, val reply: KClass<*>?, val doc: String)
42
+
43
+ internal val exports = mutableListOf<Export>()
44
+ internal val events = mutableListOf<Event>()
45
+
46
+ /** Lists the event [name], whose listeners receive a [type] and may reply with a [reply]. */
47
+ fun event(name: String, type: KClass<*>, reply: KClass<*>? = null, doc: String = "") {
48
+ events += Event(name, type, reply, doc)
49
+ }
50
+
51
+ /** Exports [method], which returns once. */
52
+ fun call(method: KFunction<*>, doc: String = "") {
53
+ exports += Export("call", method, doc, TokamakOverflow.ERROR)
54
+ }
55
+
56
+ /** Exports [method], whose values the Worker reads until it cancels. */
57
+ fun stream(method: KFunction<Flow<*>>, overflow: TokamakOverflow = TokamakOverflow.ERROR, doc: String = "") {
58
+ exports += Export("stream", method, doc, overflow)
59
+ }
60
+
61
+ /** Exports [method], which returns a native object the Worker holds as a `NativeReference`. */
62
+ fun resource(method: KFunction<Any>, doc: String = "") {
63
+ exports += Export("resource", method, doc, TokamakOverflow.ERROR)
64
+ }
65
+ }
66
+
67
+ /** How many values listeners keep: those a slow reader has not taken, or those held for the first. */
68
+ private const val LISTENER_CAPACITY = 64
69
+
70
+ /**
71
+ * The flows of an event's listeners, such as a page's, each of which receives every value [send]
72
+ * delivers while it collects, keeping the newest 64 that a slow one has not taken. When [holding],
73
+ * the newest 64 values sent while none listen wait for the first listener.
74
+ */
75
+ class TokamakListeners<T>(private val holding: Boolean = false) {
76
+ private val values = MutableSharedFlow<T>(extraBufferCapacity = LISTENER_CAPACITY, onBufferOverflow = BufferOverflow.DROP_OLDEST)
77
+ private val held = mutableListOf<T>()
78
+
79
+ /** A new listener's flow. */
80
+ fun stream(): Flow<T> =
81
+ values.onSubscription {
82
+ synchronized(held) { held.toList().also { held.clear() } }.forEach { emit(it) }
83
+ }
84
+
85
+ fun send(value: T) {
86
+ synchronized(held) {
87
+ if (holding && values.subscriptionCount.value == 0) {
88
+ held += value
89
+ if (held.size > LISTENER_CAPACITY) held.removeAt(0)
90
+ return
91
+ }
92
+ }
93
+ values.tryEmit(value)
94
+ }
95
+ }
96
+
97
+ /** A native object another plugin retained, which the Worker passes as a `NativeReference`. */
98
+ class TokamakReference<T : Any>(val value: T)
99
+
100
+ /**
101
+ * Names the [field] that tags the forms of a sealed type the Worker passes: each form is an object
102
+ * whose [field] is the form's name, with a data class form's fields.
103
+ */
104
+ @Target(AnnotationTarget.CLASS)
105
+ annotation class TokamakTag(val field: String)
106
+
107
+ /** A JSON value in a call's arguments, at [path], which errors name. */
108
+ class TokamakValue(private val json: Any?, private val path: String) {
109
+ /** The field [key] of this object. */
110
+ operator fun get(key: String): TokamakValue {
111
+ val json = json as? JSONObject ?: throw invalid("an object")
112
+ return TokamakValue(json.opt(key), if (path.isEmpty()) key else "$path.$key")
113
+ }
114
+
115
+ fun string(): String = json as? String ?: throw invalid("a string")
116
+
117
+ fun boolean(): Boolean = json as? Boolean ?: throw invalid("a boolean")
118
+
119
+ fun double(): Double = (json as? Number)?.toDouble() ?: throw invalid("a number")
120
+
121
+ fun float(): Float = double().toFloat()
122
+
123
+ /** The whole number, which JSON from JavaScript carries exactly up to 2^53. */
124
+ fun long(): Long {
125
+ val number = json as? Number ?: throw invalid("a number")
126
+ if (number is Long || number is Int) return number.toLong()
127
+ // A Double from 2^63 up converts to Long.MAX_VALUE.
128
+ val double = number.toDouble()
129
+ if (double % 1.0 != 0.0) throw invalid("a whole number")
130
+ if (double < Long.MIN_VALUE.toDouble() || double >= -Long.MIN_VALUE.toDouble()) throw invalid("a Long")
131
+ return double.toLong()
132
+ }
133
+
134
+ fun int(): Int = long().takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.toInt() ?: throw invalid("an Int")
135
+
136
+ fun short(): Short = long().takeIf { it in Short.MIN_VALUE..Short.MAX_VALUE }?.toShort() ?: throw invalid("a Short")
137
+
138
+ fun byte(): Byte = long().takeIf { it in Byte.MIN_VALUE..Byte.MAX_VALUE }?.toByte() ?: throw invalid("a Byte")
139
+
140
+ /** Any JSON value, as org.json reads it, with null for JSON null. */
141
+ fun json(): Any? = json.takeUnless { it == JSONObject.NULL }
142
+
143
+ /** A JSON value other than null, as org.json reads it. */
144
+ fun any(): Any = json() ?: throw invalid("a value other than null")
145
+
146
+ fun jsonObject(): JSONObject = json as? JSONObject ?: throw invalid("an object")
147
+
148
+ fun jsonArray(): JSONArray = json as? JSONArray ?: throw invalid("an array")
149
+
150
+ /** Null for JSON null or a missing field, and otherwise what [read] reads. */
151
+ fun <T> nullable(read: (TokamakValue) -> T): T? = if (json == null || json == JSONObject.NULL) null else read(this)
152
+
153
+ fun <T> list(read: (TokamakValue) -> T): List<T> {
154
+ val array = json as? JSONArray ?: throw invalid("an array")
155
+ return List(array.length()) { read(TokamakValue(array.opt(it), "$path[$it]")) }
156
+ }
157
+
158
+ fun <T> map(read: (TokamakValue) -> T): Map<String, T> {
159
+ val json = json as? JSONObject ?: throw invalid("an object")
160
+ return json.keys().asSequence().associateWith { read(get(it)) }
161
+ }
162
+
163
+ fun <E : Enum<E>> enum(entries: EnumEntries<E>): E {
164
+ val name = string()
165
+ return entries.firstOrNull { it.name == name } ?: throw invalid("one of ${entries.joinToString()}")
166
+ }
167
+
168
+ /** The error of a value that is none of the forms of the sealed type [name]. */
169
+ fun mismatch(name: String): TokamakPluginError = invalid("one of $name's forms")
170
+
171
+ /** The object of type [type] that [resources] retains as this ID. */
172
+ fun <T : Any> reference(resources: TokamakResources, type: Class<T>): TokamakReference<T> =
173
+ TokamakReference(resources.get(string(), type))
174
+
175
+ private fun invalid(expected: String) = TokamakPluginError.typeError("${path.ifEmpty { "arguments" }} must be $expected")
176
+
177
+ companion object {
178
+ /** A call's arguments: a JSON object of them by parameter name. */
179
+ fun arguments(payload: ByteArray): TokamakValue =
180
+ TokamakValue(runCatching { decodePluginValue(payload) }.getOrNull(), "")
181
+ }
182
+ }
183
+
184
+ /**
185
+ * A plugin with the dispatch generated from its `android/Exports.kt`. The app's registry creates the
186
+ * generated subclass in place of [plugin], which plugins find with `tokamakPlugin(id)`.
187
+ */
188
+ abstract class TokamakDispatch<P : TokamakPlugin>(val plugin: P, protected val host: TokamakHost) : TokamakPlugin by plugin {
189
+ /** [event] as the JSON payload of the event [name], which `android/Exports.kt` lists. */
190
+ open fun eventPayload(name: String, event: Any): ByteArray = throw TokamakPluginError.unlistedEvent(name)
191
+
192
+ /** The listeners' [reply] to the event [name], which `android/Exports.kt` lists with a reply, as its type. */
193
+ open fun eventReply(name: String, reply: TokamakValue): Any = throw TokamakPluginError.unlistedReply(name)
194
+
195
+ /** [value], of a data class or sealed type the plugin's methods and events use, as the JSON org.json writes. */
196
+ open fun encodeValue(value: Any): Any = throw TokamakPluginError.typeError("android/Exports.kt uses no ${value.javaClass.simpleName}")
197
+
198
+ /** [json] as a data class or sealed [type] the plugin's methods and events use. */
199
+ open fun decodeValue(json: TokamakValue, type: KClass<*>): Any = throw TokamakPluginError.typeError("android/Exports.kt uses no ${type.simpleName}")
200
+
201
+ /** The JSON [json], as org.json reads it, as a [type], which [decodeValue] decodes. */
202
+ fun <T : Any> fromJson(json: Any?, type: KClass<T>): T {
203
+ val value = decodeValue(TokamakValue(json, "json"), type)
204
+ return type.castOrNull(value) ?: throw TokamakPluginError.typeError("json is ${value.javaClass.simpleName}, not ${type.simpleName}")
205
+ }
206
+
207
+ /** Delivers [event] to the Worker's listeners of the event [name], returning their encoded reply. */
208
+ fun emit(name: String, event: Any, timeoutMillis: Long): ByteArray = host.emitBytes(name, eventPayload(name, event), timeoutMillis)
209
+
210
+ /** [emit] returning the listeners' reply as a [reply], or null when none replied. */
211
+ fun <R : Any> emit(name: String, event: Any, reply: KClass<R>, timeoutMillis: Long): R? {
212
+ val payload = emit(name, event, timeoutMillis)
213
+ if (payload.isEmpty()) return null
214
+ val json = decodePluginValue(payload).takeUnless { it == JSONObject.NULL } ?: return null
215
+ val value = eventReply(name, TokamakValue(json, "reply"))
216
+ return reply.castOrNull(value)
217
+ ?: throw TokamakPluginError.typeError("event $name replies with ${value.javaClass.simpleName}, not ${reply.simpleName}")
218
+ }
219
+
220
+ /** [event] as the payload of the event [name], whose listeners receive a [type] as [encode] encodes it. */
221
+ protected fun <T : Any> encodeEvent(name: String, event: Any, type: KClass<T>, encode: (T) -> Any?): ByteArray {
222
+ val value = type.castOrNull(event)
223
+ ?: throw TokamakPluginError.typeError("event $name takes ${type.simpleName}, not ${event.javaClass.simpleName}")
224
+ return encodePluginValue(encode(value))
225
+ }
226
+
227
+ /** Replies with what [method] returns, on the call's executor, with nothing to cancel. */
228
+ protected fun respond(reply: TokamakPluginBytesReply, method: () -> Any?): (() -> Unit)? {
229
+ reply(TokamakPluginResult.encoded(runCatching { encodePluginValue(method().unlessUnit()) }, true))
230
+ return null
231
+ }
232
+
233
+ /**
234
+ * Runs the suspending [block] in a coroutine on the executor of [method], replying with what it
235
+ * returns. Cancelling the call cancels the coroutine.
236
+ */
237
+ protected fun launch(method: String, reply: TokamakPluginBytesReply, block: suspend () -> Any?): () -> Unit =
238
+ start(method) {
239
+ reply(TokamakPluginResult.encoded(catching { encodePluginValue(block().unlessUnit()) }, true))
240
+ }
241
+
242
+ /** Replies with each of [values], encoded by [encode], until they end or the Worker cancels. */
243
+ protected fun <T> collect(method: String, reply: TokamakPluginBytesReply, values: Flow<T>, encode: (T) -> Any? = { it }): () -> Unit =
244
+ start(method) {
245
+ val ended = catching { values.collect { reply(TokamakPluginResult(encodePluginValue(encode(it)), false, false)) } }
246
+ reply(TokamakPluginResult.encoded(ended.map { ByteArray(0) }, true))
247
+ }
248
+
249
+ /** Retains [value], replying with its ID, until the subscription ends. */
250
+ protected fun retain(reply: TokamakPluginBytesReply, value: Any): () -> Unit =
251
+ host.resources.retain(value) { reply(TokamakPluginResult.encoded(it.mapCatching(::encodePluginValue), false)) }
252
+
253
+ /** Retains what the suspending [block] returns, replying with its ID, until the subscription ends. */
254
+ protected fun retain(method: String, reply: TokamakPluginBytesReply, block: suspend () -> Any): () -> Unit {
255
+ // The coroutine and its cancellation run on the method's serial executor.
256
+ var release: (() -> Unit)? = null
257
+ var cancelled = false
258
+ val cancel = start(method) {
259
+ catching { block() }.fold(
260
+ // A method that returns after cancellation, ignoring it, leaves nothing to retain.
261
+ { value -> if (!cancelled) release = retain(reply, value) },
262
+ { reply(TokamakPluginResult.encoded(Result.failure(it), true)) },
263
+ )
264
+ }
265
+ return {
266
+ cancelled = true
267
+ cancel()
268
+ release?.invoke()
269
+ }
270
+ }
271
+
272
+ private fun start(method: String, block: suspend () -> Unit): () -> Unit {
273
+ val job: Job = CoroutineScope(executor(method).asCoroutineDispatcher()).launch(start = CoroutineStart.UNDISPATCHED) { block() }
274
+ return { job.cancel() }
275
+ }
276
+ }
277
+
278
+ private fun Any?.unlessUnit(): Any? = takeUnless { it == Unit }
279
+
280
+ /** [value] as a [T], or null when it is of another type. */
281
+ private fun <T : Any> KClass<T>.castOrNull(value: Any): T? = javaObjectType.takeIf { it.isInstance(value) }?.cast(value)
282
+
283
+ /** What [block] returns or throws, except cancellation, which ends the coroutine. */
284
+ private suspend fun <T> catching(block: suspend () -> T): Result<T> =
285
+ try {
286
+ Result.success(block())
287
+ } catch (error: CancellationException) {
288
+ throw error
289
+ } catch (error: Throwable) {
290
+ Result.failure(error)
291
+ }
@@ -6,6 +6,7 @@ import android.content.Intent
6
6
  import android.os.Handler
7
7
  import android.os.Looper
8
8
  import java.util.concurrent.Executor
9
+ import kotlin.reflect.KClass
9
10
  import org.json.JSONArray
10
11
  import org.json.JSONObject
11
12
  import org.json.JSONTokener
@@ -27,6 +28,12 @@ class TokamakPluginError(
27
28
 
28
29
  /** UI was needed while the app is in the background, where it cannot show any. */
29
30
  fun needsUI() = TokamakPluginError("NeedsUIError", "The app cannot show UI while it is in the background")
31
+
32
+ /** The plugin emitted an event its registration does not list. */
33
+ fun unlistedEvent(name: String) = typeError("android/Exports.kt lists no event $name")
34
+
35
+ /** The plugin asked for the reply to an event its registration lists without one. */
36
+ fun unlistedReply(name: String) = typeError("android/Exports.kt lists no reply to event $name")
30
37
  }
31
38
  }
32
39
 
@@ -199,18 +206,35 @@ interface TokamakHost {
199
206
 
200
207
  /**
201
208
  * Delivers the plugin's event [name], which the Worker's listeners receive as
202
- * `<plugin>.<name>`, with its encoded [payload], and returns their encoded reply, which is
203
- * empty when none replied. Starts the runtime when it is not running. Blocks, so call it off
209
+ * `<plugin>.android.<name>`, with its encoded [payload], and returns their encoded reply, which
210
+ * is empty when none replied. Starts the runtime when it is not running. Blocks, so call it off
204
211
  * the main thread; throws unless the listeners return within [timeoutMillis], which includes
205
212
  * runtime startup.
206
213
  */
207
214
  fun emitBytes(name: String, payload: ByteArray, timeoutMillis: Long): ByteArray
208
215
 
209
- /** [emitBytes] with [event] encoded as JSON, returning their reply decoded from JSON, or null when none replied. */
210
- fun emit(name: String, event: Any?, timeoutMillis: Long): Any? {
211
- val reply = emitBytes(name, encodePluginValue(event), timeoutMillis)
212
- return if (reply.isEmpty()) null else decodePluginValue(reply).takeUnless { it == JSONObject.NULL }
213
- }
216
+ /**
217
+ * Delivers [event] to the Worker's listeners of the plugin's event [name], which
218
+ * `android/Exports.kt` lists. Starts the runtime when it is not running. Blocks, so call it off
219
+ * the main thread; throws unless the listeners return within [timeoutMillis], which includes
220
+ * runtime startup.
221
+ */
222
+ fun emit(name: String, event: Any, timeoutMillis: Long)
223
+
224
+ /** [emit] of an event whose listeners may reply, returning the reply, or null when none replied. */
225
+ fun <R : Any> emit(name: String, event: Any, reply: KClass<R>, timeoutMillis: Long): R?
226
+
227
+ /**
228
+ * [value], of a data class or sealed type `android/Exports.kt`'s methods and events use, as
229
+ * the JSON the Worker receives, which org.json writes, for a value the plugin stores.
230
+ */
231
+ fun json(value: Any): Any
232
+
233
+ /**
234
+ * The JSON [json], as org.json reads it, as a data class or sealed [type] `android/Exports.kt`'s
235
+ * methods and events use, for a value the plugin stored with [json].
236
+ */
237
+ fun <T : Any> fromJson(json: Any?, type: KClass<T>): T
214
238
 
215
239
  /**
216
240
  * What the app serves at [path], as its WebView would load it: a file the app ships or the
@@ -27,7 +27,6 @@
27
27
  "class": "string",
28
28
  "dependencies": "strings",
29
29
  "manifest": "path",
30
- "raw": "paths",
31
- "sources": "paths"
30
+ "raw": "paths"
32
31
  }
33
32
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-android-arm64",
3
- "version": "0.1.1-beta.128",
3
+ "version": "0.1.1-beta.130",
4
4
  "description": "The tokamak platform pack for android-arm64",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,23 +0,0 @@
1
- package com.tokamak.runtime
2
-
3
- import org.json.JSONObject
4
-
5
- /** [arguments] as an object; throws a `TypeError` otherwise. */
6
- fun requireObject(arguments: Any?): JSONObject =
7
- arguments as? JSONObject ?: throw TokamakPluginError.typeError("arguments must be an object")
8
-
9
- /** The string [name]; throws a `TypeError` otherwise. */
10
- fun JSONObject.requireString(name: String): String =
11
- optionalString(name) ?: throw TokamakPluginError.typeError("$name must be a string")
12
-
13
- /** The string [name], or null when it is absent or null; throws a `TypeError` otherwise. */
14
- fun JSONObject.optionalString(name: String): String? =
15
- when (val value = opt(name)) {
16
- null, JSONObject.NULL -> null
17
- is String -> value
18
- else -> throw TokamakPluginError.typeError("$name must be a string")
19
- }
20
-
21
- /** The boolean [name]; throws a `TypeError` otherwise. */
22
- fun JSONObject.requireBoolean(name: String): Boolean =
23
- opt(name) as? Boolean ?: throw TokamakPluginError.typeError("$name must be a boolean")