Skip to content

Lightpanda: the headless browser designed for AI and automation

js: sequence arguments and members take any iterable

orezraey21849667c83d
diff --git a/src/browser/js/Local.zig b/src/browser/js/Local.zig
index 2d342c202..480b4a020 100644
--- a/src/browser/js/Local.zig
+++ b/src/browser/js/Local.zig
@@ -644,7 +644,7 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
}
if (!js_val.isArray()) {
- return error.InvalidArgument;
+ return self.iterableToSlice(ptr.child, js_val);
}
const js_arr = js_val.toArray();
const arr = try self.call_arena.alloc(ptr.child, js_arr.len());
@@ -726,6 +726,39 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
@compileError("has an unsupported parameter type: " ++ @typeName(T));
}
+// A WebIDL sequence<T> from a non-Array value: any object with an
+// @@iterator method, iterated to its end (a Set, a Map's entries, a
+// generator, a NodeList...). Anything else is InvalidArgument. An exception
+// the page's iterator throws stays pending, as JsException.
+fn iterableToSlice(self: *const Local, comptime T: type, js_val: js.Value) ![]T {
+ var it = (js_val.iterator() catch |err| return iterationError(err)) orelse return error.InvalidArgument;
+ var items: std.ArrayList(T) = .empty;
+ while (it.next() catch |err| return iterationError(err)) |item| {
+ try items.append(self.call_arena, try self.jsValueToZig(T, item));
+ }
+ return items.items;
+}
+
+// Value.iterator rethrows the page's exception (TryCatchRethrow): it's
+// pending, so report it as one; a malformed iterator is InvalidArgument.
+fn iterationError(err: anyerror) anyerror {
+ return switch (err) {
+ error.TryCatchRethrow, error.JsException => error.JsException,
+ error.OutOfMemory => err,
+ else => error.InvalidArgument,
+ };
+}
+
+// Whether `js_val` is an object with an @@iterator method, without calling
+// it (probing must not run the page's iterator).
+fn isIterable(js_val: js.Value) !bool {
+ if (!js_val.isObject()) {
+ return false;
+ }
+ const method = try js_val.toObject().getSymbol(v8.v8__Symbol__GetIterator(js_val.local.isolate.handle).?);
+ return method.isFunction();
+}
+
// Extracted so that it can be used in both jsValueToZig and in
// probeJsValueToZig. Avoids having to duplicate this logic when probing.
fn jsValueToStruct(self: *const Local, comptime T: type, js_val: js.Value) !?T {
@@ -1149,7 +1182,12 @@ fn probeJsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !Pr
}
if (!js_val.isArray()) {
- return .{ .invalid = {} };
+ // A WebIDL sequence also takes any iterable object, and
+ // union conversion picks it over a record, which js.Object
+ // stands for in unions like Headers' init (a URLSearchParams
+ // or a FormData there is a sequence of pairs). An interface
+ // variant is declared, and so probed, before the sequence.
+ return if (try isIterable(js_val)) .{ .ok = {} } else .{ .invalid = {} };
}
// This can get tricky.
diff --git a/src/browser/tests/net/headers.html b/src/browser/tests/net/headers.html
index 91cf341ec..ddcef6702 100644
--- a/src/browser/tests/net/headers.html
+++ b/src/browser/tests/net/headers.html
@@ -155,6 +155,47 @@
}
</script>
+<script id=iterable-initialization>
+// A sequence<sequence<ByteString>> takes any iterable, not only an Array:
+// a Map, a Set of pairs, a generator. A plain object is still a record.
+{
+ testing.expectEqual("1", new Headers(new Map([["a", "1"]])).get("a"));
+ testing.expectEqual("2", new Headers(new Set([["b", "2"]])).get("b"));
+ testing.expectEqual("3", new Headers((function* () { yield ["c", "3"]; })()).get("c"));
+ testing.expectEqual("4", new Request("http://example.com/", { headers: new Map([["d", "4"]]) }).headers.get("d"));
+ testing.expectEqual("5", new Response("", { headers: new Map([["e", "5"]]) }).headers.get("e"));
+ testing.expectEqual("6", new Headers({ f: "6" }).get("f"));
+ // A platform object that iterates pairs is a sequence too, not a record.
+ testing.expectEqual("7", new Headers(new URLSearchParams("g=7")).get("g"));
+ const form = new FormData();
+ form.append("h", "8");
+ testing.expectEqual("8", new Headers(form).get("h"));
+}
+
+// Each item must itself be a pair, and an exception from the page's
+// iterator propagates.
+{
+ const errorName = (fn) => {
+ try {
+ fn();
+ return null;
+ } catch (err) {
+ return err.name;
+ }
+ };
+ testing.expectEqual("TypeError", errorName(() => new Headers(new Set([5]))));
+ testing.expectEqual("TypeError", errorName(() => new Headers(new Set([["a"]]))));
+ const boom = new RangeError("boom");
+ let thrown = null;
+ try {
+ new Headers({ [Symbol.iterator]() { throw boom; } });
+ } catch (err) {
+ thrown = err;
+ }
+ testing.expectEqual(boom, thrown);
+}
+</script>
+
<script id=value-validation>
// The constructor validates names/values and normalizes values per Fetch.
{