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

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.
@@ -307,11 +307,13 @@ for plugin in "$input/plugins"/*/; do
307
307
  echo "plugin '$plugin_id' has invalid android class '$class'" >&2
308
308
  exit 1
309
309
  fi
310
- # A plugin that exports methods runs behind the dispatch generated for it.
310
+ # A plugin that exports methods runs behind the dispatch generated for it,
311
+ # whose companion object converts its values for its host.
311
312
  if [[ -f "$plugin/native/Exports.kt" ]]; then
312
- class=${class}Dispatch
313
+ printf ' %sDispatch(app.host("%s", %sDispatch)),\n' "$class" "$plugin_id" "$class" >> "$registry"
314
+ else
315
+ printf ' %s(app.host("%s")),\n' "$class" "$plugin_id" >> "$registry"
313
316
  fi
314
- printf ' %s(app.host("%s")),\n' "$class" "$plugin_id" >> "$registry"
315
317
  module=$plugin_modules/$plugin_id
316
318
  mkdir -p "$module/src/main/kotlin"
317
319
  if [[ -d "$plugin/native" ]]; then
@@ -32,23 +32,17 @@ internal fun dispatch(plugin: KClass<*>, exports: List<Export>, events: List<Eve
32
32
  exports.filter { it.kind != "call" },
33
33
  "is not supported",
34
34
  ),
35
- code.events(events),
36
- code.replies(events),
37
35
  )
38
36
  val results = exports.filter { it.kind != "resource" }.map { if (it.kind == "stream") it.returns.arguments.single().type!! else it.returns }
39
37
  val parameters = exports.flatMap { export -> export.parameters.map { it.type } }
40
38
  val classes = jsonClasses(parameters + results + events.flatMap { listOfNotNull(it.type, it.reply) })
41
- val functions = (requests + code.values(classes)).filter { it.isNotEmpty() }
39
+ val functions = requests.filter { it.isNotEmpty() }
42
40
  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"
41
+ // Conversions are the companion's, so the file declares only the class, whose name is the plugin's.
48
42
  val dispatch = listOf(
49
- "/** Routes the Worker's requests to the methods [$name] exports$emits. */",
43
+ "/** Routes the Worker's requests to the methods [$name] exports. */",
50
44
  "class ${name}Dispatch(host: TokamakHost) : TokamakDispatch<$name>($name(host), host) {",
51
- ) + functions.flatMap { listOf("") + it }.drop(1) + conversions + "}"
45
+ ) + functions.flatMap { listOf("") + it }.drop(1) + code.codec(name, classes, events) + "}"
52
46
  val header = listOf("// Generated by `tok plugin generate android`. Do not edit.", "package ${code.packageName}", "")
53
47
  return (header + code.imports() + "" + dispatch).joinToString("\n") + "\n"
54
48
  }
@@ -89,7 +83,7 @@ private class Code(val packageName: String) {
89
83
  }
90
84
 
91
85
  /** The encoding of the events' payloads, or nothing without events. */
