@mikrojs/native 0.21.1-next.20260928214050 → 0.23.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.
Files changed (52) hide show
  1. package/CMakeLists.txt +21 -0
  2. package/dist/runtime/result/native-result.node-shim.d.ts +2 -0
  3. package/dist/runtime/result/native-result.node-shim.d.ts.map +1 -1
  4. package/dist/runtime/result/native-result.node-shim.js +57 -0
  5. package/dist/runtime/result/native-result.node-shim.js.map +1 -1
  6. package/dist/runtime/result/types.d.ts +33 -0
  7. package/dist/runtime/result/types.d.ts.map +1 -1
  8. package/include/mikrojs/app_store.h +16 -0
  9. package/include/mikrojs/ble_port.h +50 -0
  10. package/include/mikrojs/build_install.h +36 -0
  11. package/include/mikrojs/device_store.h +84 -0
  12. package/include/mikrojs/http_native.h +52 -0
  13. package/include/mikrojs/mikrojs.h +19 -9
  14. package/include/mikrojs/ota.h +75 -0
  15. package/include/mikrojs/ota_env.h +1 -1
  16. package/include/mikrojs/platform.h +35 -0
  17. package/include/mikrojs/private.h +13 -3
  18. package/include/mikrojs/utils.h +17 -7
  19. package/package.json +4 -4
  20. package/prebuilds/darwin-arm64/mikrojs.napi.node +0 -0
  21. package/prebuilds/linux-arm64/mikrojs.napi.node +0 -0
  22. package/prebuilds/linux-x64/mikrojs.napi.node +0 -0
  23. package/runtime/http/server-impl.ts +5 -60
  24. package/runtime/http/server.ts +0 -1
  25. package/runtime/internal.d.ts +2 -0
  26. package/runtime/modules.json +1 -1
  27. package/runtime/result/native-result.node-shim.ts +60 -0
  28. package/runtime/result/result.ts +1 -1
  29. package/runtime/result/types.ts +61 -0
  30. package/runtime/sys/sys.ts +1 -2
  31. package/runtime/sys/types.ts +5 -2
  32. package/src/mik_app_store.cpp +32 -0
  33. package/src/mik_ble.cpp +1573 -0
  34. package/src/mik_build_install.cpp +785 -0
  35. package/src/mik_config.cpp +330 -0
  36. package/src/mik_console.cpp +15 -24
  37. package/src/mik_deploy.cpp +759 -0
  38. package/src/mik_ota.cpp +1403 -0
  39. package/src/mik_ota_client_module.cpp +1142 -0
  40. package/src/mik_ota_env.cpp +318 -0
  41. package/src/mik_repl.cpp +15 -6
  42. package/src/mik_result.cpp +159 -0
  43. package/src/mik_sys.cpp +57 -52
  44. package/src/mik_test.cpp +1334 -0
  45. package/src/mik_test_supervisor.cpp +151 -0
  46. package/src/mik_udp.cpp +4 -1
  47. package/src/mik_watchdog.cpp +4 -5
  48. package/src/mik_wifi_client.cpp +1 -2
  49. package/src/mikrojs.cpp +15 -6
  50. package/src/modules.cpp +2 -1
  51. package/src/utils.cpp +1 -2
  52. package/runtime/test/test.ts +0 -686
