@nativue/core 0.8.0 → 0.10.0

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.
package/AGENTS.md ADDED
@@ -0,0 +1,94 @@
1
+ # nativue: guide for coding agents
2
+
3
+ This app is built with nativue: Vue 3 single-file components rendered as real native views on iOS and
4
+ Android. It is not a web app. There is no DOM, no browser and no CSS, so web habits produce code that
5
+ doesn't work. Full docs: https://github.com/nativue/nativue/tree/main/docs
6
+
7
+ ## What doesn't exist
8
+
9
+ - HTML elements (`<div>`, `<span>`, `<p>`, `<img>`, `<button>`, `<input>`, `<ul>`...): use the
10
+ components below.
11
+ - CSS: `<style>` blocks, class names from a stylesheet, `px`/`rem`/`em` units, `:hover`, media queries.
12
+ A `.vue` file's `<style>` block is left out of the build.
13
+ - Browser globals: `window`, `document`, `localStorage`, `sessionStorage`, `navigator`, `alert`.
14
+ Use `AsyncStorage` for storage.
15
+ - Vue Router and `main.ts`: routing is file-based (below), and nativue creates the app.
16
+
17
+ ## Components
18
+
19
+ Global, with no import: `View`, `Text`, `Image`, `ImageBackground`, `Pressable`, `Button`, `TextInput`,
20
+ `Switch`, `ScrollView`, `FlatList`, `Swipeable`, `Modal`, `ActivityIndicator`, `SafeAreaView`,
21
+ `KeyboardAvoidingView`, `Svg`.
22
+
23
+ - Text must be inside a `<Text>`, never directly in a `<View>`.
24
+ - Taps: `<Pressable @press="save">` (also `@long-press`, and `v-slot="{ pressed }"`), or
25
+ `<Button title="Save" @press="save" />`. There is no `@click`.
26
+ - Inputs: `<TextInput v-model="name" placeholder="Name" @submit-editing="save" />`.
27
+ - Images: `import logo from '@/assets/logo.png'` then `<Image :source="logo" />`; remote ones as
28
+ `:source="{ uri: url }"`. A remote image has no size until it loads: give it a width and height
29
+ where the layout shouldn't jump, like a list's rows.
30
+ - Long lists: `<FlatList :data="items" :key-extractor="(item) => item.id">` with a
31
+ `<template #item="{ item }">` slot, not `v-for` in a `ScrollView`.
32
+
33
+ ## Styling
34
+
35
+ - `style` takes an object with CSS properties in camelCase and numbers in points, no units:
36
+ `:style="{ padding: 16, borderRadius: 12, backgroundColor: '#ffffff' }"`. Arrays merge, later wins:
37
+ `:style="[styles.card, selected && styles.selected]"`.
38
+ - `StyleSheet.create({...})` (from `vue`) groups and types a screen's styles.
39
+ - Every view is a flexbox container stacking its children in a **column** by default; `flex: 1` takes
40
+ the space left. Percentages (`'50%'`) work for sizes.
41
+ - Text styles (`color`, `fontSize`, `fontWeight`, `textAlign`, `textDecorationLine`) go on the
42
+ `<Text>` itself: native views don't inherit them from their parents.
43
+ - Pressed and focused states: `pressed-style` on `Pressable`, `focused-style` on `TextInput`.
44
+ - Dark mode: `useColorScheme()` (from `vue`) gives `'light'` or `'dark'`, live.
45
+ - Platform: `Platform.OS` is `'ios'` or `'android'`; `Platform.select({ ios, android })`.
46
+ - If the app uses `@nativue/tailwind` (see `nativue.config.ts`), Tailwind classes work in `class`,
47
+ with the `active:`, `focus:`, `disabled:`, `dark:`, `ios:` and `android:` variants.
48
+
49
+ ## Navigation
50
+
51
+ Every `.vue` file in `src/app` is a screen, and its path is its URL:
52
+
53
+ | File | URL |
54
+ | --------------------- | ------------------------------------------------------ |
55
+ | `app/index.vue` | `/` |
56
+ | `app/items/[id].vue` | `/items/42`, param `id` |
57
+ | `app/(tabs)/home.vue` | `/home`: a folder in parentheses groups without a path |
58
+ | `app/_layout.vue` | the layout of its folder: a `<Stack>` or a `<Tabs>` |
59
+ | `app/+not-found.vue` | shown when no route matches |
60
+
61
+ Import navigation from `@nativue/core/router`:
62
+
63
+ - `<Link href="/items/42">` (a Pressable); `router.push(path)`, `router.navigate(path)`,
64
+ `router.replace(path)`, `router.back()`.
65
+ - `useLocalSearchParams<{ id: string }>()` reads params and the query string.
66
+ - `<Stack.Screen :options="{ title: 'Item' }" />` inside a screen sets its header; in a layout,
67
+ `<Stack.Screen name="modal" :options="{ presentation: 'modal' }" />` sets a route's options.
68
+
69
+ ## APIs
70
+
71
+ Import the runtime from `vue`: `ref`, `computed`, `StyleSheet`, `Animated`, `LayoutAnimation`,
72
+ `Platform`, `AsyncStorage`, `Keyboard`, `Dimensions`, `useWindowDimensions`, `useColorScheme`,
73
+ `AccessibilityInfo`, `requireNativeFunction`.
74
+
75
+ - `AsyncStorage`: `getItem`, `setItem`, `removeItem`, `getAllKeys`, `multiGet`, `multiSet`,
76
+ `clear`; promise-based, string values. Store objects as JSON. For large data or queries, use
77
+ `@nativue/sqlite`.
78
+ - `fetch`, `XMLHttpRequest`, `Blob`, `FileReader`, `URL`, `URLSearchParams`, timers and `console`
79
+ work as on the web, with no import.
80
+ - Accessibility: `role` and `aria-*` attributes (`aria-label`, `aria-hidden`...) on any component.
81
+
82
+ ## Project
83
+
84
+ - `@/` points at `src/`. Shared components go in `src/components`, everything else in `src/lib`.
85
+ - Vue plugins (Pinia...) are installed in `src/app.ts`: `export default function setup(app: App)`.
86
+ - Official packages: `@nativue/icons` (icon components), `@nativue/tailwind`, `@nativue/haptics`,
87
+ `@nativue/sqlite`. A package with native code needs the app rebuilt with `npm run ios` or
88
+ `npm run android`, not just a reload.
89
+ - Commands: `npm run ios` / `npm run android` build and open the app, then reload on save;
90
+ `npm run typecheck` checks scripts and templates; `npm run build` makes the release bundle;
91
+ `npm run format` formats with Prettier.
92
+ - Check changes with `npm run typecheck`. `ios/` and `android/` are the native host apps: change them
93
+ only for native settings (permissions in `Info.plist` or `AndroidManifest.xml`, the app's name and
94
+ icon).
@@ -1,11 +1,13 @@
1
1
  // JNI bridge between dev.nativue.JavaScriptRuntime (Kotlin) and Hermes, through JSI. Values cross as