92
- fun events(events: List<Event>): List<String> {
86
+ private fun events(events: List<Event>): List<String> {
93
87
  if (events.isEmpty()) return emptyList()
94
88
  val branches = events.map { event ->
95
89
  val type = event.type.classifier as KClass<*>
@@ -99,7 +93,7 @@ private class Code(val packageName: String) {
99
93
  }
100
94
 
101
95
  /** The decoding of the events' replies, or nothing when no event takes one. */
102
- fun replies(events: List<Event>): List<String> {
96
+ private fun replies(events: List<Event>): List<String> {
103
97
  val branches = events.mapNotNull { event -> event.reply?.let { "\"${event.name}\" -> ${decode(it, "reply")}" } }
104
98
  if (branches.isEmpty()) return emptyList()
105
99
  imports += "com.tokamak.runtime.TokamakValue"
@@ -107,19 +101,31 @@ private class Code(val packageName: String) {
107
101
  }
108
102
 
109
103
  /**
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.
104
+ * The companion object that converts the [classes] and [events] to and from JSON, for the
105
+ * dispatch's methods and the plugin's host. A sealed type's data class form encodes as the
106
+ * sealed type does, with its tag.
112
107
  */
113
- fun values(classes: Set<KClass<*>>): List<List<String>> {
108
+ fun codec(plugin: String, classes: Set<KClass<*>>, events: List<Event>): List<String> {
109
+ imports += "com.tokamak.runtime.TokamakCodec"
110
+ val doc = " /** Converts the values and events of [$plugin] to and from JSON. */"
111
+ val sorted = classes.sortedBy { it.simpleName }
112
+ val switches = listOf(events(events), replies(events), values(sorted)).filter { it.isNotEmpty() }
113
+ if (switches.isEmpty()) return listOf("", doc, " companion object : TokamakCodec")
114
+ val members = switches.flatMap { listOf("") + it }.drop(1).map { if (it.isEmpty()) it else " $it" }
115
+ val conversions = sorted.flatMap { decoder(it) + encoder(it) }
116
+ return listOf("", doc, " companion object : TokamakCodec {") + members +
117
+ conversions.map { if (it.isEmpty()) it else " $it" } + " }"
118
+ }
119
+
120
+ /** The conversions of the [classes], sorted by name, to and from JSON by type, or nothing without classes. */
121
+ private fun values(classes: List<KClass<*>>): List<String> {
114
122
  if (classes.isEmpty()) return emptyList()
115
123
  imports += listOf("com.tokamak.runtime.TokamakValue", "kotlin.reflect.KClass")
116
- val sorted = classes.sortedBy { it.simpleName }
117
124
  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
- )
125
+ val encodes = classes.filter { it !in forms }.map { "is ${name(it)} -> json(value)" }
126
+ val decodes = classes.map { "${name(it)}::class -> json.as${it.simpleName}()" }
127
+ return switch("override fun encodeValue(value: Any): Any =", "value", encodes, "super.encodeValue(value)") + "" +
128
+ switch("override fun decodeValue(json: TokamakValue, type: KClass<*>): Any =", "type", decodes, "super.decodeValue(json, type)")
123
129
  }
124
130
 
125
131
  /** A function whose body switches on the event's name, leaving others to [otherwise]. */
@@ -92,8 +92,11 @@ class TokamakApplication : Application(), TokamakPlugins {
92
92
 
93
93
  override fun plugin(id: String): TokamakPlugin? = plugins[id].let { (it as? TokamakDispatch<*>)?.plugin ?: it }
94
94
 
95
- /** The host the plugin [id] sees, whose events the Worker's listeners receive as `<id>.android.<name>`. */
96
- internal fun host(id: String): TokamakHost =
95
+ /**
96
+ * The host the plugin [id] sees, whose events the Worker's listeners receive as
97
+ * `<id>.android.<name>`, and which converts values to and from JSON with the plugin's [codec].
98
+ */
99
+ internal fun host(id: String, codec: TokamakCodec? = null): TokamakHost =
97
100
  object : TokamakHost {
98
101
  override val context: Context
99
102
  get() = this@TokamakApplication
@@ -122,19 +125,20 @@ class TokamakApplication : Application(), TokamakPlugins {
122
125
  emitEvent("$id.android.$name", payload, timeoutMillis)
123
126
 
124
127
  override fun emit(name: String, event: Any, timeoutMillis: Long) {
125
- dispatch { TokamakPluginError.unlistedEvent(name) }.emit(name, event, timeoutMillis)
128
+ emitBytes(name, codec { TokamakPluginError.unlistedEvent(name) }.eventPayload(name, event), timeoutMillis)
126
129
  }
127
130
 
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)
131
+ override fun <R : Any> emit(name: String, event: Any, reply: KClass<R>, timeoutMillis: Long): R? {
132
+ val codec = codec { TokamakPluginError.unlistedEvent(name) }
133
+ return codec.reply(name, emitBytes(name, codec.eventPayload(name, event), timeoutMillis), reply)
134
+ }
130
135
 
131
- override fun json(value: Any): Any = dispatch(::unregistered).encodeValue(value)
136
+ override fun json(value: Any): Any = codec(::unregistered).encodeValue(value)
132
137
 
133
- override fun <T : Any> fromJson(json: Any?, type: KClass<T>): T = dispatch(::unregistered).fromJson(json, type)
138
+ override fun <T : Any> fromJson(json: Any?, type: KClass<T>): T = codec(::unregistered).fromJson(json, type)
134
139
 
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()
140
+ /** The plugin's codec, or else the error [missing] gives: a plugin without `android/Exports.kt` has none. */
141
+ private fun codec(missing: () -> TokamakPluginError): TokamakCodec = codec ?: throw missing()
138
142
 
139
143
  private fun unregistered() = TokamakPluginError.typeError("$id has no android/Exports.kt")
140
144
 
@@ -94,6 +94,50 @@ class TokamakListeners<T>(private val holding: Boolean = false) {
94
94
  }
95
95
  }
96
96
 
97
+ /**
98
+ * Converts the values a plugin's `android/Exports.kt` uses to and from JSON: its data classes and
99
+ * sealed types, and its events and their replies. Each generated dispatch's companion object is
100
+ * one, which the plugin's host uses, even while the plugin is being created.
101
+ */
102
+ interface TokamakCodec {
103
+ /** [value] as the JSON org.json writes. */
104
+ fun encodeValue(value: Any): Any = throw TokamakPluginError.typeError("android/Exports.kt uses no ${value.javaClass.simpleName}")
105
+
106
+ /** [json] as a [type]. */
107
+ fun decodeValue(json: TokamakValue, type: KClass<*>): Any = throw TokamakPluginError.typeError("android/Exports.kt uses no ${type.simpleName}")
108
+
109
+ /** The JSON [json], as org.json reads it, as a [type], which [decodeValue] decodes. */
110
+ fun <T : Any> fromJson(json: Any?, type: KClass<T>): T {
111
+ val value = decodeValue(TokamakValue(json, "json"), type)
112
+ return type.castOrNull(value) ?: throw TokamakPluginError.typeError("json is ${value.javaClass.simpleName}, not ${type.simpleName}")
113
+ }
114
+
115
+ /** [event] as the JSON payload of the event [name], which `android/Exports.kt` lists. */
116
+ fun eventPayload(name: String, event: Any): ByteArray = throw TokamakPluginError.unlistedEvent(name)
117
+
118
+ /** The listeners' [reply] to the event [name], which `android/Exports.kt` lists with a reply, as its type. */
119
+ fun eventReply(name: String, reply: TokamakValue): Any = throw TokamakPluginError.unlistedReply(name)
120
+
121
+ /** The listeners' encoded [payload] in reply to the event [name] as a [type], or null when none replied. */
122
+ fun <R : Any> reply(name: String, payload: ByteArray, type: KClass<R>): R? {
123
+ if (payload.isEmpty()) return null
124
+ val json = decodePluginValue(payload).takeUnless { it == JSONObject.NULL } ?: return null
125
+ val value = eventReply(name, TokamakValue(json, "reply"))
126
+ return type.castOrNull(value)
127
+ ?: throw TokamakPluginError.typeError("event $name replies with ${value.javaClass.simpleName}, not ${type.simpleName}")
128
+ }
129
+
130
+ /**
131
+ * [event] as the payload of the event [name], whose listeners receive a [type] as [encode]
132
+ * encodes it, for the generated [eventPayload].
133
+ */
134
+ fun <T : Any> encodeEvent(name: String, event: Any, type: KClass<T>, encode: (T) -> Any?): ByteArray {
135
+ val value = type.castOrNull(event)
136
+ ?: throw TokamakPluginError.typeError("event $name takes ${type.simpleName}, not ${event.javaClass.simpleName}")
137
+ return encodePluginValue(encode(value))
138
+ }
139
+ }
140
+
97
141
  /** A native object another plugin retained, which the Worker passes as a `NativeReference`. */
98
142
  class TokamakReference<T : Any>(val value: T)
99
143
 
@@ -186,44 +230,6 @@ class TokamakValue(private val json: Any?, private val path: String) {
186
230
  * generated subclass in place of [plugin], which plugins find with `tokamakPlugin(id)`.
187
231
  */
188
232
  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
233
  /** Replies with what [method] returns, on the call's executor, with nothing to cancel. */
228
234
  protected fun respond(reply: TokamakPluginBytesReply, method: () -> Any?): (() -> Unit)? {
229
235
  reply(TokamakPluginResult.encoded(runCatching { encodePluginValue(method().unlessUnit()) }, true))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-android-arm64",
3
- "version": "0.1.1-beta.130",
3
+ "version": "0.1.1-beta.131",
4
4
  "description": "The tokamak platform pack for android-arm64",
5
5
  "repository": {
6
6
  "type": "git",