@@ -0,0 +1,318 @@
1
+ /**
2
+ * MIKOtaEnv: the platform side of the native OTA client, built from the
3
+ * platform hooks (mikrojs/platform.h), the device store (mikrojs/device_store.h)
4
+ * and the HTTP module's native path (mikrojs/http_native.h).
5
+ *
6
+ * Every seam here is deliberately thin. The parts that are easy to get subtly
7
+ * wrong — how a mik.sys value is encoded, how the device-name pair is spelled —
8
+ * live in the portable library behind host tests (mikrojs/sys_codec.h), because
9
+ * getting them wrong means the C and JS implementations disagree about live
10
+ * device state in a way no compile catches.
11
+ */
12
+
13
+ #include <cstdarg>
14
+ #include <cstdio>
15
+ #include <cstdlib>
16
+ #include <cstring>
17
+
18
+ #include "mikrojs/device_store.h"
19
+ #include "mikrojs/http_native.h"
20
+ #include "mikrojs/mikrojs.h"
21
+ #include "mikrojs/ota.h"
22
+ #include "mikrojs/platform.h"
23
+ #include "mikrojs/private.h"
24
+ #include "mikrojs/sys_codec.h"
25
+
26
+ #define MIK_OTA_ENV_TAG "native:mikro/ota_client"
27
+ #define MIK_OTA_SYS_NS "mik.sys"
28
+
29
+ namespace {
30
+
31
+ /* One env per runtime. The OTA client is a singleton within a runtime (one
32
+ * check-in loop per device), so a file-scope record is the whole lifetime story. */
33
+ struct EnvState {
34
+ MIKOtaEnv env;
35
+ MIKRuntime* rt;
36
+ int bytecode_version;
37
+ /* The device id string the platform owns; copied so identity() can hand back
38
+ * a fixed-size field without worrying about the platform's lifetime. */
39
+ char device_id[64];
40
+ };
41
+
42
+ EnvState g_state = {};
43
+
44
+ // ── kv (mik.sys) ─────────────────────────────────────────────────────────────
45
+ // Values are the CBOR encoding of the value itself, exactly as
46
+ // native:mikro/nvs_kv writes them, so `ota.tries` means the same thing whether
47
+ // the C policy or the JS one reads it.
48
+
49
+ /* Through the device store's kv hooks, which read and write the same blobs as
50
+ * native:mikro/nvs_kv. The store keeps absent and failed apart. */
51
+ MIKOtaKvStatus kv_read_blob(const char* key, uint8_t* out, size_t* inout_len) {
52
+ const MIKDeviceStore* store = mik__device_store();
53
+ if (!store || !store->kv_get) return MIK_OTA_KV_ERROR;
54
+ return store->kv_get(MIK_OTA_SYS_NS, key, out, inout_len);
55
+ }
56
+
57
+ bool kv_write_blob(const char* key, const uint8_t* data, size_t len) {
58
+ const MIKDeviceStore* store = mik__device_store();
59
+ return store && store->kv_set && store->kv_set(MIK_OTA_SYS_NS, key, data, len);
60
+ }
61
+
62
+ MIKOtaKvStatus env_kv_get_blob(void*, const char* key, uint8_t* out, size_t* inout_len) {
63
+ return kv_read_blob(key, out, inout_len);
64
+ }
65
+
66
+ bool env_kv_set_blob(void*, const char* key, const uint8_t* data, size_t len) {
67
+ return kv_write_blob(key, data, len);
68
+ }
69
+
70
+ MIKOtaKvStatus env_kv_get_str(void*, const char* key, char* out, size_t max_len) {
71
+ uint8_t buf[320];
72
+ size_t len = sizeof(buf);
73
+ MIKOtaKvStatus status = kv_read_blob(key, buf, &len);
74
+ if (status != MIK_OTA_KV_OK) return status;
75
+ /* Stored bytes that will not decode are corruption, not absence. */
76
+ return mik__kv_decode_str(buf, len, out, max_len) ? MIK_OTA_KV_OK : MIK_OTA_KV_ERROR;
77
+ }
78
+
79
+ bool env_kv_set_str(void*, const char* key, const char* value) {
80
+ uint8_t buf[320];
81
+ size_t needed = mik__kv_encode_str(value, buf, sizeof(buf));
82
+ if (needed > sizeof(buf)) return false;
83
+ return kv_write_blob(key, buf, needed);
84
+ }
85
+
86
+ MIKOtaKvStatus env_kv_get_i32(void*, const char* key, int32_t* out) {
87
+ uint8_t buf[16];
88
+ size_t len = sizeof(buf);
89
+ MIKOtaKvStatus status = kv_read_blob(key, buf, &len);
90
+ if (status != MIK_OTA_KV_OK) return status;
91
+ return mik__kv_decode_i32(buf, len, out) ? MIK_OTA_KV_OK : MIK_OTA_KV_ERROR;
92
+ }
93
+
94
+ bool env_kv_set_i32(void*, const char* key, int32_t value) {
95
+ uint8_t buf[16];
96
+ size_t needed = mik__kv_encode_i32(value, buf, sizeof(buf));
97
+ if (needed > sizeof(buf)) return false;
98
+ return kv_write_blob(key, buf, needed);
99
+ }
100
+
101
+ bool env_kv_remove(void*, const char* key) {
102
+ const MIKDeviceStore* store = mik__device_store();
103
+ /* A key that was never there is not a failure (kv_delete returns 0): the
104
+ * client removes slots unconditionally. */
105
+ return store && store->kv_delete && store->kv_delete(MIK_OTA_SYS_NS, key) >= 0;
106
+ }
107
+
108
+ // ── HTTP ─────────────────────────────────────────────────────────────────────
109
+ // Borrowed from native:mikro/http: its task, TLS setup, inflight ceiling and
110
+ // chunk budget. A second HTTP client would double the handshake heap spike
111
+ // these devices have the least of.
112
+
113
+ void* env_http_request(void* opaque, const MIKOtaHttpRequest* req,
114
+ const MIKOtaHttpCallbacks* cbs) {
115
+ auto* state = static_cast<EnvState*>(opaque);
116
+ MIKHttpNativeRequest spec = {};
117
+ spec.url = req->url;
118
+ spec.method = req->method;
119
+ spec.header_keys = req->header_keys;
120
+ spec.header_values = req->header_values;
121
+ spec.header_count = req->header_count;
122
+ spec.body = req->body;
123
+ spec.body_len = req->body_len;
124
+ spec.timeout_ms = req->timeout_ms;
125
+
126
+ MIKHttpNativeSink sink = {};
127
+ sink.headers = cbs->headers;
128
+ sink.data = cbs->data;
129
+ sink.done = cbs->done;
130
+ sink.user_data = cbs->user_data;
131
+
132
+ uint32_t id = mik__http_start_native(state->rt, &spec, &sink);
133
+ if (id == 0) return nullptr;
134
+ /* The handle is the id, offset so it is never NULL for id 0's sake. */
135
+ return reinterpret_cast<void*>(static_cast<uintptr_t>(id));
136
+ }
137
+
138
+ void env_http_cancel(void* opaque, void* handle) {
139
+ auto* state = static_cast<EnvState*>(opaque);
140
+ mik__http_cancel_native(state->rt, static_cast<uint32_t>(reinterpret_cast<uintptr_t>(handle)));
141
+ }
142
+
143
+ // ── identity and system ──────────────────────────────────────────────────────
144
+
145
+ bool env_identity(void* opaque, MIKDeviceIdentity* out) {
146
+ auto* state = static_cast<EnvState*>(opaque);
147
+ if (!out) return false;
148
+ *out = {};
149
+ snprintf(out->device_id, sizeof(out->device_id), "%s", state->device_id);
150
+ #ifdef MIK_FW_VERSION
151
+ snprintf(out->firmware_version, sizeof(out->firmware_version), "%s", MIK_FW_VERSION);
152
+ #else
153
+ snprintf(out->firmware_version, sizeof(out->firmware_version), "0.0.0-dev");
154
+ #endif
155
+ const MIKDeviceStore* store = mik__device_store();
156
+ const char* hash = store && store->firmware_hash ? store->firmware_hash() : nullptr;
157
+ snprintf(out->firmware_hash, sizeof(out->firmware_hash), "%s", hash ? hash : "");
158
+ out->bytecode_version = state->bytecode_version;
159
+ snprintf(out->board, sizeof(out->board), "%s", mik__board_name());
160
+ return true;
161
+ }
162
+
163
+ bool env_storage_free(void*, size_t* out) {
164
+ const MIKPlatform* platform = MIK_GetPlatform();
165
+ size_t total = 0;
166
+ size_t used = 0;
167
+ if (!platform->get_fs_info || !platform->get_fs_info("user", &total, &used)) return false;
168
+ if (out) *out = total > used ? total - used : 0;
169
+ return true;
170
+ }
171
+
172
+ bool env_get_device_name(void*, int* out_rev, char* out_name, size_t name_len) {
173
+ const MIKPlatform* platform = MIK_GetPlatform();
174
+ const char* stored = platform->get_device_name ? platform->get_device_name() : nullptr;
175
+ if (!stored) return false;
176
+ /* A pair that will not parse reads as never named, matching the JS reader. */
177
+ return mik__device_name_parse(stored, out_rev, out_name, name_len);
178
+ }
179
+
180
+ void env_set_device_name(void*, int rev, const char* name) {
181
+ const MIKPlatform* platform = MIK_GetPlatform();
182
+ if (!platform->set_device_name) return;
183
+ char text[160];
184
+ size_t needed = mik__device_name_format(rev, name, text, sizeof(text));
185
+ if (needed >= sizeof(text)) return; /* an absurd name: leave the pair alone */
186
+ platform->set_device_name(text);
187
+ }
188
+
189
+ void env_restart(void*) {
190
+ const MIKPlatform* platform = MIK_GetPlatform();
191
+ if (platform->restart) platform->restart();
192
+ }
193
+
194
+ int64_t env_monotonic_ms(void*) { return MIK_GetPlatform()->get_boot_us() / 1000; }
195
+
196
+ double env_random_fraction(void*) {
197
+ /* The platform's random is uniform over the full 32-bit range; scale to [0, 1). */
198
+ return static_cast<double>(MIK_GetPlatform()->random()) / 4294967296.0;
199
+ }
200
+
201
+ void env_log(void*, int level, const char* fmt, ...) {
202
+ va_list args;
203
+ va_start(args, fmt);
204
+ char buf[320];
205
+ vsnprintf(buf, sizeof(buf), fmt, args);
206
+ va_end(args);
207
+ const MIKPlatform* platform = MIK_GetPlatform();
208
+ if (platform && platform->log) platform->log(level, MIK_OTA_ENV_TAG, "%s", buf);
209
+ }
210
+
211
+ /* Join a JS-level app path onto the runtime's fs base, the way the fs layer
212
+ * does for `readFile('/app/...')`. */
213
+ void resolve_app_path(EnvState* state, const char* leaf, char* out, size_t out_len) {
214
+ const char* root = state && state->rt
215
+ ? (state->rt->fs_root ? state->rt->fs_root : state->rt->fs_base_path)
216
+ : nullptr;
217
+ snprintf(out, out_len, "%s%s", root ? root : "", leaf);
218
+ }
219
+
220
+ char* env_read_manifest(void* opaque) {
221
+ auto* state = static_cast<EnvState*>(opaque);
222
+ char path[128];
223
+ resolve_app_path(state, "/app/mikro.app.json", path, sizeof(path));
224
+ FILE* f = fopen(path, "r");
225
+ if (!f) return nullptr;
226
+ fseek(f, 0, SEEK_END);
227
+ long size = ftell(f);
228
+ /* A manifest is a few hundred bytes of metadata plus whatever configDefaults
229
+ * carries. The bound is generous but present: this is read into RAM. */
230
+ if (size <= 0 || size > 8192) {
231
+ fclose(f);
232
+ return nullptr;
233
+ }
234
+ rewind(f);
235
+ char* text = static_cast<char*>(malloc(static_cast<size_t>(size) + 1));
236
+ if (!text) {
237
+ fclose(f);
238
+ return nullptr;
239
+ }
240
+ size_t read = fread(text, 1, static_cast<size_t>(size), f);
241
+ fclose(f);
242
+ text[read] = '\0';
243
+ return text;
244
+ }
245
+
246
+ bool env_read_app_version(void* opaque, char* out, size_t out_len) {
247
+ auto* state = static_cast<EnvState*>(opaque);
248
+ /* The live app version, the same file `ota.ts` reads as /app/package.json.
249
+ * That is a JS-level path: the fs layer joins it onto the runtime's base
250
+ * path, so reaching it from C means joining it here too. Read with stdio
251
+ * rather than through the JS fs layer, because the client runs from C and
252
+ * must not need a JSContext for a report field. */
253
+ char path[128];
254
+ resolve_app_path(state, "/app/package.json", path, sizeof(path));
255
+ FILE* f = fopen(path, "r");
256
+ if (!f) return false;
257
+ /* First 511 bytes only: enough for the small package.json a packed app
258
+ * carries. A "version" key past that, or a nested one before the top-level
259
+ * key, misreports; keep version near the top of package.json. */
260
+ char buf[512];
261
+ size_t read = fread(buf, 1, sizeof(buf) - 1, f);
262
+ fclose(f);
263
+ buf[read] = '\0';
264
+
265
+ /* Minimal scan for the top-level "version" string. A full JSON parse would
266
+ * mean pulling one in for a single field. */
267
+ const char* key = strstr(buf, "\"version\"");
268
+ if (!key) return false;
269
+ const char* colon = strchr(key, ':');
270
+ if (!colon) return false;
271
+ const char* quote = strchr(colon, '"');
272
+ if (!quote) return false;
273
+ const char* end = strchr(quote + 1, '"');
274
+ if (!end) return false;
275
+ size_t len = static_cast<size_t>(end - quote - 1);
276
+ if (len == 0 || len + 1 > out_len) return false;
277
+ memcpy(out, quote + 1, len);
278
+ out[len] = '\0';
279
+ return true;
280
+ }
281
+
282
+ } // namespace
283
+
284
+ const MIKOtaEnv* mik__ota_env_for(MIKRuntime* rt, int bytecode_version) {
285
+ g_state.rt = rt;
286
+ g_state.bytecode_version = bytecode_version;
287
+ snprintf(g_state.device_id, sizeof(g_state.device_id), "%s",
288
+ MIK_GetPlatform()->get_device_id());
289
+
290
+ MIKOtaEnv& env = g_state.env;
291
+ env = {};
292
+ env.opaque = &g_state;
293
+
294
+ env.http_request = env_http_request;
295
+ env.http_cancel = env_http_cancel;
296
+
297
+ env.kv_get_blob = env_kv_get_blob;
298
+ env.kv_set_blob = env_kv_set_blob;
299
+ env.kv_get_str = env_kv_get_str;
300
+ env.kv_set_str = env_kv_set_str;
301
+ env.kv_get_i32 = env_kv_get_i32;
302
+ env.kv_set_i32 = env_kv_set_i32;
303
+ env.kv_remove = env_kv_remove;
304
+
305
+ mik__ota_fill_install_ops(&env);
306
+
307
+ env.identity = env_identity;
308
+ env.storage_free = env_storage_free;
309
+ env.get_device_name = env_get_device_name;
310
+ env.set_device_name = env_set_device_name;
311
+ env.restart = env_restart;
312
+ env.monotonic_ms = env_monotonic_ms;
313
+ env.random_fraction = env_random_fraction;
314
+ env.log = env_log;
315
+ env.read_app_version = env_read_app_version;
316
+ env.read_manifest = env_read_manifest;
317
+ return &env;
318
+ }
package/src/mik_repl.cpp CHANGED
@@ -723,10 +723,15 @@ static bool handle_directive_impl(JSContext* ctx, const char* line, std::string&
723
723
  return true;
724
724
  }