2
- // plain Java objects: null, Boolean, Double, String, ArrayList and HashMap (and back from any Number,
3
- // List, Map or Object[]). Every call happens on the JS thread.
2
+ // plain Java objects: null, Boolean, Double, String, ByteArray (from an ArrayBuffer or a typed array, back
3
+ // as a Uint8Array), ArrayList and HashMap (and back from any Number, List, Map or Object[]). Every call
4
+ // happens on the JS thread.
4
5
  #include <hermes/hermes.h>
5
6
  #include <jni.h>
6
7
  #include <jsi/jsi.h>
7
8
 
8
9
  #include <memory>
10
+ #include <optional>
9
11
  #include <string>
10
12
  #include <vector>
11
13
 
@@ -16,7 +18,7 @@ namespace {
16
18
  JavaVM* javaVM;
17
19
 
18
20
  struct JavaTypes {
19
- jclass object, boolean, number, doubleClass, string, list, arrayList, map, hashMap, objectArray;
21
+ jclass object, boolean, number, doubleClass, string, byteArray, list, arrayList, map, hashMap, objectArray;
20
22
  jmethodID booleanValueOf, booleanValue, doubleValueOf, numberDoubleValue;
21
23
  jmethodID listSize, listGet, arrayListInit, arrayListAdd;
22
24
  jmethodID mapKeys, mapGet, hashMapInit, hashMapPut, setToArray;
@@ -84,6 +86,53 @@ std::string toStdString(JNIEnv* env, jstring string) {
84
86
  return text;
85
87
  }
86
88
 
89
+ // ---------- Bytes ----------
90
+
91
+ struct Bytes {
92
+ const uint8_t* data;
93
+ size_t size;
94
+ };
95
+
96
+ // An ArrayBuffer, or what a typed array or DataView sees of one. Not copied: use before calling JS again.
97
+ std::optional<Bytes> bytesOf(jsi::Runtime& runtime, const jsi::Object& object) {
98
+ if (object.isArrayBuffer(runtime)) {
99
+ jsi::ArrayBuffer buffer = object.getArrayBuffer(runtime);
100
+
101
+ return Bytes{buffer.data(runtime), buffer.size(runtime)};
102
+ }
103
+
104
+ jsi::Value buffer = object.getProperty(runtime, "buffer");
105
+ if (!buffer.isObject() || !buffer.getObject(runtime).isArrayBuffer(runtime)) return std::nullopt;
106
+
107
+ jsi::ArrayBuffer arrayBuffer = buffer.getObject(runtime).getArrayBuffer(runtime);
108
+ auto offset = static_cast<size_t>(object.getProperty(runtime, "byteOffset").asNumber());
109
+ auto length = static_cast<size_t>(object.getProperty(runtime, "byteLength").asNumber());
110
+
111
+ return Bytes{arrayBuffer.data(runtime) + offset, length};
112
+ }
113
+
114
+ class OwnedBuffer : public jsi::MutableBuffer {
115
+ public:
116
+ explicit OwnedBuffer(std::vector<uint8_t> bytes) : bytes_(std::move(bytes)) {}
117
+
118
+ size_t size() const override {
119
+ return bytes_.size();
120
+ }
121
+
122
+ uint8_t* data() override {
123
+ return bytes_.data();
124
+ }
125
+
126
+ private:
127
+ std::vector<uint8_t> bytes_;
128
+ };
129
+
130
+ jsi::Value uint8Array(jsi::Runtime& runtime, std::vector<uint8_t> bytes) {
131
+ jsi::ArrayBuffer buffer(runtime, std::make_shared<OwnedBuffer>(std::move(bytes)));
132
+
133
+ return runtime.global().getPropertyAsFunction(runtime, "Uint8Array").callAsConstructor(runtime, buffer);
134
+ }
135
+
87
136
  // ---------- Values ----------
88
137
 
89
138
  jobject toJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Value& value);
@@ -118,6 +167,13 @@ jobject objectToJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Object& obje
118
167
  return map;
119
168
  }
