• Stars
    star
    2,053
  • Rank 22,507 (Top 0.5 %)
  • Language
    C
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Run Kotlin/JS libraries in Kotlin/JVM and Kotlin/Native programs

Zipline

This library streamlines using Kotlin/JS libraries from Kotlin/JVM and Kotlin/Native programs. It makes it fetching code as easy as fetching data:

  • For continuous deployment within mobile apps, just like we do for servers and web apps. It'd be simpler to do continuous deploys via the app stores! But that process is too slow and we can't guarantee that userโ€™s devices will update immediately.
  • For user-customizable behavior and plugin systems
  • For updating business rules, like pricing or payments
  • For fresh content like games

Zipline works by embedding the QuickJS JavaScript engine in your Kotlin/JVM or Kotlin/Native program. It's a small and fast JavaScript engine that's well-suited to embedding in applications.

(Looking for Duktape Android?)

Code Example

Let's make a trivia game that has fresh questions every day, even if our users don't update their apps. We define our interface in commonMain so that we can call it from Kotlin/JVM and implement it in Kotlin/JS.

interface TriviaService : ZiplineService {
  fun games(): List<TriviaGame>
  fun answer(questionId: String, answer: String): AnswerResult
}

Next we implement it in jsMain:

class RealTriviaService : TriviaService {
  // ...
}

Let's connect the implementation running in Kotlin/JS to the interface running in Kotlin/JVM. In jsMain we define an exported function to bind the implementation:

@JsExport
fun launchZipline() {
  val zipline = Zipline.get()
  zipline.bind<TriviaService>("triviaService", RealTriviaService())
}

Now we can start a development server to serve our JavaScript to any running applications that request it.

$ ./gradlew -p samples trivia:trivia-js:serveDevelopmentZipline --info --continuous

Note that this Gradle won't ever reach 100%. That's expected; we want the development server to stay on. Also note that the --continuous flag will trigger a re-compile whenever the code changes.

You can see the served application manifest at localhost:8080/manifest.zipline.json. It references all the code modules for the application.

In jvmMain we need write a program that downloads our Kotlin/JS code and calls it. We use ZiplineLoader which handles code downloading, caching, and loading. We create a Dispatcher to run Kotlin/JS on. This must be a single-threaded dispatcher as each Zipline instance must be confined to a single thread.

suspend fun launchZipline(dispatcher: CoroutineDispatcher): Zipline {
  val manifestUrl = "http://localhost:8080/manifest.zipline.json"
  val loader = ZiplineLoader(
    dispatcher,
    ManifestVerifier.NO_SIGNATURE_CHECKS,
    OkHttpClient(),
  )
  return loader.loadOnce("trivia", manifestUrl)
}

Now we build and run the JVM program to put it all together. Do this in a separate terminal from the development server!

$ ./gradlew -p samples trivia:trivia-host:shadowJar
java -jar samples/trivia/trivia-host/build/libs/trivia-host-all.jar

Interface bridging

Zipline makes it easy to share interfaces with Kotlin/JS. Define an interface in commonMain, implement it in Kotlin/JS, and call it from the host platform. Or do the opposite: implement it on the host platform and call it from Kotlin/JS.

Bridged interfaces must extend ZiplineService, which defines a single close() method to release held resources.

By default, arguments and return values are pass-by-value. Zipline uses kotlinx.serialization to encode and decode values passed across the boundary.

Interface types that extend from ZiplineService are pass-by-reference: the receiver may call methods on a live instance.

Interface functions may be suspending. Internally Zipline implements setTimeout() to make asynchronous code work as it's supposed to in Kotlin/JS.

Zipline also supports Flow<T> as a parameter or return type. This makes it easy to build reactive systems.

Fast

One potential bottleneck of embedding JavaScript is waiting for the engine to compile the input source code. Zipline precompiles JavaScript into efficient QuickJS bytecode to eliminate this performance penalty.