725
725
 
726
- if (strncmp(line, "/cat ", 5) == 0) {
727
- const char* arg = line + 5;
726
+ if (strncmp(line, "/cat", 4) == 0 && (line[4] == '\0' || line[4] == ' ')) {
727
+ const char* arg = line + 4;
728
728
  while (*arg == ' ') arg++;
729
729
 
730
+ if (*arg == '\0') {
731
+ out.append("Usage: /cat FILE\n");
732
+ return true;
733
+ }
734
+
730
735
  /* Ensure path starts with / for resolve */
731
736
  char filename[PATH_MAX];
732
737
  if (arg[0] != '/') {
@@ -767,8 +772,8 @@ static bool handle_directive_impl(JSContext* ctx, const char* line, std::string&
767
772
  return true;
768
773
  }
769
774
 
770
- if (strncmp(line, "/rm ", 4) == 0) {
771
- const char* arg = line + 4;
775
+ if (strncmp(line, "/rm", 3) == 0 && (line[3] == '\0' || line[3] == ' ')) {
776
+ const char* arg = line + 3;
772
777
  while (*arg == ' ') arg++;
773
778
 
774
779
  if (*arg == '\0') {
@@ -927,8 +932,9 @@ static std::vector<uint8_t> proto_complete(JSContext* ctx, const char* partial,
927
932
  * lists the registered C modules outside the core namespace (package native
928
933
  * modules compiled in, e.g. "@mikrojs/drivers/sh8601"; empty on a generic
929
934
  * build), so the host can refuse an app importing one this firmware lacks.
930
- * `fw` is the firmware identity: the board name the build set (MIK_BOARD_NAME),
931
- * which `board` also reports. The host only auto-flashes its bundled image over
935
+ * `fw` is the firmware identity: the name the build set (MIK_BOARD_NAME). `board`
936
+ * reports the same unless `mikro flash` wrote a board's name into a generic
937
+ * image (mik__board_name). The host only auto-flashes its bundled image over
932
938
  * a device whose identity matches that image's name; omitting it reads as
933
939
  * firmware predating identity reporting, which the host treats as its own
934
940
  * bundled firmware.
@@ -1156,6 +1162,9 @@ void MIK_ProtocolClose(void) {
1156
1162
  repl_ctx = nullptr;
1157
1163
  repl_mik_rt = nullptr;
1158
1164
  s_exit_serve_loop = false;
1165
+ /* A port that restarts the app in place opens a session per app run, and
1166
+ * the next one may boot with another memReserved. */
1167
+ boot_mem_captured = false;
1159
1168
  MIK_GetPlatform()->log(MIK_LOG_INFO, TAG, "Protocol REPL exited");
1160
1169
  }
1161
1170
 
@@ -122,6 +122,18 @@ JSValue mik__result_err_named(JSContext* ctx, const char* name, const char* fmt,
122
122
  return result;
123
123
  }
124
124
 
125
+ JSValue mik__throw_panic(JSContext* ctx, const char* fmt, ...) {
126
+ va_list ap;
127
+ va_start(ap, fmt);
128
+ char msg[256];
129
+ vsnprintf(msg, sizeof(msg), fmt, ap);
130
+ va_end(ap);
131
+
132
+ JSValue error = JS_NewPlainError(ctx, "%s", msg);
133
+ define_prop(ctx, error, result_atoms(ctx).name, JS_NewString(ctx, "PanicError"));
134
+ return JS_Throw(ctx, error);
135
+ }
136
+
125
137
  JSValue MIK_ResultOk(JSContext* ctx, JSValue value) { return mik__result_ok(ctx, value); }
126
138
 
127
139
  JSValue MIK_ResultOkVoid(JSContext* ctx) { return mik__result_ok_void(ctx); }
@@ -157,6 +169,147 @@ static JSValue js_result_err(JSContext* ctx, JSValue this_val, int argc, JSValue
157
169
  return new_err_result(ctx, argc > 0 ? JS_DupValue(ctx, argv[0]) : JS_UNDEFINED);
158
170
  }
159
171
 
172
+ /* ── safe(fn, ...args) ────────────────────────────────────────── */
173
+
174
+ /* The builtins that throw on bad input. safe() calls only these, so it can't
175
+ * become a general try/catch. Looked up per call: no per-runtime cost. */
176
+ static const struct {
177
+ const char* object; /* nullptr: a global function */
178
+ const char* name;
179
+ const char* callback; /* what a function argument is called, or nullptr */
180
+ } safe_builtins[] = {
181
+ {"JSON", "parse", "reviver"},
182
+ {"JSON", "stringify", "replacer"},
183
+ {nullptr, "atob", nullptr},
184
+ {nullptr, "btoa", nullptr},
185
+ {nullptr, "decodeURI", nullptr},
186
+ {nullptr, "decodeURIComponent", nullptr},
187
+ {nullptr, "encodeURI", nullptr},
188
+ {nullptr, "encodeURIComponent", nullptr},
189
+ {nullptr, "RegExp", nullptr},
190
+ {"String", "fromCodePoint", nullptr},
191
+ };
192
+
193
+ /* ok(ret), or err(thrown) when the call threw; consumes `ret` */
194
+ static JSValue result_of_call(JSContext* ctx, JSValue ret) {
195
+ if (!JS_IsException(ret)) return mik__result_ok(ctx, ret);
196
+ JSValue thrown = JS_GetException(ctx);
197
+ if (JS_IsUncatchableError(thrown)) {
198
+ /* An interrupt, which try/catch can't catch either */
199
+ return JS_Throw(ctx, thrown);
200
+ }
201
+ return new_err_result(ctx, thrown);
202
+ }
203
+
204
+ /* Index into safe_builtins, -1 if fn isn't one, or -2 if a lookup threw */
205
+ static int safe_builtin_index(JSContext* ctx, JSValue fn) {
206
+ if (!JS_IsFunction(ctx, fn)) return -1;
207
+ JSValue global = JS_GetGlobalObject(ctx);
208
+ int found = -1;
209
+ for (int i = 0; i < (int)countof(safe_builtins) && found == -1; i++) {
210
+ const auto& b = safe_builtins[i];
211
+ JSValue holder = b.object ? JS_GetPropertyStr(ctx, global, b.object)
212
+ : JS_DupValue(ctx, global);
213
+ JSValue candidate = JS_GetPropertyStr(ctx, holder, b.name);
214
+ if (JS_IsException(holder) || JS_IsException(candidate)) {
215
+ found = -2;
216
+ } else if (JS_IsStrictEqual(ctx, candidate, fn)) {
217
+ found = i;
218
+ }
219
+ JS_FreeValue(ctx, candidate);
220
+ JS_FreeValue(ctx, holder);
221
+ }
222
+ JS_FreeValue(ctx, global);
223
+ return found;
224
+ }
225
+
226
+ /* Stands in for a reviver or replacer. Its throw becomes an Error naming the
227
+ * builtin, with the thrown value as cause, so a bug in it can't pass for bad
228
+ * input. `magic` is the builtin's index in safe_builtins. */
229
+ static JSValue safe_callback(JSContext* ctx, JSValue this_val, int argc, JSValue* argv, int magic,
230
+ JSValue* data) {
231
+ JSValue ret = JS_Call(ctx, data[0], this_val, argc, argv);
232
+ if (!JS_IsException(ret)) return ret;
233
+ JSValue thrown = JS_GetException(ctx);
234
+ if (JS_IsUncatchableError(thrown)) return JS_Throw(ctx, thrown);
235
+ const auto& b = safe_builtins[magic];
236
+ char msg[64];
237
+ snprintf(msg, sizeof(msg), "%s.%s %s threw", b.object, b.name, b.callback);
238
+ JSValue error = JS_NewError(ctx);
239
+ JS_DefinePropertyValueStr(ctx, error, "message", JS_NewString(ctx, msg), JS_PROP_C_W_E);
240
+ JS_DefinePropertyValueStr(ctx, error, "cause", thrown, JS_PROP_C_W_E);
241
+ return JS_Throw(ctx, error);
242
+ }
243
+
244
+ /* safe(fn, ...args): ok(fn(...args)), or err(thrown) when it throws. */
245
+ static JSValue js_result_safe(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {
246
+ int index = argc < 1 ? -1 : safe_builtin_index(ctx, argv[0]);
247
+ if (index == -2) return JS_EXCEPTION;
248
+ if (index < 0) {
249
+ return JS_ThrowTypeError(ctx,
250
+ "safe: expected one of JSON.parse, JSON.stringify, atob, "
251
+ "btoa, decodeURI, decodeURIComponent, encodeURI, "
252
+ "encodeURIComponent, RegExp, String.fromCodePoint");
253
+ }
254
+ /* Only JSON.parse and JSON.stringify call back into JS: the reviver or
255
+ * replacer is their second argument */
256
+ JSValue args[3];
257
+ int nargs = argc - 1;
258
+ JSValue* call_args = argv + 1;
259
+ bool takes_callback = safe_builtins[index].callback != nullptr;
260
+ if (takes_callback) {
261
+ nargs = nargs < 3 ? nargs : 3;
262
+ for (int i = 0; i < nargs; i++) {
263
+ args[i] = i == 1 && JS_IsFunction(ctx, argv[i + 1])
264
+ ? JS_NewCFunctionData(ctx, safe_callback, 2, index, 1, &argv[i + 1])
265
+ : JS_DupValue(ctx, argv[i + 1]);
266
+ if (JS_IsException(args[i])) {
267
+ while (i-- > 0) JS_FreeValue(ctx, args[i]);
268
+ return JS_EXCEPTION;
269
+ }
270
+ }
271
+ call_args = args;
272
+ }
273
+ JSValue ret = JS_Call(ctx, argv[0], JS_UNDEFINED, nargs, call_args);
274
+ if (takes_callback) {
275
+ for (int i = 0; i < nargs; i++) JS_FreeValue(ctx, args[i]);
276
+ }
277
+ return result_of_call(ctx, ret);
278
+ }
279
+
280
+ /* promise.then(ok, err): a promise of a Result that never rejects */
281
+ static JSValue result_promise(JSContext* ctx, JSValue promise) {
282
+ JSValue handlers[2] = {JS_NewCFunction(ctx, js_result_ok, "ok", 1),
283
+ JS_NewCFunction(ctx, js_result_err, "err", 1)};
284
+ JSValue then = JS_GetPropertyStr(ctx, promise, "then");
285
+ /* Without both handlers a rejection would pass through */
286
+ JSValue chained = JS_IsException(handlers[0]) || JS_IsException(handlers[1]) ||
287
+ JS_IsException(then)
288
+ ? JS_EXCEPTION
289
+ : JS_Call(ctx, then, promise, 2, handlers);
290
+ JS_FreeValue(ctx, then);
291
+ JS_FreeValue(ctx, handlers[0]);
292
+ JS_FreeValue(ctx, handlers[1]);
293
+ return chained;
294
+ }
295
+
296
+ /* tryCall(fn | promise): the outcome as a Result, for code safe() doesn't
297
+ * cover, such as a library. A promise, or a fn that returns one, gives a
298
+ * promise of a Result instead. */
299
+ static JSValue js_result_try_call(JSContext* ctx, JSValue this_val, int argc, JSValue* argv) {
300
+ if (argc > 0 && JS_IsPromise(argv[0])) return result_promise(ctx, argv[0]);
301
+ if (argc < 1 || !JS_IsFunction(ctx, argv[0])) {
302
+ return JS_ThrowTypeError(ctx, "tryCall: expected a function or a promise");
303
+ }
304
+ JSValue ret = JS_Call(ctx, argv[0], JS_UNDEFINED, 0, nullptr);
305
+ if (JS_IsPromise(ret)) {
306
+ JSValue chained = result_promise(ctx, ret);
307
+ JS_FreeValue(ctx, ret);
308
+ return chained;
309
+ }
310
+ return result_of_call(ctx, ret);
311
+ }
312
+
160
313
  /* ── Prototype method helpers ───────────────────────────────────── */
161
314
 
162
315
  static inline bool result_is_ok(JSContext* ctx, JSValue this_val) {
@@ -338,6 +491,10 @@ static void mik__result_install_methods(JSContext* ctx, JSValue proto) {
338
491
  static int mik__result_module_init(JSContext* ctx, JSModuleDef* m) {
339
492
  JS_SetModuleExport(ctx, m, "ok", JS_NewCFunction(ctx, js_result_ok, "ok", 1));
340
493
  JS_SetModuleExport(ctx, m, "err", JS_NewCFunction(ctx, js_result_err, "err", 1));
494
+ JS_SetModuleExport(ctx, m, "safe",
495
+ JS_NewCFunction(ctx, js_result_safe, "safe", 1));
496
+ JS_SetModuleExport(ctx, m, "tryCall",
497
+ JS_NewCFunction(ctx, js_result_try_call, "tryCall", 1));
341
498
  return 0;
342
499
  }
343
500
 
@@ -370,5 +527,7 @@ JSModuleDef* mik__result_init(JSContext* ctx) {
370
527
  if (!m) return nullptr;
371
528
  JS_AddModuleExport(ctx, m, "ok");
372
529
  JS_AddModuleExport(ctx, m, "err");
530
+ JS_AddModuleExport(ctx, m, "safe");
531
+ JS_AddModuleExport(ctx, m, "tryCall");
373
532
  return m;
374
533
  }