120
169
 
170
+ jbyteArray bytesToJava(JNIEnv* env, const Bytes& bytes) {
171
+ jbyteArray array = env->NewByteArray(static_cast<jsize>(bytes.size));
172
+ env->SetByteArrayRegion(array, 0, static_cast<jsize>(bytes.size), reinterpret_cast<const jbyte*>(bytes.data));
173
+
174
+ return array;
175
+ }
176
+
121
177
  // Functions and other non-data values become null.
122
178
  jobject toJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Value& value) {
123
179
  if (value.isBool()) return env->CallStaticObjectMethod(types.boolean, types.booleanValueOf, value.getBool());
@@ -128,6 +184,7 @@ jobject toJava(JNIEnv* env, jsi::Runtime& runtime, const jsi::Value& value) {
128
184
  jsi::Object object = value.getObject(runtime);
129
185
  if (object.isFunction(runtime)) return nullptr;
130
186
  if (object.isArray(runtime)) return arrayToJava(env, runtime, object.getArray(runtime));
187
+ if (auto bytes = bytesOf(runtime, object)) return bytesToJava(env, *bytes);
131
188
 
132
189
  return objectToJava(env, runtime, object);
133
190
  }
@@ -189,6 +246,13 @@ jsi::Value toJavaScript(JNIEnv* env, jsi::Runtime& runtime, jobject value) {
189
246
  if (env->IsInstanceOf(value, types.string)) {
190
247
  return toJavaScriptString(env, runtime, static_cast<jstring>(value));
191
248
  }
249
+ if (env->IsInstanceOf(value, types.byteArray)) {
250
+ auto array = static_cast<jbyteArray>(value);
251
+ std::vector<uint8_t> bytes(env->GetArrayLength(array));
252
+ env->GetByteArrayRegion(array, 0, static_cast<jsize>(bytes.size()), reinterpret_cast<jbyte*>(bytes.data()));
253
+
254
+ return uint8Array(runtime, std::move(bytes));
255
+ }
192
256
  if (env->IsInstanceOf(value, types.list)) return listToJavaScript(env, runtime, value);
193
257
  if (env->IsInstanceOf(value, types.map)) return mapToJavaScript(env, runtime, value);
194
258
  if (env->IsInstanceOf(value, types.objectArray)) {
@@ -364,6 +428,7 @@ extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) {
364
428
  types.number = globalClass(env, "java/lang/Number");
365
429
  types.doubleClass = globalClass(env, "java/lang/Double");
366
430
  types.string = globalClass(env, "java/lang/String");
431
+ types.byteArray = globalClass(env, "[B");
367
432
  types.list = globalClass(env, "java/util/List");
368
433
  types.arrayList = globalClass(env, "java/util/ArrayList");
369
434
  types.map = globalClass(env, "java/util/Map");
@@ -1,6 +1,5 @@
1
1
  package dev.nativue
2
2
 
3
- import android.util.Base64
4
3
  import java.io.ByteArrayOutputStream
5
4
  import java.util.UUID
6
5
  import java.util.concurrent.ConcurrentHashMap
@@ -52,13 +51,13 @@ class BlobStore private constructor() {
52
51
  /** On reload: the Blobs' JS is gone. */
53
52
  fun removeAll() = bytesById.clear()
54
53
 
55
- /** Joins `{ string }`, `{ base64 }` and `{ blob }` parts into a new blob; null if a part's blob was released. */
54
+ /** Joins `{ string }`, `{ bytes }` and `{ blob }` parts into a new blob; null if a part's blob was released. */
56
55
  fun create(parts: List<*>): Pair<String, Int>? {
57
56
  val joined = ByteArrayOutputStream()
58
57
 
59
58
  for (part in parts.filterIsInstance<Map<*, *>>()) {
60
59
  (part["string"] as? String)?.let { joined.write(it.toByteArray()) }
61
- (part["base64"] as? String)?.let { joined.write(Base64.decode(it, Base64.DEFAULT)) }
60
+ (part["bytes"] as? ByteArray)?.let { joined.write(it) }
62
61
  (part["blob"] as? Map<*, *>)?.let { joined.write(bytes(it) ?: return null) }
63
62
  }
64
63
 
@@ -453,7 +453,11 @@ class Bridge(private val activity: Activity, private val rootView: RootView) {
453
453
  "blobRead" to { arguments ->
454
454
  val (blobId, offset, size) = Triple(arguments[0] as String, (arguments[1] as Number).toInt(), (arguments[2] as Number).toInt())
455
455
  blobStore.bytes(blobId, offset, size)?.let { bytes ->
456
- if (arguments[3] == "base64") Base64.encodeToString(bytes, Base64.NO_WRAP) else String(bytes, Charsets.UTF_8)
456
+ when (arguments[3]) {
457
+ "bytes" -> bytes
458
+ "base64" -> Base64.encodeToString(bytes, Base64.NO_WRAP)
459
+ else -> String(bytes, Charsets.UTF_8)
460
+ }
457
461
  }
458
462
  },
459
463
  "blobRelease" to { arguments -> blobStore.remove(arguments[0] as String) },
@@ -29,7 +29,7 @@ class Networking(
29
29
  private val onEvent: (owner: JavaScriptRuntime?, requestId: Int, eventName: String, payload: Map<String, Any?>) -> Unit,
30
30
  ) {
31
31
  private class Request(val id: Int, val owner: JavaScriptRuntime?, query: Map<*, *>) {
32
- /** 'text', 'base64' or 'blob'. */
32
+ /** 'text', 'bytes' or 'blob'. */
33
33
  val responseType = query["responseType"] as? String ?: "text"
34
34
  val incrementalUpdates = query["incrementalUpdates"] == true
35
35
  val streamsText = incrementalUpdates && responseType == "text"
@@ -173,7 +173,7 @@ class Networking(
173
173
  /** What to send, or null for none. */
174
174
  private fun body(body: Map<*, *>): Body? {
175
175
  (body["string"] as? String)?.let { return bytesBody(it.toByteArray()) }
176
- (body["base64"] as? String)?.let { return bytesBody(Base64.decode(it, Base64.DEFAULT)) }
176
+ (body["bytes"] as? ByteArray)?.let { return bytesBody(it) }
177
177
  (body["blob"] as? Map<*, *>)?.let { return bytesBody(blobBytes(it)) }
178
178
  (body["uri"] as? String)?.let { uri -> return Body(-1) { openUri(uri) } }
179
179
 
@@ -237,9 +237,9 @@ class Networking(
237
237
  emit(request, "data", mapOf("data" to responseData(request, bytes.toByteArray(), contentType)))
238
238
  }
239
239
 
240
- /** Text, base64, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob. */
240
+ /** Text, the bytes, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob. */
241
241
  private fun responseData(request: Request, bytes: ByteArray, contentType: String?): Any = when (request.responseType) {
242
- "base64" -> Base64.encodeToString(bytes, Base64.NO_WRAP)
242
+ "bytes" -> bytes
243
243
  "blob" -> {
244
244
  val type = contentType?.substringBefore(";")?.trim().orEmpty()
245
245
  mapOf("blobId" to blobStore.store(bytes), "offset" to 0, "size" to bytes.size, "type" to type)
@@ -50,15 +50,15 @@ final class BlobStore {
50
50
  lock.withLock { dataById = [:] }
51
51
  }
52
52
 
53
- /// Joins `{ string }`, `{ base64 }` and `{ blob }` parts into a new blob.
53
+ /// Joins `{ string }`, `{ bytes }` and `{ blob }` parts into a new blob.
54
54
  func create(parts: [[String: Any]]) throws -> (blobId: String, size: Int) {
55
55
  var joined = Data()
56
56
 
57
57
  for part in parts {
58
58
  if let text = part["string"] as? String {
59
59
  joined.append(Data(text.utf8))
60
- } else if let base64 = part["base64"] as? String {
61
- joined.append(Data(base64Encoded: base64) ?? Data())
60
+ } else if let bytes = part["bytes"] as? Data {
61
+ joined.append(bytes)
62
62
  } else if let blob = part["blob"] as? [String: Any] {
63
63
  guard let data = data(of: blob) else { throw NetworkingError("The blob has been released") }
64
64
  joined.append(data)
package/ios/Bridge.swift CHANGED
@@ -671,7 +671,11 @@ final class Bridge {
671
671
  let blob = ["blobId": arguments[0], "offset": arguments[1], "size": arguments[2]]
672
672
  guard let data = blobStore.data(of: blob) else { return nil }
673
673
 
674
- return string(arguments[3]) == "base64" ? data.base64EncodedString() : String(decoding: data, as: UTF8.self)
674
+ switch string(arguments[3]) {
675
+ case "bytes": return data
676
+ case "base64": return data.base64EncodedString()
677
+ default: return String(decoding: data, as: UTF8.self)
678
+ }
675
679
  }
676
680
 
677
681
  // Not through self: the runtime may collect Blobs as it's destroyed, with the Bridge.
@@ -1,5 +1,6 @@
1
1
  // The bridge between Bridge.swift and Hermes, through JSI: the iOS side of android/src/main/cpp/bridge.cpp.
2
- // Values cross as Foundation objects. Every call happens on the JS queue.
2
+ // Values cross as Foundation objects, bytes as NSData (back as a Uint8Array). Every call happens on the
3
+ // JS queue.
3
4
  #import "NativueJavaScriptRuntime.h"
4
5
 
5
6
  #include <hermes/hermes.h>
@@ -7,6 +8,7 @@
7
8
 
8
9
  #include <functional>
9
10
  #include <memory>
11
+ #include <optional>
10
12
  #include <string>
11
13
  #include <vector>
12
14
 
@@ -38,6 +40,53 @@ NSString *toObjectiveCString(const std::string &string) {
38
40
  return [NSString stringWithUTF8String:string.c_str()] ?: @"";
39
41
  }
40
42
 
43
+ // ---------- Bytes ----------
44
+
45
+ struct Bytes {
46
+ const uint8_t *data;
47
+ size_t size;
48
+ };
49
+
50
+ // An ArrayBuffer, or what a typed array or DataView sees of one. Not copied: use before calling JS again.
51
+ std::optional<Bytes> bytesOf(jsi::Runtime &runtime, const jsi::Object &object) {
52
+ if (object.isArrayBuffer(runtime)) {
53
+ jsi::ArrayBuffer buffer = object.getArrayBuffer(runtime);
54
+
55
+ return Bytes{buffer.data(runtime), buffer.size(runtime)};
56
+ }
57
+
58
+ jsi::Value buffer = object.getProperty(runtime, "buffer");
59
+ if (!buffer.isObject() || !buffer.getObject(runtime).isArrayBuffer(runtime)) return std::nullopt;
60
+
61
+ jsi::ArrayBuffer arrayBuffer = buffer.getObject(runtime).getArrayBuffer(runtime);
62
+ auto offset = static_cast<size_t>(object.getProperty(runtime, "byteOffset").asNumber());
63
+ auto length = static_cast<size_t>(object.getProperty(runtime, "byteLength").asNumber());
64
+
65
+ return Bytes{arrayBuffer.data(runtime) + offset, length};
66
+ }
67
+
68
+ class OwnedBuffer : public jsi::MutableBuffer {
69
+ public:
70
+ explicit OwnedBuffer(std::vector<uint8_t> bytes) : bytes_(std::move(bytes)) {}
71
+
72
+ size_t size() const override {
73
+ return bytes_.size();
74
+ }
75
+
76
+ uint8_t *data() override {
77
+ return bytes_.data();
78
+ }
79
+
80
+ private:
81
+ std::vector<uint8_t> bytes_;
82
+ };
83
+
84
+ jsi::Value uint8Array(jsi::Runtime &runtime, std::vector<uint8_t> bytes) {
85
+ jsi::ArrayBuffer buffer(runtime, std::make_shared<OwnedBuffer>(std::move(bytes)));
86
+
87
+ return runtime.global().getPropertyAsFunction(runtime, "Uint8Array").callAsConstructor(runtime, buffer);
88
+ }
89
+
41
90
  // ---------- Values ----------
42
91
 
43
92
  id toObjectiveC(jsi::Runtime &runtime, const jsi::Value &value);
@@ -79,6 +128,7 @@ id toObjectiveC(jsi::Runtime &runtime, const jsi::Value &value) {
79
128
  jsi::Object object = value.getObject(runtime);
80
129
  if (object.isFunction(runtime)) return NSNull.null;
81
130
  if (object.isArray(runtime)) return arrayToObjectiveC(runtime, object.getArray(runtime));
131
+ if (auto bytes = bytesOf(runtime, object)) return [NSData dataWithBytes:bytes->data length:bytes->size];
82
132
 
83
133
  return objectToObjectiveC(runtime, object);
84
134
  }
@@ -114,6 +164,12 @@ jsi::Value toJavaScript(jsi::Runtime &runtime, id value) {
114
164
  return jsi::Value([value doubleValue]);
115
165
  }
116
166
  if ([value isKindOfClass:NSString.class]) return toJavaScriptString(runtime, value);
167
+ if ([value isKindOfClass:NSData.class]) {
168
+ NSData *data = value;
169
+ auto bytes = static_cast<const uint8_t *>(data.bytes);
170
+
171
+ return uint8Array(runtime, std::vector<uint8_t>(bytes, bytes + data.length));
172
+ }
117
173
  if ([value isKindOfClass:NSArray.class]) return arrayToJavaScript(runtime, value);
118
174
  if ([value isKindOfClass:NSDictionary.class]) return dictionaryToJavaScript(runtime, value);
119
175
 
@@ -15,7 +15,7 @@ final class Networking: NSObject, URLSessionDataDelegate {
15
15
  private final class RequestState {
16
16
  let id: Int
17
17
  weak var owner: AnyObject?
18
- /// 'text', 'base64' or 'blob'.
18
+ /// 'text', 'bytes' or 'blob'.
19
19
  let responseType: String
20
20
  let incrementalUpdates: Bool
21
21
  var mimeType: String?
@@ -168,11 +168,11 @@ final class Networking: NSObject, URLSessionDataDelegate {
168
168
  emit(state, "complete", ["error": NSNull(), "timedOut": false])
169
169
  }
170
170
 
171
- /// Text, base64, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob.
171
+ /// Text, the bytes, or for 'blob' the bytes kept in the BlobStore, described as a NativeBlob.
172
172
  private func responseData(of state: RequestState) -> Any {
173
173
  switch state.responseType {
174
- case "base64":
175
- return state.data.base64EncodedString()
174
+ case "bytes":
175
+ return state.data
176
176
  case "blob":
177
177
  let blobId = blobStore.store(state.data)
178
178
  return ["blobId": blobId, "offset": 0, "size": state.data.count, "type": state.mimeType ?? ""]
@@ -206,7 +206,7 @@ final class Networking: NSObject, URLSessionDataDelegate {
206
206
  guard let body else { return .none }
207
207
 
208
208
  if let text = body["string"] as? String { return .data(Data(text.utf8)) }
209
- if let base64 = body["base64"] as? String { return .data(Data(base64Encoded: base64) ?? Data()) }
209
+ if let bytes = body["bytes"] as? Data { return .data(bytes) }
210
210
  if let blob = body["blob"] as? [String: Any] { return .data(try blobData(blob)) }
211
211
  if let uri = body["uri"] as? String {
212
212
  let url = try fileOrDataURL(uri)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativue/core",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Vue rendering real native views on iOS and Android",
5
5
  "keywords": [
6
6
  "vue",
@@ -38,7 +38,6 @@
38
38
  "dependencies": {
39
39
  "@vitejs/plugin-vue": "^6.0.11",
40
40
  "@vue/runtime-core": "^3.5.45",
41
- "base64-js": "^1.5.1",
42
41
  "hermes-compiler": "260318099.0.8",
43
42
  "vite": "^8.3.8",
44
43
  "vue": "^3.5.45",
@@ -57,7 +56,8 @@
57
56
  "android/build.gradle.kts",
58
57
  "android/consumer-rules.pro",
59
58
  "android/nativue.settings.gradle.kts",
60
- "android/src"
59
+ "android/src",
60
+ "AGENTS.md"
61
61
  ],
62
62
  "publishConfig": {
63
63
  "access": "public"
package/src/blob.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  // Blob, File and FileReader, like the browser's. The bytes stay native (see BlobStore), so a large
2
2
  // download never crosses into JS unless it's read. They're freed when the garbage collector collects
3
3
  // the last Blob that points to them: __blobCollector gives an object whose collection frees them.
4
- import { fromByteArray, toByteArray } from 'base64-js'
5
4
  import { EventTarget, ProgressEvent } from './events'
6
5
  import { ReadableStream } from './streams'
7
6
  import type { NativeBlob, NativeBlobPart } from './types'
@@ -62,7 +61,7 @@ export class Blob {
62
61
  }
63
62
 
64
63
  async arrayBuffer(): Promise<ArrayBuffer> {
65
- return toByteArray(this.read('base64')).buffer as ArrayBuffer
64
+ return this.readBytes().buffer as ArrayBuffer
66
65
  }
67
66
 
68
67
  /** The bytes in chunks, each read from native when the stream is read. */
@@ -75,7 +74,7 @@ export class Blob {
75
74
 
76
75
  const chunk = this.slice(offset, offset + STREAM_CHUNK_SIZE)
77
76
  offset += chunk.size
78
- controller.enqueue(toByteArray(chunk.read('base64')))
77
+ controller.enqueue(chunk.readBytes())
79
78
  },
80
79
  })
81
80
  }
@@ -83,10 +82,15 @@ export class Blob {
83
82
  /** Synchronous: the bytes are in native memory. */
84
83
  read(encoding: 'text' | 'base64'): string {
85
84
  const { blobId, offset, size } = this.data
86
- const contents = native.blobRead(blobId, offset, size, encoding)
87
- if (contents === null) throw new Error('The blob has been released')
88
85
 
89
- return contents
86
+ return released(native.blobRead(blobId, offset, size, encoding))
87
+ }
88
+
89
+ /** A copy of the bytes, in a buffer of their own. */
90
+ readBytes(): Uint8Array {
91
+ const { blobId, offset, size } = this.data
92
+
93
+ return released(native.blobRead(blobId, offset, size, 'bytes'))
90
94
  }
91
95
  }
92
96
 
@@ -109,7 +113,13 @@ function nativeBlobPart(part: BlobPart): NativeBlobPart {
109
113
  if (typeof part === 'string') return { string: part }
110
114
  if (part instanceof Blob) return { blob: part.data }
111
115
 
112
- return { base64: fromByteArray(bytesOf(part)) }
116
+ return { bytes: bytesOf(part) }
117
+ }
118
+
119
+ function released<Contents>(contents: Contents | null): Contents {
120
+ if (contents === null) throw new Error('The blob has been released')
121
+
122
+ return contents
113
123
  }
114
124
 
115
125
  export function bytesOf(buffer: ArrayBuffer | ArrayBufferView): Uint8Array {
@@ -159,7 +169,7 @@ export class FileReader extends EventTarget {
159
169
  }
160
170
 
161
171
  readAsArrayBuffer(blob: Blob): void {
162
- this.startReading(blob, () => toByteArray(blob.read('base64')).buffer as ArrayBuffer)
172
+ this.startReading(blob, () => blob.readBytes().buffer as ArrayBuffer)
163
173
  }
164
174
 
165
175
  abort(): void {
package/src/types.ts CHANGED
@@ -146,8 +146,9 @@ export interface NativeModule {
146
146
 
147
147
  /** Joins the parts into new native bytes; null if a part's blob has been released. */
148
148
  blobCreate(parts: NativeBlobPart[]): { blobId: string; size: number } | null
149
- /** UTF-8 text or base64 of the bytes; null once released. */
149
+ /** UTF-8 text, base64 (for data URLs) or the bytes themselves; null once released. */
150
150
  blobRead(blobId: string, offset: number, size: number, encoding: 'text' | 'base64'): string | null
151
+ blobRead(blobId: string, offset: number, size: number, encoding: 'bytes'): Uint8Array | null
151
152
  blobRelease(blobId: string): void
152
153
  }
153
154
 
@@ -159,15 +160,15 @@ export interface NativeBlob {
159
160
  type: string
160
161
  }
161
162
 
162
- export type NativeBlobPart = { string: string } | { base64: string } | { blob: NativeBlob }
163
+ export type NativeBlobPart = { string: string } | { bytes: Uint8Array } | { blob: NativeBlob }
163
164
 
164
165
  export interface NativeRequest {
165
166
  method: string
166
167
  url: string
167
168
  headers: Record<string, string>
168
169
  body: NativeRequestBody
169
- /** 'base64' for arraybuffer responses; 'blob' keeps the bytes native. */
170
- responseType: 'text' | 'base64' | 'blob'
170
+ /** 'bytes' for arraybuffer responses; 'blob' keeps the bytes native. */
171
+ responseType: 'text' | 'bytes' | 'blob'
171
172
  /** Send the text as it arrives (incrementaldata) and download progress, not just the whole at the end. */
172
173
  incrementalUpdates: boolean
173
174
  /** In milliseconds; 0 for the platform's. */
@@ -175,11 +176,11 @@ export interface NativeRequest {
175
176
  withCredentials: boolean
176
177
  }
177
178
 
178
- // Text, bytes as base64, a file native reads by uri, or the parts of a multipart/form-data body.
179
+ // Text, bytes, a file native reads by uri, or the parts of a multipart/form-data body.
179
180
  export type NativeRequestBody =
180
181
  | null
181
182
  | { string: string }
182
- | { base64: string }
183
+ | { bytes: Uint8Array }
183
184
  | { uri: string }
184
185
  | { blob: NativeBlob }
185
186
  | { formData: NativeFormDataPart[] }
@@ -193,8 +194,8 @@ export type NativeFormDataPart =
193
194
  export interface NetworkEventPayloads {
194
195
  uploadprogress: { loaded: number; total: number }
195
196
  response: { status: number; headers: Record<string, string>; url: string }
196
- /** The whole response, once: text, base64 for 'base64', a NativeBlob for 'blob'. Not sent after incrementaldata. */
197
- data: { data: string | NativeBlob }
197
+ /** The whole response, once: text, the bytes for 'bytes', a NativeBlob for 'blob'. Not sent after incrementaldata. */
198
+ data: { data: string | Uint8Array | NativeBlob }
198
199
  incrementaldata: { text: string; loaded: number; total: number }
199
200
  progress: { loaded: number; total: number }
200
201
  /** The end: `error` set when it failed. */
package/src/xhr.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  // XMLHttpRequest and FormData, like the browser's: native runs the request, and its progress comes back as
2
2
  // events through __networkEvent. fetch and libraries like axios build on it.
3
- import { fromByteArray, toByteArray } from 'base64-js'
4
3
  import { Blob, bytesOf, File } from './blob'
5
4
  import { Event, EventTarget, ProgressEvent } from './events'
6
5
  import { URLSearchParams } from './url'
@@ -109,7 +108,7 @@ function nativeBody(body: XMLHttpRequestBody): NativeRequestBody {
109
108
  if (body instanceof URLSearchParams) return { string: body.toString() }
110
109
  if (body instanceof Blob) return { blob: body.data }
111
110
  if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
112
- return { base64: fromByteArray(bytesOf(body)) }
111
+ return { bytes: bytesOf(body) }
113
112
  }
114
113
  if ('uri' in body) return { uri: body.uri }
115
114
 
@@ -166,8 +165,8 @@ export class XMLHttpRequest extends EventTarget {
166
165
  private requestHeaders: Record<string, string> = {}
167
166
  private responseHeaders: Record<string, string> = {}
168
167
  private chosenResponseType: XMLHttpRequestResponseType = ''
169
- /** Text, or base64 for 'arraybuffer'. */
170
168
  private rawResponse = ''
169
+ private bytesResponse: Uint8Array | null = null
171
170
  private blobResponse: Blob | null = null
172
171
  // Held until the request ends, so a Blob being uploaded isn't collected (and released) meanwhile.
173
172
  private sentBody: XMLHttpRequestBody = null
@@ -312,8 +311,9 @@ export class XMLHttpRequest extends EventTarget {
312
311
  this.setReadyState(HEADERS_RECEIVED)
313
312
  }
314
313
 
315
- private receiveData(data: string | NativeBlob) {
314
+ private receiveData(data: string | Uint8Array | NativeBlob) {
316
315
  if (typeof data === 'string') this.rawResponse = data
316
+ else if (data instanceof Uint8Array) this.bytesResponse = data
317
317
  else this.blobResponse = Blob.fromNative(data)
318
318
  this.parsedResponse = undefined
319
319
  this.setReadyState(LOADING)
@@ -349,7 +349,7 @@ export class XMLHttpRequest extends EventTarget {
349
349
  : this.failed
350
350
  ? 'error'
351
351
  : 'load'
352
- const length = this.blobResponse?.size ?? this.rawResponse.length
352
+ const length = this.blobResponse?.size ?? this.bytesResponse?.length ?? this.rawResponse.length
353
353
  this.dispatchProgress(this, outcome, length, length)
354
354
  this.dispatchProgress(this, 'loadend', length, length)
355
355
  }
@@ -369,7 +369,7 @@ export class XMLHttpRequest extends EventTarget {
369
369
  }
370
370
 
371
371
  private nativeResponseType() {
372
- if (this.chosenResponseType === 'arraybuffer') return 'base64'
372
+ if (this.chosenResponseType === 'arraybuffer') return 'bytes'
373
373
  if (this.chosenResponseType === 'blob') return 'blob'
374
374
 
375
375
  return 'text'
@@ -381,7 +381,8 @@ export class XMLHttpRequest extends EventTarget {
381
381
 
382
382
  private parseResponse(): unknown {
383
383
  if (this.chosenResponseType === 'blob') return this.blobResponse
384
- if (this.chosenResponseType === 'arraybuffer') return toByteArray(this.rawResponse).buffer
384
+ if (this.chosenResponseType === 'arraybuffer')
385
+ return (this.bytesResponse ?? new Uint8Array()).buffer
385
386
 
386
387
  try {
387
388
  return JSON.parse(this.rawResponse)
@@ -396,6 +397,7 @@ export class XMLHttpRequest extends EventTarget {
396
397
  this.responseURL = ''
397
398
  this.responseHeaders = {}
398
399
  this.rawResponse = ''
400
+ this.bytesResponse = null
399
401
  this.blobResponse = null
400
402
  this.parsedResponse = undefined
401
403
  this.failed = false