Another bottleneck is waiting for code to download. Zipline addresses this with support for modular applications. Each input module (Like Kotlin's standard, serialization, and coroutines libraries) is downloaded concurrently. Each downloaded module is cached. Modules can also be embedded with the host application to avoid any downloads if the network is unreachable. If your application module changes more frequently than your libraries, users only download what's changed.

If you run into performance problems in the QuickJS runtime, Zipline includes a sampling profiler. You can use this to get a breakdown of how your application spends its CPU time.

Developer-Friendly

Zipline implements console.log by forwarding messages to the host platform. It uses android.util.Log on Android, java.util.logging on JVM, and stdout on Kotlin/Native.

Zipline integrates Kotlin source maps into QuickJS bytecode. If your process crashes, the stacktrace will print .kt files and line numbers. Even though there's JavaScript underneath, developers don't need to interface with .js files.

After using a bridged interface it must be closed so the peer object can be garbage collected. This is difficult to get right, so Zipline borrows ideas from LeakCanary and aggressively detects when a close() call is missed.

Secure

Zipline supports EdDSA Ed25519 and ECDSA P-256 signatures to authenticate downloaded libraries.

Set up is straightforward. Generate an EdDSA key pair. A task for this is installed with the Zipline Gradle plugin.

$ ./gradlew :generateZiplineManifestKeyPairEd25519
...
---------------- ----------------------------------------------------------------
      ALGORITHM: Ed25519
     PUBLIC KEY: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    PRIVATE KEY: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
---------------- ----------------------------------------------------------------
...

Put the private key on the build server and configure it to sign builds:

zipline {
  signingKeys {
    create("key1") {
      privateKeyHex.set(...)
      algorithmId.set(app.cash.zipline.loader.SignatureAlgorithmId.Ed25519)
    }
  }
}

Put the public key in each host application and configure it to verify signatures:

val manifestVerifier = ManifestVerifier.Builder()
  .addEd25519("key1", ...)
  .build()
val loader = ZiplineLoader(
  manifestVerifier = manifestVerifier,
  ...
)

Both signing and verifying accept multiple keys to support key rotation.

Zipline is designed to run your organization's code when and where you want it. It does not offer a sandbox or process-isolation and should not be used to execute untrusted code.

Trust Model for Signatures

It is essential to keep in mind that this design puts implicit trust on:

  1. The Host Application that verifies the signatures.
  2. The Build Server that generates the signature(Has access to the signing keys)

It does not protect against any kind of compromise of the above.

Also It does not yet provide a mechanism to outlaw older(signed) versions of executable code that have known problems.

Speeding Up Hot-Reload

There are a few things you can do to make sure that hot-reload is running as fast as it can:

  1. Ensure you are running Gradle 7.5 or later (previous versions had a delay in picking up changed files).
  2. In your app's gradle.properties add kotlin.incremental.js.ir=true to enable Kotlin/JS incremental compile.
  3. In your app's gradle.properties add org.gradle.unsafe.configuration-cache=true to enable the Gradle configuration cache.
  4. In your app's build.gradle.kts add tasks.withType(DukatTask::class) { enabled = false } to turn off the Dukat task if you are not using TypeScript type declarations.

Requirements

Zipline works on Android 4.3+ (API level 18+), Java 8+, and Kotlin/Native.

Zipline uses unstable APIs in its implementation and is sensitive to version updates for these components.

Component Supported Version Notes
Kotlin Compiler 1.8.20 Kotlin compiler plugins do not yet have a stable API.
Kotlin Serialization 1.5.1 For decodeFromDynamic(), encodeToDynamic(), and ContextualSerializer.
Kotlin Coroutines 1.7.1 For transformLatest() and Deferred.getCompleted().

We intend to use stable APIs as soon as they are available.

We intend to keep Zipline host and runtime releases interoperable so you can upgrade each independently.

Host Zipline Version Supported Runtime Zipline Versions
0.x Exact same 0.x version as the host.
1.x Any 1.x version.

License

Copyright 2015 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Duktape-Android

This project was previously known as Duktape-Android and packaged the Duktape JavaScript engine for Android. The Duktape history is still present in this repo as are the release tags. Available versions are listed on Maven central.

More Repositories

1

sqldelight

SQLDelight - Generates typesafe Kotlin APIs from SQL
Kotlin
6,146
star
2

turbine

A testing library for kotlinx.coroutines Flow
Kotlin
2,472
star
3

paparazzi

Render your Android screens without a physical device or emulator
Kotlin
2,284
star
4

molecule

Build a StateFlow stream using Jetpack Compose
Kotlin
1,864
star
5

redwood

Multiplatform reactive UI for Android, iOS, and web using Kotlin and Jetpack Compose
Kotlin
1,649
star
6

contour

Layouts with lambdas ๐Ÿ˜Ž
Kotlin
1,531
star
7

InflationInject

Constructor-inject views during XML layout inflation
Kotlin
904
star
8

licensee

Gradle plugin which validates the licenses of your dependency graph match what you expect
Kotlin
626
star
9

pranadb

Go
613
star
10

hermit

๐Ÿš Hermit manages isolated, self-bootstrapping sets of tools in software projects.
Go
596
star
11

AccessibilitySnapshot

Easy regression testing for iOS accessibility
Swift
550
star
12

multiplatform-paging

A library that packages AndroidX Paging for Kotlin/Multiplatform.
Kotlin
542
star
13

exhaustive

An annotation and Kotlin compiler plugin for enforcing a when statement is exhaustive
Kotlin
463
star
14

misk

Microservice Kontainer
Kotlin
402
star
15

copper

A content provider wrapper for reactive queries
Kotlin
301
star
16

barber

Barber ๐Ÿ’ˆ A type safe Kotlin JVM library for building up localized, fillable, themed documents using Mustache templating
Kotlin
166
star
17

paraphrase

A Gradle plugin that generates type-safe formatters for Android string resources in the ICU message format.
Kotlin
163
star
18

stagehand

Modern, type-safe API for building animations on iOS
Swift
132
star
19

hermit-packages

Hermit manages isolated, self-bootstrapping sets of tools in software projects.
HCL
120
star
20

quiver

Quiver is a collection of extension methods and handy functions to make the wonderful functional programming Kotlin library, Arrow, even better.
Kotlin
116
star
21

spirit

Online Schema Change Tool for MySQL 8.0+
Go
104
star
22

pivit

Go
89
star
23

tempest

Typesafe DynamoDB for Kotlin and Java.
Kotlin
83
star
24

better-dynamic-features

Making dynamic feature modules better
Kotlin
80
star
25

misk-web

Micro-Frontends React + Redux + Typescript Framework
TypeScript
64
star
26

blip

Sublime MySQL monitoring
Go
62
star
27

logquacious

Logquacious (lq) is a fast and simple log viewer.
TypeScript
59
star
28

wisp

Wisp is a collection of kotlin modules providing various features and utilities, including config, logging, feature flags and more.
Kotlin
57
star
29

certifikit

Kotlin Certificate processing library.
Kotlin
40
star
30

cash-app-pay-android-sdk

Cash Android PayKit SDK for merchant integrations with Cash App Pay
Kotlin
32
star
31

backfila

Service that manages backfill state, calling into other services to do batched work
Kotlin
31
star
32

nostrino

A Kotlin SDK for Nostr
Kotlin
28
star
33

cloner

Go
28
star
34

cash-app-pay-ios-sdk

Swift
24
star
35

transflect

Kubernetes operator using Istio to set up Envoy's gRPC-JSON transcoding.
Go
24
star
36

kfsm

Finite state machinery in Kotlin
Kotlin
22
star
37

cmmc

K8S ConfigMap Merging Controller
Go
21
star
38

yet-another-aws-exporter

A Prometheus metrics exporter for AWS that fills in gaps CloudWatch doesn't cover
Go
17
star
39

protosync

ProtoSync synchronises remote .proto files to a local directory
Go
15
star
40

cash-pay-pay-sdk-android-sample-app

Cash App Pay Kit SDK Sample app for Android.
Kotlin
15
star
41

trifle

Security functionality for interoperability/interaction with core services.
Swift
12
star
42

jooq-encryption

Kotlin
11
star
43

kfactories

Set of factories and utils to create effective and lightweight property-based testing strategies.
Kotlin
10
star
44

AardvarkReveal

Generate and attach a Reveal file to your Aardvark bug reports
Swift
10
star
45

ln-invoice

Parse lightning network payment requests (invoices) in Kotlin.
Kotlin
10
star
46

hermit-ij-plugin

Kotlin
9
star
47

kotlin-editor

Kotlin
8
star
48

cash-app-pay-sdk-ios-sample-app

Swift
8
star
49

awsu

su for aws roles
Go
8
star
50

AardvarkCrashReport

AardvarkCrashReport makes it easy to provide high quality data about crashes in your bug reports
Swift
7
star
51

activate-hermit

Github Action to activate a Hermit environment.
Shell
7
star
52

knit

Safety features for Swinject
Swift
7
star
53

csop

Go
6
star
54

check-signature-action

Shell
5
star
55

kruit

TypeScript
4
star
56

hermit-build

Relocatable/static builds for Hermit packages
Makefile
3
star
57

chronicler

Kotlin
2
star
58

s3-copy-gradle-plugin

1
star
59

.github

1
star
60

hermit-package-version

Shell
1
star
61

cash-app-pay-sandbox-releases

1
star