Full Code of lightpanda-io/browser for AI

main 4cdc24326af3 cached
697 files
4.6 MB
1.2M tokens
101 symbols
2 requests
Download .txt
Showing preview only (4,944K chars total). Download the full file or copy to clipboard to get everything.
Repository: lightpanda-io/browser
Branch: main
Commit: 4cdc24326af3
Files: 697
Total size: 4.6 MB

Directory structure:
gitextract_h4l2nhcz/

├── .github/
│   ├── actions/
│   │   └── install/
│   │       └── action.yml
│   └── workflows/
│       ├── cla.yml
│       ├── e2e-integration-test.yml
│       ├── e2e-test.yml
│       ├── nightly.yml
│       ├── wpt.yml
│       └── zig-test.yml
├── .gitignore
├── CLA.md
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── LICENSING.md
├── Makefile
├── README.md
├── build.zig
├── build.zig.zon
├── flake.nix
└── src/
    ├── App.zig
    ├── ArenaPool.zig
    ├── Config.zig
    ├── Notification.zig
    ├── SemanticTree.zig
    ├── Server.zig
    ├── Sighandler.zig
    ├── TestHTTPServer.zig
    ├── browser/
    │   ├── Browser.zig
    │   ├── EventManager.zig
    │   ├── Factory.zig
    │   ├── HttpClient.zig
    │   ├── Mime.zig
    │   ├── Page.zig
    │   ├── ScriptManager.zig
    │   ├── Session.zig
    │   ├── URL.zig
    │   ├── actions.zig
    │   ├── color.zig
    │   ├── css/
    │   │   ├── Parser.zig
    │   │   └── Tokenizer.zig
    │   ├── dump.zig
    │   ├── interactive.zig
    │   ├── js/
    │   │   ├── Array.zig
    │   │   ├── BigInt.zig
    │   │   ├── Caller.zig
    │   │   ├── Context.zig
    │   │   ├── Env.zig
    │   │   ├── Function.zig
    │   │   ├── HandleScope.zig
    │   │   ├── Inspector.zig
    │   │   ├── Integer.zig
    │   │   ├── Isolate.zig
    │   │   ├── Local.zig
    │   │   ├── Module.zig
    │   │   ├── Number.zig
    │   │   ├── Object.zig
    │   │   ├── Origin.zig
    │   │   ├── Platform.zig
    │   │   ├── Private.zig
    │   │   ├── Promise.zig
    │   │   ├── PromiseRejection.zig
    │   │   ├── PromiseResolver.zig
    │   │   ├── Scheduler.zig
    │   │   ├── Snapshot.zig
    │   │   ├── String.zig
    │   │   ├── TaggedOpaque.zig
    │   │   ├── TryCatch.zig
    │   │   ├── Value.zig
    │   │   ├── bridge.zig
    │   │   └── js.zig
    │   ├── markdown.zig
    │   ├── parser/
    │   │   ├── Parser.zig
    │   │   └── html5ever.zig
    │   ├── reflect.zig
    │   ├── structured_data.zig
    │   ├── tests/
    │   │   ├── animation/
    │   │   │   └── animation.html
    │   │   ├── blob.html
    │   │   ├── canvas/
    │   │   │   ├── canvas_rendering_context_2d.html
    │   │   │   ├── offscreen_canvas.html
    │   │   │   └── webgl_rendering_context.html
    │   │   ├── cdata/
    │   │   │   ├── cdata_section.html
    │   │   │   ├── character_data.html
    │   │   │   ├── comment.html
    │   │   │   ├── data.html
    │   │   │   └── text.html
    │   │   ├── cdp/
    │   │   │   ├── dom1.html
    │   │   │   ├── dom2.html
    │   │   │   ├── dom3.html
    │   │   │   ├── registry1.html
    │   │   │   ├── registry2.html
    │   │   │   └── registry3.html
    │   │   ├── collections/
    │   │   │   └── radio_node_list.html
    │   │   ├── console/
    │   │   │   └── console.html
    │   │   ├── crypto.html
    │   │   ├── css/
    │   │   │   ├── font_face.html
    │   │   │   ├── font_face_set.html
    │   │   │   ├── media_query_list.html
    │   │   │   └── stylesheet.html
    │   │   ├── css.html
    │   │   ├── custom_elements/
    │   │   │   ├── attribute_changed.html
    │   │   │   ├── built_in.html
    │   │   │   ├── connected.html
    │   │   │   ├── connected_from_parser.html
    │   │   │   ├── constructor.html
    │   │   │   ├── disconnected.html
    │   │   │   ├── registry.html
    │   │   │   ├── throw_on_dynamic_markup_insertion.html
    │   │   │   └── upgrade.html
    │   │   ├── document/
    │   │   │   ├── adopt_import.html
    │   │   │   ├── all_collection.html
    │   │   │   ├── children.html
    │   │   │   ├── collections.html
    │   │   │   ├── create_element.html
    │   │   │   ├── create_element_ns.html
    │   │   │   ├── document-title.html
    │   │   │   ├── document.html
    │   │   │   ├── element_from_point.html
    │   │   │   ├── focus.html
    │   │   │   ├── get_element_by_id.html
    │   │   │   ├── get_elements_by_class_name-multiple.html
    │   │   │   ├── get_elements_by_class_name.html
    │   │   │   ├── get_elements_by_name.html
    │   │   │   ├── get_elements_by_tag_name-wildcard.html
    │   │   │   ├── get_elements_by_tag_name.html
    │   │   │   ├── insert_adjacent_element.html
    │   │   │   ├── insert_adjacent_html.html
    │   │   │   ├── insert_adjacent_text.html
    │   │   │   ├── query_selector.html
    │   │   │   ├── query_selector_all.html
    │   │   │   ├── query_selector_attributes.html
    │   │   │   ├── query_selector_edge_cases.html
    │   │   │   ├── query_selector_not.html
    │   │   │   ├── replace_children.html
    │   │   │   └── write.html
    │   │   ├── document_fragment/
    │   │   │   ├── document_fragment.html
    │   │   │   └── insertion.html
    │   │   ├── document_head_body.html
    │   │   ├── domexception.html
    │   │   ├── domimplementation.html
    │   │   ├── domparser.html
    │   │   ├── element/
    │   │   │   ├── append.html
    │   │   │   ├── attributes.html
    │   │   │   ├── bounding_rect.html
    │   │   │   ├── class_list.html
    │   │   │   ├── closest.html
    │   │   │   ├── css_style_properties.html
    │   │   │   ├── dataset.html
    │   │   │   ├── duplicate_ids.html
    │   │   │   ├── element.html
    │   │   │   ├── get_elements_by_class_name.html
    │   │   │   ├── get_elements_by_tag_name.html
    │   │   │   ├── get_elements_by_tag_name_ns.html
    │   │   │   ├── html/
    │   │   │   │   ├── anchor.html
    │   │   │   │   ├── button.html
    │   │   │   │   ├── details.html
    │   │   │   │   ├── dialog.html
    │   │   │   │   ├── event_listeners.html
    │   │   │   │   ├── fieldset.html
    │   │   │   │   ├── form.html
    │   │   │   │   ├── htmlelement-props.html
    │   │   │   │   ├── image.html
    │   │   │   │   ├── input-attrs.html
    │   │   │   │   ├── input.html
    │   │   │   │   ├── input_click.html
    │   │   │   │   ├── input_radio.html
    │   │   │   │   ├── label.html
    │   │   │   │   ├── li.html
    │   │   │   │   ├── link.html
    │   │   │   │   ├── media.html
    │   │   │   │   ├── ol.html
    │   │   │   │   ├── optgroup.html
    │   │   │   │   ├── option.html
    │   │   │   │   ├── picture.html
    │   │   │   │   ├── quote.html
    │   │   │   │   ├── script/
    │   │   │   │   │   ├── async_text.html
    │   │   │   │   │   ├── dynamic.html
    │   │   │   │   │   ├── dynamic1.js
    │   │   │   │   │   ├── dynamic2.js
    │   │   │   │   │   ├── dynamic_inline.html
    │   │   │   │   │   ├── empty.js
    │   │   │   │   │   ├── order.html
    │   │   │   │   │   ├── order.js
    │   │   │   │   │   ├── order_async.js
    │   │   │   │   │   ├── order_defer.js
    │   │   │   │   │   └── script.html
    │   │   │   │   ├── select.html
    │   │   │   │   ├── slot.html
    │   │   │   │   ├── style.html
    │   │   │   │   ├── tablecell.html
    │   │   │   │   ├── template.html
    │   │   │   │   ├── textarea.html
    │   │   │   │   ├── time.html
    │   │   │   │   └── track.html
    │   │   │   ├── inner.html
    │   │   │   ├── inner.js
    │   │   │   ├── matches.html
    │   │   │   ├── outer.html
    │   │   │   ├── position.html
    │   │   │   ├── pseudo_classes.html
    │   │   │   ├── query_selector.html
    │   │   │   ├── query_selector_all.html
    │   │   │   ├── query_selector_scope.html
    │   │   │   ├── remove.html
    │   │   │   ├── replace_with.html
    │   │   │   ├── selector_invalid.html
    │   │   │   ├── styles.html
    │   │   │   └── svg/
    │   │   │       └── svg.html
    │   │   ├── encoding/
    │   │   │   ├── text_decoder.html
    │   │   │   └── text_encoder.html
    │   │   ├── event/
    │   │   │   ├── abort_controller.html
    │   │   │   ├── composition.html
    │   │   │   ├── custom_event.html
    │   │   │   ├── error.html
    │   │   │   ├── focus.html
    │   │   │   ├── keyboard.html
    │   │   │   ├── listener_removal.html
    │   │   │   ├── message.html
    │   │   │   ├── message_multiple_listeners.html
    │   │   │   ├── mouse.html
    │   │   │   ├── pointer.html
    │   │   │   ├── promise_rejection.html
    │   │   │   ├── report_error.html
    │   │   │   ├── text.html
    │   │   │   ├── ui.html
    │   │   │   └── wheel.html
    │   │   ├── events.html
    │   │   ├── file.html
    │   │   ├── file_reader.html
    │   │   ├── frames/
    │   │   │   ├── frames.html
    │   │   │   ├── post_message.html
    │   │   │   ├── support/
    │   │   │   │   ├── after_link.html
    │   │   │   │   ├── message_receiver.html
    │   │   │   │   ├── page.html
    │   │   │   │   ├── sub 1.html
    │   │   │   │   ├── sub2.html
    │   │   │   │   └── with_link.html
    │   │   │   └── target.html
    │   │   ├── history.html
    │   │   ├── history_after_nav.skip.html
    │   │   ├── image_data.html
    │   │   ├── integration/
    │   │   │   └── custom_element_composition.html
    │   │   ├── intersection_observer/
    │   │   │   ├── basic.html
    │   │   │   ├── disconnect.html
    │   │   │   ├── multiple_targets.html
    │   │   │   └── unobserve.html
    │   │   ├── legacy/
    │   │   │   ├── browser.html
    │   │   │   ├── crypto.html
    │   │   │   ├── css.html
    │   │   │   ├── cssom/
    │   │   │   │   ├── css_style_declaration.html
    │   │   │   │   └── css_stylesheet.html
    │   │   │   ├── dom/
    │   │   │   │   ├── animation.html
    │   │   │   │   ├── attribute.html
    │   │   │   │   ├── character_data.html
    │   │   │   │   ├── comment.html
    │   │   │   │   ├── document.html
    │   │   │   │   ├── document_fragment.html
    │   │   │   │   ├── document_type.html
    │   │   │   │   ├── dom_parser.html
    │   │   │   │   ├── element.html
    │   │   │   │   ├── event_target.html
    │   │   │   │   ├── exceptions.html
    │   │   │   │   ├── html_collection.html
    │   │   │   │   ├── implementation.html
    │   │   │   │   ├── intersection_observer.html
    │   │   │   │   ├── named_node_map.html
    │   │   │   │   ├── node_filter.html
    │   │   │   │   ├── node_list.html
    │   │   │   │   ├── node_owner.html
    │   │   │   │   ├── performance.html
    │   │   │   │   ├── performance_observer.html
    │   │   │   │   ├── processing_instruction.html
    │   │   │   │   ├── range.html
    │   │   │   │   ├── text.html
    │   │   │   │   └── token_list.html
    │   │   │   ├── encoding/
    │   │   │   │   ├── decoder.html
    │   │   │   │   └── encoder.html
    │   │   │   ├── events/
    │   │   │   │   ├── composition.html
    │   │   │   │   ├── custom.html
    │   │   │   │   ├── event.html
    │   │   │   │   ├── keyboard.html
    │   │   │   │   └── mouse.html
    │   │   │   ├── fetch/
    │   │   │   │   ├── fetch.html
    │   │   │   │   ├── headers.html
    │   │   │   │   ├── request.html
    │   │   │   │   └── response.html
    │   │   │   ├── file/
    │   │   │   │   ├── blob.html
    │   │   │   │   └── file.html
    │   │   │   ├── html/
    │   │   │   │   ├── abort_controller.html
    │   │   │   │   ├── canvas.html
    │   │   │   │   ├── dataset.html
    │   │   │   │   ├── document.html
    │   │   │   │   ├── element.html
    │   │   │   │   ├── error_event.html
    │   │   │   │   ├── history/
    │   │   │   │   │   ├── history.html
    │   │   │   │   │   ├── history2.html
    │   │   │   │   │   └── history_after_nav.skip.html
    │   │   │   │   ├── image.html
    │   │   │   │   ├── input.html
    │   │   │   │   ├── link.html
    │   │   │   │   ├── location.html
    │   │   │   │   ├── navigation/
    │   │   │   │   │   ├── navigation.html
    │   │   │   │   │   ├── navigation_after_nav.skip.html
    │   │   │   │   │   └── navigation_currententrychange.html
    │   │   │   │   ├── navigator.html
    │   │   │   │   ├── screen.html
    │   │   │   │   ├── script/
    │   │   │   │   │   ├── dynamic_import.html
    │   │   │   │   │   ├── import.html
    │   │   │   │   │   ├── import.js
    │   │   │   │   │   ├── import2.js
    │   │   │   │   │   ├── importmap.html
    │   │   │   │   │   ├── inline_defer.html
    │   │   │   │   │   ├── inline_defer.js
    │   │   │   │   │   ├── order.html
    │   │   │   │   │   ├── order.js
    │   │   │   │   │   ├── order_async.js
    │   │   │   │   │   ├── order_defer.js
    │   │   │   │   │   └── script.html
    │   │   │   │   ├── select.html
    │   │   │   │   ├── slot.html
    │   │   │   │   ├── style.html
    │   │   │   │   └── svg.html
    │   │   │   ├── storage/
    │   │   │   │   └── local_storage.html
    │   │   │   ├── streams/
    │   │   │   │   └── readable_stream.html
    │   │   │   ├── testing.js
    │   │   │   ├── url/
    │   │   │   │   ├── url.html
    │   │   │   │   └── url_search_params.html
    │   │   │   ├── window/
    │   │   │   │   ├── frames.html
    │   │   │   │   └── window.html
    │   │   │   ├── xhr/
    │   │   │   │   ├── form_data.html
    │   │   │   │   ├── progress_event.html
    │   │   │   │   └── xhr.html
    │   │   │   └── xmlserializer.html
    │   │   ├── mcp_actions.html
    │   │   ├── media/
    │   │   │   ├── mediaerror.html
    │   │   │   └── vttcue.html
    │   │   ├── message_channel.html
    │   │   ├── mutation_observer/
    │   │   │   ├── attribute_filter.html
    │   │   │   ├── character_data.html
    │   │   │   ├── childlist.html
    │   │   │   ├── multiple_observers.html
    │   │   │   ├── mutation_observer.html
    │   │   │   ├── mutations_during_callback.html
    │   │   │   ├── observe_multiple_targets.html
    │   │   │   ├── reobserve_same_target.html
    │   │   │   └── subtree.html
    │   │   ├── navigator/
    │   │   │   └── navigator.html
    │   │   ├── net/
    │   │   │   ├── fetch.html
    │   │   │   ├── form_data.html
    │   │   │   ├── headers.html
    │   │   │   ├── request.html
    │   │   │   ├── response.html
    │   │   │   ├── url_search_params.html
    │   │   │   └── xhr.html
    │   │   ├── node/
    │   │   │   ├── adoption.html
    │   │   │   ├── append_child.html
    │   │   │   ├── base_uri.html
    │   │   │   ├── child_nodes.html
    │   │   │   ├── clone_node.html
    │   │   │   ├── compare_document_position.html
    │   │   │   ├── insert_before.html
    │   │   │   ├── is_connected.html
    │   │   │   ├── is_equal_node.html
    │   │   │   ├── node.html
    │   │   │   ├── node_iterator.html
    │   │   │   ├── normalize.html
    │   │   │   ├── noscript_serialization.html
    │   │   │   ├── owner.html
    │   │   │   ├── remove_child.html
    │   │   │   ├── replace_child.html
    │   │   │   ├── text_content.html
    │   │   │   ├── tree.html
    │   │   │   └── tree_walker.html
    │   │   ├── page/
    │   │   │   ├── blob.html
    │   │   │   ├── load_event.html
    │   │   │   ├── meta.html
    │   │   │   ├── mod1.js
    │   │   │   ├── module.html
    │   │   │   └── modules/
    │   │   │       ├── base.js
    │   │   │       ├── circular-a.js
    │   │   │       ├── circular-b.js
    │   │   │       ├── dynamic-chain-a.js
    │   │   │       ├── dynamic-chain-b.js
    │   │   │       ├── dynamic-chain-c.js
    │   │   │       ├── dynamic-circular-x.js
    │   │   │       ├── dynamic-circular-y.js
    │   │   │       ├── importer.js
    │   │   │       ├── mixed-circular-dynamic.js
    │   │   │       ├── mixed-circular-static.js
    │   │   │       ├── re-exporter.js
    │   │   │       ├── self_async.js
    │   │   │       ├── shared.js
    │   │   │       ├── syntax-error.js
    │   │   │       ├── test-404.js
    │   │   │       └── test-syntax-error.js
    │   │   ├── performance.html
    │   │   ├── performance_observer/
    │   │   │   └── performance_observer.html
    │   │   ├── polyfill/
    │   │   │   └── webcomponents.html
    │   │   ├── processing_instruction.html
    │   │   ├── range.html
    │   │   ├── range_mutations.html
    │   │   ├── selection.html
    │   │   ├── shadowroot/
    │   │   │   ├── basic.html
    │   │   │   ├── custom_elements.html
    │   │   │   ├── dom_traversal.html
    │   │   │   ├── dump.html
    │   │   │   ├── edge_cases.html
    │   │   │   ├── events.html
    │   │   │   ├── id_collision.html
    │   │   │   ├── id_management.html
    │   │   │   ├── innerHTML_spec.html
    │   │   │   └── scoping.html
    │   │   ├── storage.html
    │   │   ├── streams/
    │   │   │   ├── readable_stream.html
    │   │   │   ├── text_decoder_stream.html
    │   │   │   └── transform_stream.html
    │   │   ├── support/
    │   │   │   └── history.html
    │   │   ├── testing.js
    │   │   ├── url.html
    │   │   ├── window/
    │   │   │   ├── body_onload1.html
    │   │   │   ├── body_onload2.html
    │   │   │   ├── body_onload3.html
    │   │   │   ├── location.html
    │   │   │   ├── named_access.html
    │   │   │   ├── onerror.html
    │   │   │   ├── report_error.html
    │   │   │   ├── screen.html
    │   │   │   ├── scroll.html
    │   │   │   ├── stubs.html
    │   │   │   ├── timers.html
    │   │   │   ├── visual_viewport.html
    │   │   │   ├── window.html
    │   │   │   └── window_event.html
    │   │   ├── window_scroll.html
    │   │   └── xmlserializer.html
    │   └── webapi/
    │       ├── AbortController.zig
    │       ├── AbortSignal.zig
    │       ├── AbstractRange.zig
    │       ├── Blob.zig
    │       ├── CData.zig
    │       ├── CSS.zig
    │       ├── Console.zig
    │       ├── Crypto.zig
    │       ├── CustomElementDefinition.zig
    │       ├── CustomElementRegistry.zig
    │       ├── DOMException.zig
    │       ├── DOMImplementation.zig
    │       ├── DOMNodeIterator.zig
    │       ├── DOMParser.zig
    │       ├── DOMRect.zig
    │       ├── DOMTreeWalker.zig
    │       ├── Document.zig
    │       ├── DocumentFragment.zig
    │       ├── DocumentType.zig
    │       ├── Element.zig
    │       ├── Event.zig
    │       ├── EventTarget.zig
    │       ├── File.zig
    │       ├── FileList.zig
    │       ├── FileReader.zig
    │       ├── HTMLDocument.zig
    │       ├── History.zig
    │       ├── IdleDeadline.zig
    │       ├── ImageData.zig
    │       ├── IntersectionObserver.zig
    │       ├── KeyValueList.zig
    │       ├── Location.zig
    │       ├── MessageChannel.zig
    │       ├── MessagePort.zig
    │       ├── MutationObserver.zig
    │       ├── Navigator.zig
    │       ├── Node.zig
    │       ├── NodeFilter.zig
    │       ├── Performance.zig
    │       ├── PerformanceObserver.zig
    │       ├── Permissions.zig
    │       ├── PluginArray.zig
    │       ├── Range.zig
    │       ├── ResizeObserver.zig
    │       ├── Screen.zig
    │       ├── Selection.zig
    │       ├── ShadowRoot.zig
    │       ├── StorageManager.zig
    │       ├── SubtleCrypto.zig
    │       ├── TreeWalker.zig
    │       ├── URL.zig
    │       ├── VisualViewport.zig
    │       ├── Window.zig
    │       ├── XMLDocument.zig
    │       ├── XMLSerializer.zig
    │       ├── animation/
    │       │   └── Animation.zig
    │       ├── canvas/
    │       │   ├── CanvasRenderingContext2D.zig
    │       │   ├── OffscreenCanvas.zig
    │       │   ├── OffscreenCanvasRenderingContext2D.zig
    │       │   └── WebGLRenderingContext.zig
    │       ├── cdata/
    │       │   ├── CDATASection.zig
    │       │   ├── Comment.zig
    │       │   ├── ProcessingInstruction.zig
    │       │   └── Text.zig
    │       ├── children.zig
    │       ├── collections/
    │       │   ├── ChildNodes.zig
    │       │   ├── DOMTokenList.zig
    │       │   ├── HTMLAllCollection.zig
    │       │   ├── HTMLCollection.zig
    │       │   ├── HTMLFormControlsCollection.zig
    │       │   ├── HTMLOptionsCollection.zig
    │       │   ├── NodeList.zig
    │       │   ├── RadioNodeList.zig
    │       │   ├── iterator.zig
    │       │   └── node_live.zig
    │       ├── collections.zig
    │       ├── css/
    │       │   ├── CSSRule.zig
    │       │   ├── CSSRuleList.zig
    │       │   ├── CSSStyleDeclaration.zig
    │       │   ├── CSSStyleProperties.zig
    │       │   ├── CSSStyleRule.zig
    │       │   ├── CSSStyleSheet.zig
    │       │   ├── FontFace.zig
    │       │   ├── FontFaceSet.zig
    │       │   ├── MediaQueryList.zig
    │       │   └── StyleSheetList.zig
    │       ├── element/
    │       │   ├── Attribute.zig
    │       │   ├── DOMStringMap.zig
    │       │   ├── Html.zig
    │       │   ├── Svg.zig
    │       │   ├── html/
    │       │   │   ├── Anchor.zig
    │       │   │   ├── Area.zig
    │       │   │   ├── Audio.zig
    │       │   │   ├── BR.zig
    │       │   │   ├── Base.zig
    │       │   │   ├── Body.zig
    │       │   │   ├── Button.zig
    │       │   │   ├── Canvas.zig
    │       │   │   ├── Custom.zig
    │       │   │   ├── DList.zig
    │       │   │   ├── Data.zig
    │       │   │   ├── DataList.zig
    │       │   │   ├── Details.zig
    │       │   │   ├── Dialog.zig
    │       │   │   ├── Directory.zig
    │       │   │   ├── Div.zig
    │       │   │   ├── Embed.zig
    │       │   │   ├── FieldSet.zig
    │       │   │   ├── Font.zig
    │       │   │   ├── Form.zig
    │       │   │   ├── Generic.zig
    │       │   │   ├── HR.zig
    │       │   │   ├── Head.zig
    │       │   │   ├── Heading.zig
    │       │   │   ├── Html.zig
    │       │   │   ├── IFrame.zig
    │       │   │   ├── Image.zig
    │       │   │   ├── Input.zig
    │       │   │   ├── LI.zig
    │       │   │   ├── Label.zig
    │       │   │   ├── Legend.zig
    │       │   │   ├── Link.zig
    │       │   │   ├── Map.zig
    │       │   │   ├── Media.zig
    │       │   │   ├── Meta.zig
    │       │   │   ├── Meter.zig
    │       │   │   ├── Mod.zig
    │       │   │   ├── OL.zig
    │       │   │   ├── Object.zig
    │       │   │   ├── OptGroup.zig
    │       │   │   ├── Option.zig
    │       │   │   ├── Output.zig
    │       │   │   ├── Paragraph.zig
    │       │   │   ├── Param.zig
    │       │   │   ├── Picture.zig
    │       │   │   ├── Pre.zig
    │       │   │   ├── Progress.zig
    │       │   │   ├── Quote.zig
    │       │   │   ├── Script.zig
    │       │   │   ├── Select.zig
    │       │   │   ├── Slot.zig
    │       │   │   ├── Source.zig
    │       │   │   ├── Span.zig
    │       │   │   ├── Style.zig
    │       │   │   ├── Table.zig
    │       │   │   ├── TableCaption.zig
    │       │   │   ├── TableCell.zig
    │       │   │   ├── TableCol.zig
    │       │   │   ├── TableRow.zig
    │       │   │   ├── TableSection.zig
    │       │   │   ├── Template.zig
    │       │   │   ├── TextArea.zig
    │       │   │   ├── Time.zig
    │       │   │   ├── Title.zig
    │       │   │   ├── Track.zig
    │       │   │   ├── UL.zig
    │       │   │   ├── Unknown.zig
    │       │   │   └── Video.zig
    │       │   └── svg/
    │       │       ├── Generic.zig
    │       │       └── Rect.zig
    │       ├── encoding/
    │       │   ├── TextDecoder.zig
    │       │   ├── TextDecoderStream.zig
    │       │   ├── TextEncoder.zig
    │       │   └── TextEncoderStream.zig
    │       ├── event/
    │       │   ├── CompositionEvent.zig
    │       │   ├── CustomEvent.zig
    │       │   ├── ErrorEvent.zig
    │       │   ├── FocusEvent.zig
    │       │   ├── InputEvent.zig
    │       │   ├── KeyboardEvent.zig
    │       │   ├── MessageEvent.zig
    │       │   ├── MouseEvent.zig
    │       │   ├── NavigationCurrentEntryChangeEvent.zig
    │       │   ├── PageTransitionEvent.zig
    │       │   ├── PointerEvent.zig
    │       │   ├── PopStateEvent.zig
    │       │   ├── ProgressEvent.zig
    │       │   ├── PromiseRejectionEvent.zig
    │       │   ├── TextEvent.zig
    │       │   ├── UIEvent.zig
    │       │   └── WheelEvent.zig
    │       ├── global_event_handlers.zig
    │       ├── media/
    │       │   ├── MediaError.zig
    │       │   ├── TextTrackCue.zig
    │       │   └── VTTCue.zig
    │       ├── navigation/
    │       │   ├── Navigation.zig
    │       │   ├── NavigationActivation.zig
    │       │   ├── NavigationHistoryEntry.zig
    │       │   └── root.zig
    │       ├── net/
    │       │   ├── Fetch.zig
    │       │   ├── FormData.zig
    │       │   ├── Headers.zig
    │       │   ├── Request.zig
    │       │   ├── Response.zig
    │       │   ├── URLSearchParams.zig
    │       │   ├── XMLHttpRequest.zig
    │       │   └── XMLHttpRequestEventTarget.zig
    │       ├── selector/
    │       │   ├── List.zig
    │       │   ├── Parser.zig
    │       │   └── Selector.zig
    │       ├── storage/
    │       │   ├── Cookie.zig
    │       │   └── storage.zig
    │       └── streams/
    │           ├── ReadableStream.zig
    │           ├── ReadableStreamDefaultController.zig
    │           ├── ReadableStreamDefaultReader.zig
    │           ├── TransformStream.zig
    │           ├── WritableStream.zig
    │           ├── WritableStreamDefaultController.zig
    │           └── WritableStreamDefaultWriter.zig
    ├── cdp/
    │   ├── AXNode.zig
    │   ├── Node.zig
    │   ├── cdp.zig
    │   ├── domains/
    │   │   ├── accessibility.zig
    │   │   ├── browser.zig
    │   │   ├── css.zig
    │   │   ├── dom.zig
    │   │   ├── emulation.zig
    │   │   ├── fetch.zig
    │   │   ├── input.zig
    │   │   ├── inspector.zig
    │   │   ├── log.zig
    │   │   ├── lp.zig
    │   │   ├── network.zig
    │   │   ├── page.zig
    │   │   ├── performance.zig
    │   │   ├── runtime.zig
    │   │   ├── security.zig
    │   │   ├── storage.zig
    │   │   └── target.zig
    │   ├── id.zig
    │   └── testing.zig
    ├── crash_handler.zig
    ├── crypto.zig
    ├── data/
    │   ├── public_suffix_list.zig
    │   └── public_suffix_list_gen.go
    ├── datetime.zig
    ├── html5ever/
    │   ├── Cargo.toml
    │   ├── lib.rs
    │   ├── sink.rs
    │   └── types.rs
    ├── id.zig
    ├── lightpanda.zig
    ├── log.zig
    ├── main.zig
    ├── main_legacy_test.zig
    ├── main_snapshot_creator.zig
    ├── mcp/
    │   ├── Server.zig
    │   ├── protocol.zig
    │   ├── resources.zig
    │   ├── router.zig
    │   └── tools.zig
    ├── mcp.zig
    ├── network/
    │   ├── Robots.zig
    │   ├── Runtime.zig
    │   ├── WebBotAuth.zig
    │   ├── http.zig
    │   └── websocket.zig
    ├── slab.zig
    ├── string.zig
    ├── sys/
    │   └── libcurl.zig
    ├── telemetry/
    │   ├── lightpanda.zig
    │   └── telemetry.zig
    ├── test_runner.zig
    └── testing.zig

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/actions/install/action.yml
================================================
name: "Browsercore install"
description: "Install deps for the project browsercore"

inputs:
  arch:
    description: 'CPU arch used to select the v8 lib'
    required: false
    default: 'x86_64'
  os:
    description: 'OS used to select the v8 lib'
    required: false
    default: 'linux'
  zig-v8:
    description: 'zig v8 version to install'
    required: false
    default: 'v0.3.4'
  v8:
    description: 'v8 version to install'
    required: false
    default: '14.0.365.4'
  cache-dir:
    description: 'cache dir to use'
    required: false
    default: '~/.cache'
  debug:
    description: 'enable v8 pre-built debug version, only available for linux x86_64'
    required: false
    default: 'false'

runs:
  using: "composite"

  steps:
    - name: Install apt deps
      if: ${{ inputs.os == 'linux' }}
      shell: bash
      run: |
        sudo apt-get update
        sudo apt-get install -y wget xz-utils ca-certificates clang make git

    # Zig version used from the `minimum_zig_version` field in build.zig.zon
    - uses: mlugg/setup-zig@v2

    # Rust Toolchain for html5ever
    - uses: dtolnay/rust-toolchain@stable

    - name: Cache v8
      id: cache-v8
      uses: actions/cache@v5
      env:
        cache-name: cache-v8
      with:
        path: ${{ inputs.cache-dir }}/v8
        key: libc_v8_${{ inputs.v8 }}_${{ inputs.os }}_${{ inputs.arch }}_${{ inputs.zig-v8 }}${{inputs.debug == 'true' && '_debug' || '' }}.a

    - if: ${{ steps.cache-v8.outputs.cache-hit != 'true' }}
      shell: bash
      run: |
        mkdir -p ${{ inputs.cache-dir }}/v8

        wget -O ${{ inputs.cache-dir }}/v8/libc_v8.a https://github.com/lightpanda-io/zig-v8-fork/releases/download/${{ inputs.zig-v8 }}/libc_v8_${{ inputs.v8 }}_${{ inputs.os }}_${{ inputs.arch }}${{inputs.debug == 'true' && '_debug' || '' }}.a

    - name: install v8
      shell: bash
      run: |
        mkdir -p v8
        ln -s ${{ inputs.cache-dir }}/v8/libc_v8.a v8/libc_v8${{inputs.debug == 'true' && '_debug' || '' }}.a


================================================
FILE: .github/workflows/cla.yml
================================================
name: "CLA Assistant"
on:
  issue_comment:
    types: [created]
  pull_request_target:
    types: [opened,closed,synchronize]

permissions:
  actions: write
  contents: read
  pull-requests: write
  statuses: write

jobs:
  CLAAssistant:
    runs-on: ubuntu-latest
    timeout-minutes: 5

    steps:
      - name: "CLA Assistant"
        if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
        uses: contributor-assistant/github-action@v2.6.1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PERSONAL_ACCESS_TOKEN: ${{ secrets.CLA_GH_PAT }}
        with:
          path-to-signatures: 'signatures/browser/version1/cla.json'
          path-to-document: 'https://github.com/lightpanda-io/browser/blob/main/CLA.md'
          # branch should not be protected
          branch: 'main'
          allowlist: krichprollsch,francisbouvier,katie-lpd,sjorsdonkers,bornlex

          remote-organization-name: lightpanda-io
          remote-repository-name: cla


================================================
FILE: .github/workflows/e2e-integration-test.yml
================================================
name: e2e-integration-test

env:
  LIGHTPANDA_DISABLE_TELEMETRY: true

on:
  schedule:
    - cron: "4 4 * * *"
  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  zig-build-release:
    name: zig build release

    runs-on: ubuntu-latest
    timeout-minutes: 15

    # Don't run the CI with draft PR.
    if: github.event.pull_request.draft == false

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install

      - name: zig build release
        run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64 -Dgit_commit=$(git rev-parse --short ${{ github.sha }})

      - name: upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: lightpanda-build-release
          path: |
            zig-out/bin/lightpanda
          retention-days: 1

  demo-scripts:
    name: demo-integration-scripts
    needs: zig-build-release

    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - uses: actions/checkout@v6
        with:
          repository: 'lightpanda-io/demo'
          fetch-depth: 0

      - run: npm install

      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: lightpanda-build-release

      - run: chmod a+x ./lightpanda

      - name: run end to end integration tests
        run: |
          ./lightpanda serve --log_level error & echo $! > LPD.pid
          go run integration/main.go
          kill `cat LPD.pid`


================================================
FILE: .github/workflows/e2e-test.yml
================================================
name: e2e-test

env:
  AWS_ACCESS_KEY_ID: ${{ vars.LPD_PERF_AWS_ACCESS_KEY_ID }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.LPD_PERF_AWS_SECRET_ACCESS_KEY }}
  AWS_BUCKET: ${{ vars.LPD_PERF_AWS_BUCKET }}
  AWS_REGION: ${{ vars.LPD_PERF_AWS_REGION }}
  LIGHTPANDA_DISABLE_TELEMETRY: true

on:
  push:
    branches: [main]
    paths:
      - ".github/**"
      - "src/**"
      - "build.zig"
      - "build.zig.zon"

  pull_request:

    # By default GH trigger on types opened, synchronize and reopened.
    # see https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request
    # Since we skip the job when the PR is in draft state, we want to force CI
    # running when the PR is marked ready_for_review w/o other change.
    # see https://github.com/orgs/community/discussions/25722#discussioncomment-3248917
    types: [opened, synchronize, reopened, ready_for_review]

    paths:
      - ".github/**"
      - "src/**"
      - "build.zig"
      - "build.zig.zon"

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  zig-build-release:
    name: zig build release

    runs-on: ubuntu-latest
    timeout-minutes: 15

    # Don't run the CI with draft PR.
    if: github.event.pull_request.draft == false

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install

      - name: zig build release
        run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64 -Dgit_commit=$(git rev-parse --short ${{ github.sha }})

      - name: upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: lightpanda-build-release
          path: |
            zig-out/bin/lightpanda
          retention-days: 1

  demo-scripts:
    name: demo-scripts
    needs: zig-build-release

    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - uses: actions/checkout@v6
        with:
          repository: 'lightpanda-io/demo'
          fetch-depth: 0

      - run: npm install

      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: lightpanda-build-release

      - run: chmod a+x ./lightpanda

      - name: run end to end tests
        run: |
          ./lightpanda serve & echo $! > LPD.pid
          go run runner/main.go
          kill `cat LPD.pid`

      - name: build proxy
        run: |
          cd proxy
          go build

      - name: run end to end tests through proxy
        run: |
          ./proxy/proxy & echo $! > PROXY.id
          ./lightpanda serve --http_proxy 'http://127.0.0.1:3000' & echo $! > LPD.pid
          go run runner/main.go
          kill `cat LPD.pid` `cat PROXY.id`

      - name: run request interception through proxy
        run: |
          export PROXY_USERNAME=username PROXY_PASSWORD=password
          ./proxy/proxy & echo $! > PROXY.id
          ./lightpanda serve & echo $! > LPD.pid
          URL=https://demo-browser.lightpanda.io/campfire-commerce/ node puppeteer/proxy_auth.js
          BASE_URL=https://demo-browser.lightpanda.io/ node playwright/proxy_auth.js
          kill `cat LPD.pid` `cat PROXY.id`

  # e2e tests w/ web-bot-auth configuration on.
  wba-demo-scripts:
    name: wba-demo-scripts
    needs: zig-build-release

    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - uses: actions/checkout@v6
        with:
          repository: 'lightpanda-io/demo'
          fetch-depth: 0

      - run: npm install

      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: lightpanda-build-release

      - run: chmod a+x ./lightpanda

      - run: echo "${{ secrets.WBA_PRIVATE_KEY_PEM }}" > private_key.pem

      - name: run end to end tests
        run: |
          ./lightpanda serve \
            --web_bot_auth_key_file private_key.pem \
            --web_bot_auth_keyid ${{ vars.WBA_KEY_ID }} \
            --web_bot_auth_domain ${{ vars.WBA_DOMAIN }} \
            & echo $! > LPD.pid
          go run runner/main.go
          kill `cat LPD.pid`

      - name: build proxy
        run: |
          cd proxy
          go build

      - name: run end to end tests through proxy
        run: |
          ./proxy/proxy & echo $! > PROXY.id
          ./lightpanda serve \
            --web_bot_auth_key_file private_key.pem \
            --web_bot_auth_keyid ${{ vars.WBA_KEY_ID }} \
            --web_bot_auth_domain ${{ vars.WBA_DOMAIN }} \
            --http_proxy 'http://127.0.0.1:3000' \
            & echo $! > LPD.pid
          go run runner/main.go
          kill `cat LPD.pid` `cat PROXY.id`

      - name: run request interception through proxy
        run: |
          export PROXY_USERNAME=username PROXY_PASSWORD=password
          ./proxy/proxy & echo $! > PROXY.id
          ./lightpanda serve & echo $! > LPD.pid
          URL=https://demo-browser.lightpanda.io/campfire-commerce/ node puppeteer/proxy_auth.js
          BASE_URL=https://demo-browser.lightpanda.io/ node playwright/proxy_auth.js
          kill `cat LPD.pid` `cat PROXY.id`

  wba-test:
    name: wba-test
    needs: zig-build-release

    runs-on: ubuntu-latest
    timeout-minutes: 5

    steps:
      - uses: actions/checkout@v6
        with:
          repository: 'lightpanda-io/demo'
          fetch-depth: 0

      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: lightpanda-build-release

      - run: chmod a+x ./lightpanda

      # force a wakup of the auth server before requesting it w/ the test itself
      - run: curl https://${{ vars.WBA_DOMAIN }}

      - name: run wba test
        shell: bash
        run: |
          node webbotauth/validator.js &
          VALIDATOR_PID=$!
          sleep 5

          exec 3<<< "${{ secrets.WBA_PRIVATE_KEY_PEM }}"

          ./lightpanda fetch --dump http://127.0.0.1:8989/ \
            --web_bot_auth_key_file /proc/self/fd/3 \
            --web_bot_auth_keyid ${{ vars.WBA_KEY_ID }} \
            --web_bot_auth_domain ${{ vars.WBA_DOMAIN }}

          wait $VALIDATOR_PID
          exec 3>&-

  cdp-and-hyperfine-bench:
    name: cdp-and-hyperfine-bench
    needs: zig-build-release

    env:
      MAX_VmHWM: 28000 # 28MB (KB)
      MAX_CG_PEAK: 8000 # 8MB (KB)
      MAX_AVG_DURATION: 17

      # How to give cgroups access to the user actions-runner on the host:
      # $ sudo apt install cgroup-tools
      # $ sudo chmod o+w /sys/fs/cgroup/cgroup.procs
      # $ sudo mkdir -p /sys/fs/cgroup/actions-runner
      # $ sudo chown -R actions-runner:actions-runner /sys/fs/cgroup/actions-runner
      CG_ROOT: /sys/fs/cgroup
      CG: actions-runner/lpd_${{ github.run_id }}_${{ github.run_attempt }}

    # use a self host runner.
    runs-on: lpd-bench-hetzner
    timeout-minutes: 15

    steps:
      - uses: actions/checkout@v6
        with:
          repository: 'lightpanda-io/demo'
          fetch-depth: 0

      - run: npm install

      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: lightpanda-build-release

      - run: chmod a+x ./lightpanda

      - name: start http
        run: |
          go run ws/main.go & echo $! > WS.pid
          sleep 2

      - name: run lightpanda in cgroup
        run: |
          if [ ! -f /sys/fs/cgroup/cgroup.controllers ]; then
            echo "cgroup v2 not available: /sys/fs/cgroup/cgroup.controllers missing"
            exit 1
          fi

          mkdir -p $CG_ROOT/$CG
          cgexec -g memory:$CG ./lightpanda serve & echo $! > LPD.pid

          sleep 2

      - name: run puppeteer
        run: |
          RUNS=100 npm run bench-puppeteer-cdp > puppeteer.out || exit 1
          cat /proc/`cat LPD.pid`/status |grep VmHWM|grep -oP '\d+' > LPD.VmHWM
          kill `cat LPD.pid`

          PID=$(cat LPD.pid)
          while kill -0 $PID 2>/dev/null; do
            sleep 1
          done
          if [ ! -f $CG_ROOT/$CG/memory.peak ]; then
            echo "memory.peak not available in $CG"
            exit 1
          fi
          cat $CG_ROOT/$CG/memory.peak > LPD.cg_mem_peak

      - name: puppeteer result
        run: cat puppeteer.out

      - name: cgroup memory regression
        run: |
          PEAK_BYTES=$(cat LPD.cg_mem_peak)
          PEAK_KB=$((PEAK_BYTES / 1024))
          echo "memory.peak_bytes=$PEAK_BYTES"
          echo "memory.peak_kb=$PEAK_KB"
          test "$PEAK_KB" -le "$MAX_CG_PEAK"

      - name: virtual memory regression
        run: |
          export LPD_VmHWM=`cat LPD.VmHWM`
          echo "Peak resident set size: $LPD_VmHWM"
          test "$LPD_VmHWM" -le "$MAX_VmHWM"

      - name: cleanup cgroup
        run: rmdir $CG_ROOT/$CG

      - name: duration regression
        run: |
          export PUPPETEER_AVG_DURATION=`cat puppeteer.out|grep 'avg run'|sed 's/avg run duration (ms) //'`
          echo "puppeteer avg duration: $PUPPETEER_AVG_DURATION"
          test "$PUPPETEER_AVG_DURATION" -le "$MAX_AVG_DURATION"

      - name: json output
        run: |
          export AVG_DURATION=`cat puppeteer.out|grep 'avg run'|sed 's/avg run duration (ms) //'`
          export TOTAL_DURATION=`cat puppeteer.out|grep 'total duration'|sed 's/total duration (ms) //'`
          export LPD_VmHWM=`cat LPD.VmHWM`
          export LPD_CG_PEAK_KB=$(( $(cat LPD.cg_mem_peak) / 1024 ))
          echo "{\"duration_total\":${TOTAL_DURATION},\"duration_avg\":${AVG_DURATION},\"mem_peak\":${LPD_VmHWM},\"cg_mem_peak\":${LPD_CG_PEAK_KB}}" > bench.json
          cat bench.json

      - name: run hyperfine
        run: |
          hyperfine --export-json=hyperfine.json --warmup 3 --runs 20 --shell=none "./lightpanda --dump http://127.0.0.1:1234/campfire-commerce/"

      - name: stop http
        run: kill `cat WS.pid`

      - name: write commit
        run: |
          echo "${{github.sha}}" > commit.txt

      - name: upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: bench-results
          path: |
            bench.json
            hyperfine.json
            commit.txt
          retention-days: 10


  perf-fmt:
    name: perf-fmt
    needs: cdp-and-hyperfine-bench

    # Don't execute on PR
    if: github.event_name != 'pull_request'

    runs-on: ubuntu-latest
    timeout-minutes: 15

    container:
      image: ghcr.io/lightpanda-io/perf-fmt:latest
      credentials:
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    steps:
      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: bench-results

      - name: format and send json result
        run: /perf-fmt cdp ${{ github.sha }} bench.json

      - name: format and send json result
        run: /perf-fmt hyperfine ${{ github.sha }} hyperfine.json

  browser-fetch:
    name: browser fetch
    needs: zig-build-release

    runs-on: ubuntu-latest

    steps:
      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: lightpanda-build-release

      - run: chmod a+x ./lightpanda

      - run: ./lightpanda fetch https://demo-browser.lightpanda.io/campfire-commerce/


================================================
FILE: .github/workflows/nightly.yml
================================================
name: nightly build

env:
  AWS_ACCESS_KEY_ID: ${{ vars.NIGHTLY_BUILD_AWS_ACCESS_ID }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.NIGHTLY_BUILD_AWS_SECRET_ACCESS_KEY }}
  AWS_BUCKET: ${{ vars.NIGHTLY_BUILD_AWS_BUCKET }}
  AWS_REGION: ${{ vars.NIGHTLY_BUILD_AWS_REGION }}

  RELEASE: ${{ github.ref_type == 'tag' && github.ref_name || 'nightly' }}
  GIT_VERSION_FLAG: ${{ github.ref_type == 'tag' && format('-Dgit_version={0}', github.ref_name) || '' }}

on:
  push:
    tags:
      - '*'
  schedule:
    - cron: "2 2 * * *"

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

permissions:
  contents: write

jobs:
  build-linux-x86_64:
    env:
      ARCH: x86_64
      OS: linux

    runs-on: ubuntu-22.04
    timeout-minutes: 20

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install
        with:
          os: ${{env.OS}}
          arch: ${{env.ARCH}}

      - name: v8 snapshot
        run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin

      - name: zig build
        run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64 -Dgit_commit=$(git rev-parse --short ${{ github.sha }}) ${{ env.GIT_VERSION_FLAG }}

      - name: Rename binary
        run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: upload on s3
        run: |
          export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
          aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: Upload the build
        uses: ncipollo/release-action@v1
        with:
          allowUpdates: true
          artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
          tag: ${{ env.RELEASE }}
          makeLatest: true

  build-linux-aarch64:
    env:
      ARCH: aarch64
      OS: linux

    runs-on: ubuntu-22.04-arm
    timeout-minutes: 20

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install
        with:
          os: ${{env.OS}}
          arch: ${{env.ARCH}}

      - name: v8 snapshot
        run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin

      - name: zig build
        run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=generic -Dgit_commit=$(git rev-parse --short ${{ github.sha }}) ${{ env.GIT_VERSION_FLAG }}

      - name: Rename binary
        run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: upload on s3
        run: |
          export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
          aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: Upload the build
        uses: ncipollo/release-action@v1
        with:
          allowUpdates: true
          artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
          tag: ${{ env.RELEASE }}
          makeLatest: true

  build-macos-aarch64:
    env:
      ARCH: aarch64
      OS: macos

    # macos-14 runs on arm CPU. see
    # https://github.com/actions/runner-images?tab=readme-ov-file
    runs-on: macos-14
    timeout-minutes: 20

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install
        with:
          os: ${{env.OS}}
          arch: ${{env.ARCH}}

      - name: v8 snapshot
        run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin

      - name: zig build
        run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dgit_commit=$(git rev-parse --short ${{ github.sha }}) ${{ env.GIT_VERSION_FLAG }}

      - name: Rename binary
        run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: upload on s3
        run: |
          export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
          aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: Upload the build
        uses: ncipollo/release-action@v1
        with:
          allowUpdates: true
          artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
          tag: ${{ env.RELEASE }}
          makeLatest: true

  build-macos-x86_64:
    env:
      ARCH: x86_64
      OS: macos

    runs-on: macos-14-large
    timeout-minutes: 20

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install
        with:
          os: ${{env.OS}}
          arch: ${{env.ARCH}}

      - name: v8 snapshot
        run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin

      - name: zig build
        run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dgit_commit=$(git rev-parse --short ${{ github.sha }}) ${{ env.GIT_VERSION_FLAG }}

      - name: Rename binary
        run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: upload on s3
        run: |
          export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
          aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}

      - name: Upload the build
        uses: ncipollo/release-action@v1
        with:
          allowUpdates: true
          artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
          tag: ${{ env.RELEASE }}
          makeLatest: true


================================================
FILE: .github/workflows/wpt.yml
================================================
name: wpt

env:
  AWS_ACCESS_KEY_ID: ${{ vars.LPD_PERF_AWS_ACCESS_KEY_ID }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.LPD_PERF_AWS_SECRET_ACCESS_KEY }}
  AWS_BUCKET: ${{ vars.LPD_PERF_AWS_BUCKET }}
  AWS_REGION: ${{ vars.LPD_PERF_AWS_REGION }}
  AWS_CF_DISTRIBUTION: ${{ vars.AWS_CF_DISTRIBUTION }}
  LIGHTPANDA_DISABLE_TELEMETRY: true

on:
  schedule:
    - cron: "21 2 * * *"

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  wpt-build-release:
    name: zig build release

    env:
      ARCH: aarch64
      OS: linux

    runs-on: ubuntu-24.04-arm
    timeout-minutes: 20

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install
        with:
          os: ${{env.OS}}
          arch: ${{env.ARCH}}

      - name: v8 snapshot
        run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin

      - name: zig build release
        run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=generic -Dgit_commit=$(git rev-parse --short ${{ github.sha }})

      - name: upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: lightpanda-build-release
          path: |
            zig-out/bin/lightpanda
          retention-days: 1

  wpt-build-runner:
    name: build wpt runner

    runs-on: ubuntu-24.04-arm
    timeout-minutes: 15

    steps:
      - uses: actions/checkout@v6
        with:
          repository: 'lightpanda-io/demo'
          fetch-depth: 0

      - run: |
          cd ./wptrunner
          CGO_ENABLED=0 go build

      - name: upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: wptrunner
          path: |
            wptrunner/wptrunner
          retention-days: 1

  run-wpt:
    name: web platform tests json output
    needs:
      - wpt-build-release
      - wpt-build-runner

    # use a self host runner.
    runs-on: lpd-wpt-aws
    timeout-minutes: 600

    steps:
      - uses: actions/checkout@v6
        with:
          ref: fork
          repository: 'lightpanda-io/wpt'
          fetch-depth: 0

      # The hosts are configured manually on the self host runner.
      # - name: create custom hosts
      #   run: ./wpt make-hosts-file | sudo tee -a /etc/hosts

      - name: generate manifest
        run: ./wpt manifest

      - name: download lightpanda release
        uses: actions/download-artifact@v8
        with:
          name: lightpanda-build-release

      - run: chmod a+x ./lightpanda

      - name: download wptrunner
        uses: actions/download-artifact@v8
        with:
          name: wptrunner

      - run: chmod a+x ./wptrunner

      - name: run test with json output
        run: |
          ./wpt serve 2> /dev/null & echo $! > WPT.pid
          sleep 20s
          ./wptrunner -lpd-path ./lightpanda -json -concurrency 5 -pool 5 --mem-limit 400 > wpt.json
          kill `cat WPT.pid`

      - name: write commit
        run: |
          echo "${{github.sha}}" > commit.txt

      - name: upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: wpt-results
          path: |
            wpt.json
            commit.txt
          retention-days: 10

  perf-fmt:
    name: perf-fmt
    needs: run-wpt

    runs-on: ubuntu-latest
    timeout-minutes: 15

    container:
      image: ghcr.io/lightpanda-io/perf-fmt:latest
      credentials:
       username: ${{ github.actor }}
       password: ${{ secrets.GITHUB_TOKEN }}

    steps:
      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: wpt-results

      - name: format and send json result
        run: /perf-fmt wpt ${{ github.sha }} wpt.json


================================================
FILE: .github/workflows/zig-test.yml
================================================
name: zig-test

env:
  AWS_ACCESS_KEY_ID: ${{ vars.LPD_PERF_AWS_ACCESS_KEY_ID }}
  AWS_SECRET_ACCESS_KEY: ${{ secrets.LPD_PERF_AWS_SECRET_ACCESS_KEY }}
  AWS_BUCKET: ${{ vars.LPD_PERF_AWS_BUCKET }}
  AWS_REGION: ${{ vars.LPD_PERF_AWS_REGION }}
  LIGHTPANDA_DISABLE_TELEMETRY: true

on:
  push:
    branches: [main]
    paths:
      - ".github/**"
      - "src/**"
      - "build.zig"
      - "build.zig.zon"

  pull_request:
    # By default GH trigger on types opened, synchronize and reopened.
    # see https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request
    # Since we skip the job when the PR is in draft state, we want to force CI
    # running when the PR is marked ready_for_review w/o other change.
    # see https://github.com/orgs/community/discussions/25722#discussioncomment-3248917
    types: [opened, synchronize, reopened, ready_for_review]

    paths:
      - ".github/**"
      - "src/**"
      - "build.zig"
      - "build.zig.zon"

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  zig-fmt:
    name: zig fmt

    runs-on: ubuntu-latest
    timeout-minutes: 15

    if: github.event.pull_request.draft == false

    steps:
      - uses: actions/checkout@v6

      # Zig version used from the `minimum_zig_version` field in build.zig.zon
      - uses: mlugg/setup-zig@v2

      - name: Run zig fmt
        id: fmt
        run: |
          zig fmt --check ./*.zig ./**/*.zig 2> zig-fmt.err > zig-fmt.err2 || echo "Failed"
          delimiter="$(openssl rand -hex 8)"
          echo "zig_fmt_errs<<${delimiter}" >> "${GITHUB_OUTPUT}"

          if [ -s zig-fmt.err ]; then
            echo "// The following errors occurred:" >> "${GITHUB_OUTPUT}"
            cat zig-fmt.err >> "${GITHUB_OUTPUT}"
          fi

          if [ -s zig-fmt.err2 ]; then
            echo "// The following files were not formatted:" >> "${GITHUB_OUTPUT}"
            cat zig-fmt.err2 >> "${GITHUB_OUTPUT}"
          fi

          echo "${delimiter}" >> "${GITHUB_OUTPUT}"

      - name: Fail the job
        if: steps.fmt.outputs.zig_fmt_errs != ''
        run: exit 1

  zig-test-debug:
    name: zig test using v8 in debug mode

    runs-on: ubuntu-latest
    timeout-minutes: 15

    if: github.event.pull_request.draft == false

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install
        with:
          debug: true

      - name: zig build test
        run: zig build -Dprebuilt_v8_path=v8/libc_v8_debug.a -Dtsan=true test

  zig-test-release:
    name: zig test

    runs-on: ubuntu-latest
    timeout-minutes: 15

    if: github.event.pull_request.draft == false

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: ./.github/actions/install

      - name: zig build test
        run: METRICS=true zig build -Dprebuilt_v8_path=v8/libc_v8.a test > bench.json

      - name: write commit
        run: |
          echo "${{github.sha}}" > commit.txt

      - name: upload artifact
        uses: actions/upload-artifact@v7
        with:
          name: bench-results
          path: |
            bench.json
            commit.txt
          retention-days: 10

  bench-fmt:
    name: perf-fmt
    needs: zig-test-release

    runs-on: ubuntu-latest
    timeout-minutes: 15

    if: github.event_name != 'pull_request'

    container:
      image: ghcr.io/lightpanda-io/perf-fmt:latest
      credentials:
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    steps:
      - name: download artifact
        uses: actions/download-artifact@v8
        with:
          name: bench-results

      - name: format and send json result
        run: /perf-fmt bench-browser ${{ github.sha }} bench.json


================================================
FILE: .gitignore
================================================
/.zig-cache/
/.lp-cache/
zig-out
lightpanda.id
/src/html5ever/target/
src/snapshot.bin


================================================
FILE: CLA.md
================================================
# Lightpanda (Selecy SAS) Grant and Contributor License Agreement (“Agreement”)

This agreement is based on the Apache Software Foundation Contributor License
Agreement. (v r190612)

Thank you for your interest in software projects stewarded by Lightpanda
(Selecy SAS) (“Lightpanda”). In order to clarify the intellectual property
license granted with Contributions from any person or entity, Lightpanda must
have a Contributor License Agreement (CLA) on file that has been agreed to by
each Contributor, indicating agreement to the license terms below. This license
is for your protection as a Contributor as well as the protection of Lightpanda
and its users; it does not change your rights to use your own Contributions for
any other purpose. This Agreement allows an individual to contribute to
Lightpanda on that individual’s own behalf, or an entity (the “Corporation”) to
submit Contributions to Lightpanda, to authorize Contributions submitted by its
designated employees to Lightpanda, and to grant copyright and patent licenses
thereto.

You accept and agree to the following terms and conditions for Your present and
future Contributions submitted to Lightpanda. Except for the license granted
herein to Lightpanda and recipients of software distributed by Lightpanda, You
reserve all right, title, and interest in and to Your Contributions.

1. Definitions. “You” (or “Your”) shall mean the copyright owner or legal
   entity authorized by the copyright owner that is making this Agreement with
   Lightpanda. For legal entities, the entity making a Contribution and all
   other entities that control, are controlled by, or are under common control
   with that entity are considered to be a single Contributor. For the purposes
   of this definition, “control” means (i) the power, direct or indirect, to
   cause the direction or management of such entity, whether by contract or
   otherwise, or (ii) ownership of fifty percent (50%) or more of the
   outstanding shares, or (iii) beneficial ownership of such entity.
   “Contribution” shall mean any work, as well as any modifications or
   additions to an existing work, that is intentionally submitted by You to
   Lightpanda for inclusion in, or documentation of, any of the products owned
   or managed by Lightpanda (the “Work”). For the purposes of this definition,
   “submitted” means any form of electronic, verbal, or written communication
   sent to Lightpanda or its representatives, including but not limited to
   communication on electronic mailing lists, source code control systems (such
   as GitHub), and issue tracking systems that are managed by, or on behalf of,
   Lightpanda for the purpose of discussing and improving the Work, but
   excluding communication that is conspicuously marked or otherwise designated
   in writing by You as “Not a Contribution.”

2. Grant of Copyright License. Subject to the terms and conditions of this
   Agreement, You hereby grant to Lightpanda and to recipients of software
   distributed by Lightpanda a perpetual, worldwide, non-exclusive, no-charge,
   royalty-free, irrevocable copyright license to reproduce, prepare derivative
   works of, publicly display, publicly perform, sublicense, and distribute
   Your Contributions and such derivative works.

3. Grant of Patent License. Subject to the terms and conditions of this
   Agreement, You hereby grant to Lightpanda and to recipients of software
   distributed by Lightpanda a perpetual, worldwide, non-exclusive, no-charge,
   royalty-free, irrevocable (except as stated in this section) patent license
   to make, have made, use, offer to sell, sell, import, and otherwise transfer
   the Work, where such license applies only to those patent claims licensable
   by You that are necessarily infringed by Your Contribution(s) alone or by
   combination of Your Contribution(s) with the Work to which such
   Contribution(s) were submitted. If any entity institutes patent litigation
   against You or any other entity (including a cross-claim or counterclaim in
   a lawsuit) alleging that your Contribution, or the Work to which you have
   contributed, constitutes direct or contributory patent infringement, then
   any patent licenses granted to that entity under this Agreement for that
   Contribution or Work shall terminate as of the date such litigation is
   filed.

4. You represent that You are legally entitled to grant the above license. If
   You are an individual, and if Your employer(s) has rights to intellectual
   property that you create that includes Your Contributions, you represent
   that You have received permission to make Contributions on behalf of that
   employer, or that Your employer has waived such rights for your
   Contributions to Lightpanda. If You are a Corporation, any individual who
   makes a contribution from an account associated with You will be considered
   authorized to Contribute on Your behalf.

5. You represent that each of Your Contributions is Your original creation (see
   section 7 for submissions on behalf of others).

6. You are not expected to provide support for Your Contributions,except to the
   extent You desire to provide support. You may provide support for free, for
   a fee, or not at all. Unless required by applicable law or agreed to in
   writing, You provide Your Contributions on an “AS IS” BASIS, WITHOUT
   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including,
   without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
   MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.

7. Should You wish to submit work that is not Your original creation, You may
   submit it to Lightpanda separately from any Contribution, identifying the
   complete details of its source and of any license or other restriction
   (including, but not limited to, related patents, trademarks, and license
   agreements) of which you are personally aware, and conspicuously marking the
   work as “Submitted on behalf of a third-party: [named here]”.


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing

Lightpanda accepts pull requests through GitHub.

You have to sign our [CLA](CLA.md) during your first pull request process
otherwise we're not able to accept your contributions.

The process signature uses the [CLA assistant
lite](https://github.com/marketplace/actions/cla-assistant-lite). You can see
an example of the process in [#303](https://github.com/lightpanda-io/browser/pull/303).


================================================
FILE: Dockerfile
================================================
FROM debian:stable-slim

ARG MINISIG=0.12
ARG ZIG_MINISIG=RWSGOq2NVecA2UPNdBUZykf1CCb147pkmdtYxgb3Ti+JO/wCYvhbAb/U
ARG V8=14.0.365.4
ARG ZIG_V8=v0.3.4
ARG TARGETPLATFORM

RUN apt-get update -yq && \
    apt-get install -yq xz-utils ca-certificates \
        pkg-config libglib2.0-dev \
        clang make curl git

# Get Rust
RUN curl https://sh.rustup.rs -sSf | sh -s -- --profile minimal -y
ENV PATH="/root/.cargo/bin:${PATH}"

# install minisig
RUN curl --fail -L -O https://github.com/jedisct1/minisign/releases/download/${MINISIG}/minisign-${MINISIG}-linux.tar.gz && \
    tar xvzf minisign-${MINISIG}-linux.tar.gz -C /

# clone lightpanda
RUN git clone https://github.com/lightpanda-io/browser.git
WORKDIR /browser

# install zig
RUN ZIG=$(grep '\.minimum_zig_version = "' "build.zig.zon" | cut -d'"' -f2) && \
    case $TARGETPLATFORM in \
      "linux/arm64") ARCH="aarch64" ;; \
      *) ARCH="x86_64" ;; \
    esac && \
    curl --fail -L -O https://ziglang.org/download/${ZIG}/zig-${ARCH}-linux-${ZIG}.tar.xz && \
    curl --fail -L -O https://ziglang.org/download/${ZIG}/zig-${ARCH}-linux-${ZIG}.tar.xz.minisig && \
    /minisign-linux/${ARCH}/minisign -Vm zig-${ARCH}-linux-${ZIG}.tar.xz -P ${ZIG_MINISIG} && \
    tar xvf zig-${ARCH}-linux-${ZIG}.tar.xz && \
    mv zig-${ARCH}-linux-${ZIG} /usr/local/lib && \
    ln -s /usr/local/lib/zig-${ARCH}-linux-${ZIG}/zig /usr/local/bin/zig

# download and install v8
RUN case $TARGETPLATFORM in \
    "linux/arm64") ARCH="aarch64" ;; \
    *) ARCH="x86_64" ;; \
    esac && \
    curl --fail -L -o libc_v8.a https://github.com/lightpanda-io/zig-v8-fork/releases/download/${ZIG_V8}/libc_v8_${V8}_linux_${ARCH}.a && \
    mkdir -p v8/ && \
    mv libc_v8.a v8/libc_v8.a

# build v8 snapshot
RUN zig build -Doptimize=ReleaseFast \
    -Dprebuilt_v8_path=v8/libc_v8.a \
    snapshot_creator -- src/snapshot.bin

# build release
RUN zig build -Doptimize=ReleaseFast \
    -Dsnapshot_path=../../snapshot.bin \
    -Dprebuilt_v8_path=v8/libc_v8.a \
    -Dgit_commit=$(git rev-parse --short HEAD)

FROM debian:stable-slim

RUN apt-get update -yq && \
    apt-get install -yq tini

FROM debian:stable-slim

# copy ca certificates
COPY --from=0 /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt

COPY --from=0 /browser/zig-out/bin/lightpanda /bin/lightpanda
COPY --from=1 /usr/bin/tini /usr/bin/tini

EXPOSE 9222/tcp

# Lightpanda install only some signal handlers, and PID 1 doesn't have a default SIGTERM signal handler.
# Using "tini" as PID1 ensures that signals work as expected, so e.g. "docker stop" will not hang.
# (See https://github.com/krallin/tini#why-tini).
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["/bin/lightpanda", "serve", "--host", "0.0.0.0", "--port", "9222", "--log_level", "info"]


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: LICENSING.md
================================================
# Licensing

License names used in this document are as per [SPDX License
List](https://spdx.org/licenses/).

The default license for this project is [AGPL-3.0-only](LICENSE).

The following directories and their subdirectories are licensed under their
original upstream licenses:

```
vendor/
tests/wpt/
```


================================================
FILE: Makefile
================================================
# Variables
# ---------

ZIG := zig
BC := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
# option test filter make test F="server"
F=

# OS and ARCH
kernel = $(shell uname -ms)
ifeq ($(kernel), Darwin arm64)
	OS := macos
	ARCH := aarch64
else ifeq ($(kernel), Darwin x86_64)
	OS := macos
	ARCH := x86_64
else ifeq ($(kernel), Linux aarch64)
	OS := linux
	ARCH := aarch64
else ifeq ($(kernel), Linux arm64)
	OS := linux
	ARCH := aarch64
else ifeq ($(kernel), Linux x86_64)
	OS := linux
	ARCH := x86_64
else
	$(error "Unhandled kernel: $(kernel)")
endif


# Infos
# -----
.PHONY: help

## Display this help screen
help:
	@printf "\033[36m%-35s %s\033[0m\n" "Command" "Usage"
	@sed -n -e '/^## /{'\
		-e 's/## //g;'\
		-e 'h;'\
		-e 'n;'\
		-e 's/:.*//g;'\
		-e 'G;'\
		-e 's/\n/ /g;'\
		-e 'p;}' Makefile | awk '{printf "\033[33m%-35s\033[0m%s\n", $$1, substr($$0,length($$1)+1)}'


# $(ZIG) commands
# ------------
.PHONY: build build-v8-snapshot build-dev run run-release test bench data end2end

## Build v8 snapshot
build-v8-snapshot:
	@printf "\033[36mBuilding v8 snapshot (release safe)...\033[0m\n"
	@$(ZIG) build -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
	@printf "\033[33mBuild OK\033[0m\n"

## Build in release-fast mode
build: build-v8-snapshot
	@printf "\033[36mBuilding (release fast)...\033[0m\n"
	@$(ZIG) build -Doptimize=ReleaseFast -Dsnapshot_path=../../snapshot.bin -Dgit_commit=$$(git rev-parse --short HEAD) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
	@printf "\033[33mBuild OK\033[0m\n"

## Build in debug mode
build-dev:
	@printf "\033[36mBuilding (debug)...\033[0m\n"
	@$(ZIG) build -Dgit_commit=$$(git rev-parse --short HEAD) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
	@printf "\033[33mBuild OK\033[0m\n"

## Run the server in release mode
run: build
	@printf "\033[36mRunning...\033[0m\n"
	@./zig-out/bin/lightpanda || (printf "\033[33mRun ERROR\033[0m\n"; exit 1;)

## Run the server in debug mode
run-debug: build-dev
	@printf "\033[36mRunning...\033[0m\n"
	@./zig-out/bin/lightpanda || (printf "\033[33mRun ERROR\033[0m\n"; exit 1;)

## Test - `grep` is used to filter out the huge compile command on build
ifeq ($(OS), macos)
test:
	@script -q /dev/null sh -c 'TEST_FILTER="${F}" $(ZIG) build test -freference-trace' 2>&1 \
		| grep --line-buffered -v "^/.*zig test -freference-trace"
else
test:
	@script -qec 'TEST_FILTER="${F}" $(ZIG) build test -freference-trace' /dev/null 2>&1 \
		| grep --line-buffered -v "^/.*zig test -freference-trace"
endif

## Run demo/runner end to end tests
end2end:
	@test -d ../demo
	cd ../demo && go run runner/main.go

# Install and build required dependencies commands
# ------------
.PHONY: install

install: build

data:
	cd src/data && go run public_suffix_list_gen.go > public_suffix_list.zig


================================================
FILE: README.md
================================================
<p align="center">
  <a href="https://lightpanda.io"><img src="https://cdn.lightpanda.io/assets/images/logo/lpd-logo.png" alt="Logo" height=170></a>
</p>
<h1 align="center">Lightpanda Browser</h1>
<p align="center">
<strong>The headless browser built from scratch for AI agents and automation.</strong><br>
Not a Chromium fork. Not a WebKit patch. A new browser, written in Zig.
</p>

</div>
<div align="center">

[![License](https://img.shields.io/github/license/lightpanda-io/browser)](https://github.com/lightpanda-io/browser/blob/main/LICENSE)
[![Twitter Follow](https://img.shields.io/twitter/follow/lightpanda_io)](https://twitter.com/lightpanda_io)
[![GitHub stars](https://img.shields.io/github/stars/lightpanda-io/browser)](https://github.com/lightpanda-io/browser)
[![Discord](https://img.shields.io/discord/1391984864894521354?style=flat-square&label=discord)](https://discord.gg/K63XeymfB5)

</div>
<div align="center">

[<img width="350px" src="https://cdn.lightpanda.io/assets/images/github/execution-time.svg">
](https://github.com/lightpanda-io/demo)
&emsp;
[<img width="350px" src="https://cdn.lightpanda.io/assets/images/github/memory-frame.svg">
](https://github.com/lightpanda-io/demo)
</div>

_Puppeteer requesting 100 pages from a local website on a AWS EC2 m5.large instance.
See [benchmark details](https://github.com/lightpanda-io/demo)._

Lightpanda is the open-source browser made for headless usage:

- Javascript execution
- Support of Web APIs (partial, WIP)
- Compatible with Playwright[^1], Puppeteer, chromedp through [CDP](https://chromedevtools.github.io/devtools-protocol/)

Fast web automation for AI agents, LLM training, scraping and testing:

- Ultra-low memory footprint (9x less than Chrome)
- Exceptionally fast execution (11x faster than Chrome)
- Instant startup

[^1]: **Playwright support disclaimer:**
Due to the nature of Playwright, a script that works with the current version of the browser may not function correctly with a future version. Playwright uses an intermediate JavaScript layer that selects an execution strategy based on the browser's available features. If Lightpanda adds a new [Web API](https://developer.mozilla.org/en-US/docs/Web/API), Playwright may choose to execute different code for the same script. This new code path could attempt to use features that are not yet implemented. Lightpanda makes an effort to add compatibility tests, but we can't cover all scenarios. If you encounter an issue, please create a [GitHub issue](https://github.com/lightpanda-io/browser/issues) and include the last known working version of the script.

## Quick start

### Install
**Install from the nightly builds**

You can download the last binary from the [nightly
builds](https://github.com/lightpanda-io/browser/releases/tag/nightly) for
Linux x86_64 and MacOS aarch64.

*For Linux*
```console
curl -L -o lightpanda https://github.com/lightpanda-io/browser/releases/download/nightly/lightpanda-x86_64-linux && \
chmod a+x ./lightpanda
```

*For MacOS*
```console
curl -L -o lightpanda https://github.com/lightpanda-io/browser/releases/download/nightly/lightpanda-aarch64-macos && \
chmod a+x ./lightpanda
```

*For Windows + WSL2*

The Lightpanda browser is compatible to run on windows inside WSL. Follow the Linux instruction for installation from a WSL terminal.
It is recommended to install clients like Puppeteer on the Windows host.

**Install from Docker**

Lightpanda provides [official Docker
images](https://hub.docker.com/r/lightpanda/browser) for both Linux amd64 and
arm64 architectures.
The following command fetches the Docker image and starts a new container exposing Lightpanda's CDP server on port `9222`.
```console
docker run -d --name lightpanda -p 9222:9222 lightpanda/browser:nightly
```

### Dump a URL

```console
./lightpanda fetch --obey_robots --log_format pretty  --log_level info https://demo-browser.lightpanda.io/campfire-commerce/
```
```console
INFO  telemetry : telemetry status . . . . . . . . . . . . .  [+0ms]
      disabled = false

INFO  page : navigate . . . . . . . . . . . . . . . . . . . . [+6ms]
      url = https://demo-browser.lightpanda.io/campfire-commerce/
      method = GET
      reason = address_bar
      body = false
      req_id = 1

INFO  browser : executing script . . . . . . . . . . . . . .  [+118ms]
      src = https://demo-browser.lightpanda.io/campfire-commerce/script.js
      kind = javascript
      cacheable = true

INFO  http : request complete . . . . . . . . . . . . . . . . [+140ms]
      source = xhr
      url = https://demo-browser.lightpanda.io/campfire-commerce/json/product.json
      status = 200
      len = 4770

INFO  http : request complete . . . . . . . . . . . . . . . . [+141ms]
      source = fetch
      url = https://demo-browser.lightpanda.io/campfire-commerce/json/reviews.json
      status = 200
      len = 1615
<!DOCTYPE html>
```

### Start a CDP server

```console
./lightpanda serve --obey_robots --log_format pretty  --log_level info --host 127.0.0.1 --port 9222
```
```console
INFO  telemetry : telemetry status . . . . . . . . . . . . .  [+0ms]
      disabled = false

INFO  app : server running . . . . . . . . . . . . . . . . .  [+0ms]
      address = 127.0.0.1:9222
```

Once the CDP server started, you can run a Puppeteer script by configuring the
`browserWSEndpoint`.

```js
'use strict'

import puppeteer from 'puppeteer-core';

// use browserWSEndpoint to pass the Lightpanda's CDP server address.
const browser = await puppeteer.connect({
  browserWSEndpoint: "ws://127.0.0.1:9222",
});

// The rest of your script remains the same.
const context = await browser.createBrowserContext();
const page = await context.newPage();

// Dump all the links from the page.
await page.goto('https://demo-browser.lightpanda.io/amiibo/', {waitUntil: "networkidle0"});

const links = await page.evaluate(() => {
  return Array.from(document.querySelectorAll('a')).map(row => {
    return row.getAttribute('href');
  });
});

console.log(links);

await page.close();
await context.close();
await browser.disconnect();
```

### Telemetry
By default, Lightpanda collects and sends usage telemetry. This can be disabled by setting an environment variable `LIGHTPANDA_DISABLE_TELEMETRY=true`. You can read Lightpanda's privacy policy at: [https://lightpanda.io/privacy-policy](https://lightpanda.io/privacy-policy).

## Status

Lightpanda is in Beta and currently a work in progress. Stability and coverage are improving and many websites now work.
You may still encounter errors or crashes. Please open an issue with specifics if so.

Here are the key features we have implemented:

- [x] HTTP loader ([Libcurl](https://curl.se/libcurl/))
- [x] HTML parser ([html5ever](https://github.com/servo/html5ever))
- [x] DOM tree
- [x] Javascript support ([v8](https://v8.dev/))
- [x] DOM APIs
- [x] Ajax
  - [x] XHR API
  - [x] Fetch API
- [x] DOM dump
- [x] CDP/websockets server
- [x] Click
- [x] Input form
- [x] Cookies
- [x] Custom HTTP headers
- [x] Proxy support
- [x] Network interception
- [x] Respect `robots.txt` with option `--obey_robots`

NOTE: There are hundreds of Web APIs. Developing a browser (even just for headless mode) is a huge task. Coverage will increase over time.

## Build from sources

### Prerequisites

Lightpanda is written with [Zig](https://ziglang.org/) `0.15.2`. You have to
install it with the right version in order to build the project.

Lightpanda also depends on
[v8](https://chromium.googlesource.com/v8/v8.git),
[Libcurl](https://curl.se/libcurl/) and [html5ever](https://github.com/servo/html5ever).

To be able to build the v8 engine, you have to install some libs:

For **Debian/Ubuntu based Linux**:

```
sudo apt install xz-utils ca-certificates \
    pkg-config libglib2.0-dev \
    clang make curl git
```
You also need to [install Rust](https://rust-lang.org/tools/install/).

For systems with [**Nix**](https://nixos.org/download/), you can use the devShell:
```
nix develop
```

For **MacOS**, you need cmake and [Rust](https://rust-lang.org/tools/install/).
```
brew install cmake
```

### Build and run

You an build the entire browser with `make build` or `make build-dev` for debug
env.

But you can directly use the zig command: `zig build run`.

#### Embed v8 snapshot

Lighpanda uses v8 snapshot. By default, it is created on startup but you can
embed it by using the following commands:

Generate the snapshot.
```
zig build snapshot_creator -- src/snapshot.bin
```

Build using the snapshot binary.
```
zig build -Dsnapshot_path=../../snapshot.bin
```

See [#1279](https://github.com/lightpanda-io/browser/pull/1279) for more details.

## Test

### Unit Tests

You can test Lightpanda by running `make test`.

### End to end tests

To run end to end tests, you need to clone the [demo
repository](https://github.com/lightpanda-io/demo) into `../demo` dir.

You have to install the [demo's node
requirements](https://github.com/lightpanda-io/demo?tab=readme-ov-file#dependencies-1)

You also need to install [Go](https://go.dev) > v1.24.

```
make end2end
```

### Web Platform Tests

Lightpanda is tested against the standardized [Web Platform
Tests](https://web-platform-tests.org/).

We use [a fork](https://github.com/lightpanda-io/wpt/tree/fork) including a custom
[`testharnessreport.js`](https://github.com/lightpanda-io/wpt/commit/01a3115c076a3ad0c84849dbbf77a6e3d199c56f).

For reference, you can easily execute a WPT test case with your browser via
[wpt.live](https://wpt.live).

#### Configure WPT HTTP server

To run the test, you must clone the repository, configure the custom hosts and generate the
`MANIFEST.json` file.

Clone the repository with the `fork` branch.
```
git clone -b fork --depth=1 git@github.com:lightpanda-io/wpt.git
```

Enter into the `wpt/` dir.

Install custom domains in your `/etc/hosts`
```
./wpt make-hosts-file | sudo tee -a /etc/hosts
```

Generate `MANIFEST.json`
```
./wpt manifest
```
Use the [WPT's setup
guide](https://web-platform-tests.org/running-tests/from-local-system.html) for
details.

#### Run WPT test suite

An external [Go](https://go.dev) runner is provided by
[github.com/lightpanda-io/demo/](https://github.com/lightpanda-io/demo/)
repository, located into `wptrunner/` dir.
You need to clone the project first.

First start the WPT's HTTP server from your `wpt/` clone dir.
```
./wpt serve
```

Run a Lightpanda browser

```
zig build run -- --insecure_disable_tls_host_verification
```

Then you can start the wptrunner from the Demo's clone dir:
```
cd wptrunner && go run .
```

Or one specific test:

```
cd wptrunner && go run . Node-childNodes.html
```

`wptrunner` command accepts `--summary` and `--json` options modifying output.
Also `--concurrency` define the concurrency limit.

:warning: Running the whole test suite will take a long time. In this case,
it's useful to build in `releaseFast` mode to make tests faster.

```
zig build -Doptimize=ReleaseFast run
```

## Contributing

Lightpanda accepts pull requests through GitHub.

You have to sign our [CLA](CLA.md) during the pull request process otherwise
we're not able to accept your contributions.

## Why?

### Javascript execution is mandatory for the modern web

In the good old days, scraping a webpage was as easy as making an HTTP request, cURL-like. It’s not possible anymore, because Javascript is everywhere, like it or not:

- Ajax, Single Page App, infinite loading, “click to display”, instant search, etc.
- JS web frameworks: React, Vue, Angular & others

### Chrome is not the right tool

If we need Javascript, why not use a real web browser? Take a huge desktop application, hack it, and run it on the server. Hundreds or thousands of instances of Chrome if you use it at scale. Are you sure it’s such a good idea?

- Heavy on RAM and CPU, expensive to run
- Hard to package, deploy and maintain at scale
- Bloated, lots of features are not useful in headless usage

### Lightpanda is built for performance

If we want both Javascript and performance in a true headless browser, we need to start from scratch. Not another iteration of Chromium, really from a blank page. Crazy right? But that’s what we did:

- Not based on Chromium, Blink or WebKit
- Low-level system programming language (Zig) with optimisations in mind
- Opinionated: without graphical rendering


================================================
FILE: build.zig
================================================
// Copyright (C) 2023-2024  Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const std = @import("std");

const Build = std.Build;

pub fn build(b: *Build) !void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const manifest = Manifest.init(b);

    const git_commit = b.option([]const u8, "git_commit", "Current git commit");
    const git_version = b.option([]const u8, "git_version", "Current git version (from tag)");
    const prebuilt_v8_path = b.option([]const u8, "prebuilt_v8_path", "Path to prebuilt libc_v8.a");
    const snapshot_path = b.option([]const u8, "snapshot_path", "Path to v8 snapshot");

    var opts = b.addOptions();
    opts.addOption([]const u8, "version", manifest.version);
    opts.addOption([]const u8, "git_commit", git_commit orelse "dev");
    opts.addOption(?[]const u8, "git_version", git_version orelse null);
    opts.addOption(?[]const u8, "snapshot_path", snapshot_path);

    const enable_tsan = b.option(bool, "tsan", "Enable Thread Sanitizer") orelse false;
    const enable_asan = b.option(bool, "asan", "Enable Address Sanitizer") orelse false;
    const enable_csan = b.option(std.zig.SanitizeC, "csan", "Enable C Sanitizers");

    const lightpanda_module = blk: {
        const mod = b.addModule("lightpanda", .{
            .root_source_file = b.path("src/lightpanda.zig"),
            .target = target,
            .optimize = optimize,
            .link_libc = true,
            .link_libcpp = true,
            .sanitize_c = enable_csan,
            .sanitize_thread = enable_tsan,
        });
        mod.addImport("lightpanda", mod); // allow circular "lightpanda" import
        mod.addImport("build_config", opts.createModule());

        // Format check
        const fmt_step = b.step("fmt", "Check code formatting");
        const fmt = b.addFmt(.{
            .paths = &.{ "src", "build.zig", "build.zig.zon" },
            .check = true,
        });
        fmt_step.dependOn(&fmt.step);

        // Set default behavior
        b.default_step.dependOn(fmt_step);

        try linkV8(b, mod, enable_asan, enable_tsan, prebuilt_v8_path);
        try linkCurl(b, mod, enable_tsan);
        try linkHtml5Ever(b, mod);

        break :blk mod;
    };

    {
        // browser
        const exe = b.addExecutable(.{
            .name = "lightpanda",
            .use_llvm = true,
            .root_module = b.createModule(.{
                .root_source_file = b.path("src/main.zig"),
                .target = target,
                .optimize = optimize,
                .sanitize_c = enable_csan,
                .sanitize_thread = enable_tsan,
                .imports = &.{
                    .{ .name = "lightpanda", .module = lightpanda_module },
                },
            }),
        });
        b.installArtifact(exe);

        const run_cmd = b.addRunArtifact(exe);
        if (b.args) |args| {
            run_cmd.addArgs(args);
        }
        const run_step = b.step("run", "Run the app");
        run_step.dependOn(&run_cmd.step);
    }

    {
        // snapshot creator
        const exe = b.addExecutable(.{
            .name = "lightpanda-snapshot-creator",
            .use_llvm = true,
            .root_module = b.createModule(.{
                .root_source_file = b.path("src/main_snapshot_creator.zig"),
                .target = target,
                .optimize = optimize,
                .imports = &.{
                    .{ .name = "lightpanda", .module = lightpanda_module },
                },
            }),
        });
        b.installArtifact(exe);

        const run_cmd = b.addRunArtifact(exe);
        if (b.args) |args| {
            run_cmd.addArgs(args);
        }
        const run_step = b.step("snapshot_creator", "Generate a v8 snapshot");
        run_step.dependOn(&run_cmd.step);
    }

    {
        // test
        const tests = b.addTest(.{
            .root_module = lightpanda_module,
            .use_llvm = true,
            .test_runner = .{ .path = b.path("src/test_runner.zig"), .mode = .simple },
        });
        const run_tests = b.addRunArtifact(tests);
        const test_step = b.step("test", "Run unit tests");
        test_step.dependOn(&run_tests.step);
    }

    {
        // browser
        const exe = b.addExecutable(.{
            .name = "legacy_test",
            .use_llvm = true,
            .root_module = b.createModule(.{
                .root_source_file = b.path("src/main_legacy_test.zig"),
                .target = target,
                .optimize = optimize,
                .sanitize_c = enable_csan,
                .sanitize_thread = enable_tsan,
                .imports = &.{
                    .{ .name = "lightpanda", .module = lightpanda_module },
                },
            }),
        });
        b.installArtifact(exe);

        const run_cmd = b.addRunArtifact(exe);
        if (b.args) |args| {
            run_cmd.addArgs(args);
        }
        const run_step = b.step("legacy_test", "Run the app");
        run_step.dependOn(&run_cmd.step);
    }
}

fn linkV8(
    b: *Build,
    mod: *Build.Module,
    is_asan: bool,
    is_tsan: bool,
    prebuilt_v8_path: ?[]const u8,
) !void {
    const target = mod.resolved_target.?;

    const dep = b.dependency("v8", .{
        .target = target,
        .optimize = mod.optimize.?,
        .is_asan = is_asan,
        .is_tsan = is_tsan,
        .inspector_subtype = false,
        .v8_enable_sandbox = is_tsan,
        .cache_root = b.pathFromRoot(".lp-cache"),
        .prebuilt_v8_path = prebuilt_v8_path,
    });
    mod.addImport("v8", dep.module("v8"));
}

fn linkHtml5Ever(b: *Build, mod: *Build.Module) !void {
    const is_debug = if (mod.optimize.? == .Debug) true else false;

    const exec_cargo = b.addSystemCommand(&.{
        "cargo",           "build",
        "--profile",       if (is_debug) "dev" else "release",
        "--manifest-path", "src/html5ever/Cargo.toml",
    });

    // TODO: We can prefer `--artifact-dir` once it become stable.
    const out_dir = exec_cargo.addPrefixedOutputDirectoryArg("--target-dir=", "html5ever");

    const html5ever_step = b.step("html5ever", "Install html5ever dependency (requires cargo)");
    html5ever_step.dependOn(&exec_cargo.step);

    const obj = out_dir.path(b, if (is_debug) "debug" else "release").path(b, "liblitefetch_html5ever.a");
    mod.addObjectFile(obj);
}

fn linkCurl(b: *Build, mod: *Build.Module, is_tsan: bool) !void {
    const target = mod.resolved_target.?;

    const curl = buildCurl(b, target, mod.optimize.?, is_tsan);
    mod.linkLibrary(curl);

    const zlib = buildZlib(b, target, mod.optimize.?, is_tsan);
    curl.root_module.linkLibrary(zlib);

    const brotli = buildBrotli(b, target, mod.optimize.?, is_tsan);
    for (brotli) |lib| curl.root_module.linkLibrary(lib);

    const nghttp2 = buildNghttp2(b, target, mod.optimize.?, is_tsan);
    curl.root_module.linkLibrary(nghttp2);

    const boringssl = buildBoringSsl(b, target, mod.optimize.?);
    for (boringssl) |lib| curl.root_module.linkLibrary(lib);

    switch (target.result.os.tag) {
        .macos => {
            // needed for proxying on mac
            mod.addSystemFrameworkPath(.{ .cwd_relative = "/System/Library/Frameworks" });
            mod.linkFramework("CoreFoundation", .{});
            mod.linkFramework("SystemConfiguration", .{});
        },
        else => {},
    }
}

fn buildZlib(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, is_tsan: bool) *Build.Step.Compile {
    const dep = b.dependency("zlib", .{});

    const mod = b.createModule(.{
        .target = target,
        .optimize = optimize,
        .link_libc = true,
        .sanitize_thread = is_tsan,
    });

    const lib = b.addLibrary(.{ .name = "z", .root_module = mod });
    lib.installHeadersDirectory(dep.path(""), "", .{});
    lib.addCSourceFiles(.{
        .root = dep.path(""),
        .flags = &.{
            "-DHAVE_SYS_TYPES_H",
            "-DHAVE_STDINT_H",
            "-DHAVE_STDDEF_H",
            "-DHAVE_UNISTD_H",
        },
        .files = &.{
            "adler32.c", "compress.c", "crc32.c",
            "deflate.c", "gzclose.c",  "gzlib.c",
            "gzread.c",  "gzwrite.c",  "infback.c",
            "inffast.c", "inflate.c",  "inftrees.c",
            "trees.c",   "uncompr.c",  "zutil.c",
        },
    });

    return lib;
}

fn buildBrotli(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, is_tsan: bool) [3]*Build.Step.Compile {
    const dep = b.dependency("brotli", .{});

    const mod = b.createModule(.{
        .target = target,
        .optimize = optimize,
        .link_libc = true,
        .sanitize_thread = is_tsan,
    });
    mod.addIncludePath(dep.path("c/include"));

    const brotlicmn = b.addLibrary(.{ .name = "brotlicommon", .root_module = mod });
    const brotlidec = b.addLibrary(.{ .name = "brotlidec", .root_module = mod });
    const brotlienc = b.addLibrary(.{ .name = "brotlienc", .root_module = mod });

    brotlicmn.installHeadersDirectory(dep.path("c/include/brotli"), "brotli", .{});
    brotlicmn.addCSourceFiles(.{
        .root = dep.path("c/common"),
        .files = &.{
            "transform.c",  "shared_dictionary.c", "platform.c",
            "dictionary.c", "context.c",           "constants.c",
        },
    });
    brotlidec.addCSourceFiles(.{
        .root = dep.path("c/dec"),
        .files = &.{
            "bit_reader.c", "decode.c", "huffman.c",
            "prefix.c",     "state.c",  "static_init.c",
        },
    });
    brotlienc.addCSourceFiles(.{
        .root = dep.path("c/enc"),
        .files = &.{
            "backward_references.c",        "backward_references_hq.c", "bit_cost.c",
            "block_splitter.c",             "brotli_bit_stream.c",      "cluster.c",
            "command.c",                    "compound_dictionary.c",    "compress_fragment.c",
            "compress_fragment_two_pass.c", "dictionary_hash.c",        "encode.c",
            "encoder_dict.c",               "entropy_encode.c",         "fast_log.c",
            "histogram.c",                  "literal_cost.c",           "memory.c",
            "metablock.c",                  "static_dict.c",            "static_dict_lut.c",
            "static_init.c",                "utf8_util.c",
        },
    });

    return .{ brotlicmn, brotlidec, brotlienc };
}

fn buildBoringSsl(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) [2]*Build.Step.Compile {
    const dep = b.dependency("boringssl-zig", .{
        .target = target,
        .optimize = optimize,
        .force_pic = true,
    });

    const ssl = dep.artifact("ssl");
    ssl.bundle_ubsan_rt = false;

    const crypto = dep.artifact("crypto");
    crypto.bundle_ubsan_rt = false;

    return .{ ssl, crypto };
}

fn buildNghttp2(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, is_tsan: bool) *Build.Step.Compile {
    const dep = b.dependency("nghttp2", .{});

    const mod = b.createModule(.{
        .target = target,
        .optimize = optimize,
        .link_libc = true,
        .sanitize_thread = is_tsan,
    });
    mod.addIncludePath(dep.path("lib/includes"));

    const config = b.addConfigHeader(.{
        .include_path = "nghttp2ver.h",
        .style = .{ .cmake = dep.path("lib/includes/nghttp2/nghttp2ver.h.in") },
    }, .{
        .PACKAGE_VERSION = "1.68.90",
        .PACKAGE_VERSION_NUM = 0x016890,
    });
    mod.addConfigHeader(config);

    const lib = b.addLibrary(.{ .name = "nghttp2", .root_module = mod });

    lib.installConfigHeader(config);
    lib.installHeadersDirectory(dep.path("lib/includes/nghttp2"), "nghttp2", .{});
    lib.addCSourceFiles(.{
        .root = dep.path("lib"),
        .flags = &.{
            "-DNGHTTP2_STATICLIB",
            "-DHAVE_TIME_H",
            "-DHAVE_ARPA_INET_H",
            "-DHAVE_NETINET_IN_H",
        },
        .files = &.{
            "sfparse.c",                 "nghttp2_alpn.c",   "nghttp2_buf.c",
            "nghttp2_callbacks.c",       "nghttp2_debug.c",  "nghttp2_extpri.c",
            "nghttp2_frame.c",           "nghttp2_hd.c",     "nghttp2_hd_huffman.c",
            "nghttp2_hd_huffman_data.c", "nghttp2_helper.c", "nghttp2_http.c",
            "nghttp2_map.c",             "nghttp2_mem.c",    "nghttp2_option.c",
            "nghttp2_outbound_item.c",   "nghttp2_pq.c",     "nghttp2_priority_spec.c",
            "nghttp2_queue.c",           "nghttp2_rcbuf.c",  "nghttp2_session.c",
            "nghttp2_stream.c",          "nghttp2_submit.c", "nghttp2_version.c",
            "nghttp2_ratelim.c",         "nghttp2_time.c",
        },
    });

    return lib;
}

fn buildCurl(
    b: *Build,
    target: Build.ResolvedTarget,
    optimize: std.builtin.OptimizeMode,
    is_tsan: bool,
) *Build.Step.Compile {
    const dep = b.dependency("curl", .{});

    const mod = b.createModule(.{
        .target = target,
        .optimize = optimize,
        .link_libc = true,
        .sanitize_thread = is_tsan,
    });
    mod.addIncludePath(dep.path("lib"));
    mod.addIncludePath(dep.path("include"));

    const os = target.result.os.tag;
    const abi = target.result.abi;

    const is_gnu = abi.isGnu();
    const is_ios = os == .ios;
    const is_android = abi.isAndroid();
    const is_linux = os == .linux;
    const is_darwin = os.isDarwin();
    const is_windows = os == .windows;
    const is_netbsd = os == .netbsd;
    const is_openbsd = os == .openbsd;
    const is_freebsd = os == .freebsd;

    const byte_size = struct {
        fn it(b2: *std.Build, target2: Build.ResolvedTarget, name: []const u8, comptime ctype: std.Target.CType) []const u8 {
            const size = target2.result.cTypeByteSize(ctype);
            return std.fmt.allocPrint(b2.allocator, "#define SIZEOF_{s} {d}", .{ name, size }) catch @panic("OOM");
        }
    }.it;

    const config = .{
        .HAVE_LIBZ = true,
        .HAVE_BROTLI = true,
        .USE_NGHTTP2 = true,

        .USE_OPENSSL = true,
        .OPENSSL_IS_BORINGSSL = true,
        .CURL_CA_PATH = null,
        .CURL_CA_BUNDLE = null,
        .CURL_CA_FALLBACK = false,
        .CURL_CA_SEARCH_SAFE = false,
        .CURL_DEFAULT_SSL_BACKEND = "openssl",

        .CURL_DISABLE_AWS = true,
        .CURL_DISABLE_DICT = true,
        .CURL_DISABLE_DOH = true,
        .CURL_DISABLE_FILE = true,
        .CURL_DISABLE_FTP = true,
        .CURL_DISABLE_GOPHER = true,
        .CURL_DISABLE_KERBEROS_AUTH = true,
        .CURL_DISABLE_IMAP = true,
        .CURL_DISABLE_IPFS = true,
        .CURL_DISABLE_LDAP = true,
        .CURL_DISABLE_LDAPS = true,
        .CURL_DISABLE_MQTT = true,
        .CURL_DISABLE_NTLM = true,
        .CURL_DISABLE_PROGRESS_METER = true,
        .CURL_DISABLE_POP3 = true,
        .CURL_DISABLE_RTSP = true,
        .CURL_DISABLE_SMB = true,
        .CURL_DISABLE_SMTP = true,
        .CURL_DISABLE_TELNET = true,
        .CURL_DISABLE_TFTP = true,

        .ssize_t = null,
        ._FILE_OFFSET_BITS = 64,

        .USE_IPV6 = true,
        .CURL_OS = switch (os) {
            .linux => if (is_android) "\"android\"" else "\"linux\"",
            else => std.fmt.allocPrint(b.allocator, "\"{s}\"", .{@tagName(os)}) catch @panic("OOM"),
        },

        // Adjusts the sizes of variables
        .SIZEOF_INT_CODE = byte_size(b, target, "INT", .int),
        .SIZEOF_LONG_CODE = byte_size(b, target, "LONG", .long),
        .SIZEOF_LONG_LONG_CODE = byte_size(b, target, "LONG_LONG", .longlong),

        .SIZEOF_OFF_T_CODE = byte_size(b, target, "OFF_T", .longlong),
        .SIZEOF_CURL_OFF_T_CODE = byte_size(b, target, "CURL_OFF_T", .longlong),
        .SIZEOF_CURL_SOCKET_T_CODE = byte_size(b, target, "CURL_SOCKET_T", .int),

        .SIZEOF_SIZE_T_CODE = byte_size(b, target, "SIZE_T", .longlong),
        .SIZEOF_TIME_T_CODE = byte_size(b, target, "TIME_T", .longlong),

        // headers availability
        .HAVE_ARPA_INET_H = !is_windows,
        .HAVE_DIRENT_H = true,
        .HAVE_FCNTL_H = true,
        .HAVE_IFADDRS_H = !is_windows,
        .HAVE_IO_H = is_windows,
        .HAVE_LIBGEN_H = true,
        .HAVE_LINUX_TCP_H = is_linux and is_gnu,
        .HAVE_LOCALE_H = true,
        .HAVE_NETDB_H = !is_windows,
        .HAVE_NETINET_IN6_H = is_android,
        .HAVE_NETINET_IN_H = !is_windows,
        .HAVE_NETINET_TCP_H = !is_windows,
        .HAVE_NETINET_UDP_H = !is_windows,
        .HAVE_NET_IF_H = !is_windows,
        .HAVE_POLL_H = !is_windows,
        .HAVE_PWD_H = !is_windows,
        .HAVE_STDATOMIC_H = true,
        .HAVE_STDBOOL_H = true,
        .HAVE_STDDEF_H = true,
        .HAVE_STDINT_H = true,
        .HAVE_STRINGS_H = true,
        .HAVE_STROPTS_H = false,
        .HAVE_SYS_EVENTFD_H = is_linux or is_freebsd or is_netbsd,
        .HAVE_SYS_FILIO_H = !is_linux and !is_windows,
        .HAVE_SYS_IOCTL_H = !is_windows,
        .HAVE_SYS_PARAM_H = true,
        .HAVE_SYS_POLL_H = !is_windows,
        .HAVE_SYS_RESOURCE_H = !is_windows,
        .HAVE_SYS_SELECT_H = !is_windows,
        .HAVE_SYS_SOCKIO_H = !is_linux and !is_windows,
        .HAVE_SYS_TYPES_H = true,
        .HAVE_SYS_UN_H = !is_windows,
        .HAVE_SYS_UTIME_H = is_windows,
        .HAVE_TERMIOS_H = !is_windows,
        .HAVE_TERMIO_H = is_linux,
        .HAVE_UNISTD_H = true,
        .HAVE_UTIME_H = true,
        .STDC_HEADERS = true,

        // general environment
        .CURL_KRB5_VERSION = null,
        .HAVE_ALARM = !is_windows,
        .HAVE_ARC4RANDOM = is_android,
        .HAVE_ATOMIC = true,
        .HAVE_BOOL_T = true,
        .HAVE_BUILTIN_AVAILABLE = true,
        .HAVE_CLOCK_GETTIME_MONOTONIC = !is_darwin and !is_windows,
        .HAVE_CLOCK_GETTIME_MONOTONIC_RAW = is_linux,
        .HAVE_FILE_OFFSET_BITS = true,
        .HAVE_GETEUID = !is_windows,
        .HAVE_GETPPID = !is_windows,
        .HAVE_GETTIMEOFDAY = true,
        .HAVE_GLIBC_STRERROR_R = is_gnu,
        .HAVE_GMTIME_R = !is_windows,
        .HAVE_LOCALTIME_R = !is_windows,
        .HAVE_LONGLONG = !is_windows,
        .HAVE_MACH_ABSOLUTE_TIME = is_darwin,
        .HAVE_MEMRCHR = !is_darwin and !is_windows,
        .HAVE_POSIX_STRERROR_R = !is_gnu and !is_windows,
        .HAVE_PTHREAD_H = !is_windows,
        .HAVE_SETLOCALE = true,
        .HAVE_SETRLIMIT = !is_windows,
        .HAVE_SIGACTION = !is_windows,
        .HAVE_SIGINTERRUPT = !is_windows,
        .HAVE_SIGNAL = true,
        .HAVE_SIGSETJMP = !is_windows,
        .HAVE_SIZEOF_SA_FAMILY_T = false,
        .HAVE_SIZEOF_SUSECONDS_T = false,
        .HAVE_SNPRINTF = true,
        .HAVE_STRCASECMP = !is_windows,
        .HAVE_STRCMPI = false,
        .HAVE_STRDUP = true,
        .HAVE_STRERROR_R = !is_windows,
        .HAVE_STRICMP = false,
        .HAVE_STRUCT_TIMEVAL = true,
        .HAVE_TIME_T_UNSIGNED = false,
        .HAVE_UTIME = true,
        .HAVE_UTIMES = !is_windows,
        .HAVE_WRITABLE_ARGV = !is_windows,
        .HAVE__SETMODE = is_windows,
        .USE_THREADS_POSIX = !is_windows,

        // filesystem, network
        .HAVE_ACCEPT4 = is_linux or is_freebsd or is_netbsd or is_openbsd,
        .HAVE_BASENAME = true,
        .HAVE_CLOSESOCKET = is_windows,
        .HAVE_DECL_FSEEKO = !is_windows,
        .HAVE_EVENTFD = is_linux or is_freebsd or is_netbsd,
        .HAVE_FCNTL = !is_windows,
        .HAVE_FCNTL_O_NONBLOCK = !is_windows,
        .HAVE_FNMATCH = !is_windows,
        .HAVE_FREEADDRINFO = true,
        .HAVE_FSEEKO = !is_windows,
        .HAVE_FSETXATTR = is_darwin or is_linux or is_netbsd,
        .HAVE_FSETXATTR_5 = is_linux or is_netbsd,
        .HAVE_FSETXATTR_6 = is_darwin,
        .HAVE_FTRUNCATE = true,
        .HAVE_GETADDRINFO = true,
        .HAVE_GETADDRINFO_THREADSAFE = is_linux or is_freebsd or is_netbsd,
        .HAVE_GETHOSTBYNAME_R = is_linux or is_freebsd,
        .HAVE_GETHOSTBYNAME_R_3 = false,
        .HAVE_GETHOSTBYNAME_R_3_REENTRANT = false,
        .HAVE_GETHOSTBYNAME_R_5 = false,
        .HAVE_GETHOSTBYNAME_R_5_REENTRANT = false,
        .HAVE_GETHOSTBYNAME_R_6 = is_linux,
        .HAVE_GETHOSTBYNAME_R_6_REENTRANT = is_linux,
        .HAVE_GETHOSTNAME = true,
        .HAVE_GETIFADDRS = if (is_windows) false else !is_android or target.result.os.versionRange().linux.android >= 24,
        .HAVE_GETPASS_R = is_netbsd,
        .HAVE_GETPEERNAME = true,
        .HAVE_GETPWUID = !is_windows,
        .HAVE_GETPWUID_R = !is_windows,
        .HAVE_GETRLIMIT = !is_windows,
        .HAVE_GETSOCKNAME = true,
        .HAVE_IF_NAMETOINDEX = !is_windows,
        .HAVE_INET_NTOP = !is_windows,
        .HAVE_INET_PTON = !is_windows,
        .HAVE_IOCTLSOCKET = is_windows,
        .HAVE_IOCTLSOCKET_CAMEL = false,
        .HAVE_IOCTLSOCKET_CAMEL_FIONBIO = false,
        .HAVE_IOCTLSOCKET_FIONBIO = is_windows,
        .HAVE_IOCTL_FIONBIO = !is_windows,
        .HAVE_IOCTL_SIOCGIFADDR = !is_windows,
        .HAVE_MSG_NOSIGNAL = !is_windows,
        .HAVE_OPENDIR = true,
        .HAVE_PIPE = !is_windows,
        .HAVE_PIPE2 = is_linux or is_freebsd or is_netbsd or is_openbsd,
        .HAVE_POLL = !is_windows,
        .HAVE_REALPATH = !is_windows,
        .HAVE_RECV = true,
        .HAVE_SA_FAMILY_T = !is_windows,
        .HAVE_SCHED_YIELD = !is_windows,
        .HAVE_SELECT = true,
        .HAVE_SEND = true,
        .HAVE_SENDMMSG = !is_darwin and !is_windows,
        .HAVE_SENDMSG = !is_windows,
        .HAVE_SETMODE = !is_linux,
        .HAVE_SETSOCKOPT_SO_NONBLOCK = false,
        .HAVE_SOCKADDR_IN6_SIN6_ADDR = !is_windows,
        .HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID = true,
        .HAVE_SOCKET = true,
        .HAVE_SOCKETPAIR = !is_windows,
        .HAVE_STRUCT_SOCKADDR_STORAGE = true,
        .HAVE_SUSECONDS_T = is_android or is_ios,
        .USE_UNIX_SOCKETS = !is_windows,
    };

    const curl_config = b.addConfigHeader(.{
        .include_path = "curl_config.h",
        .style = .{ .cmake = dep.path("lib/curl_config-cmake.h.in") },
    }, .{
        .CURL_EXTERN_SYMBOL = "__attribute__ ((__visibility__ (\"default\"))",
    });
    curl_config.addValues(config);

    const lib = b.addLibrary(.{ .name = "curl", .root_module = mod });
    lib.addConfigHeader(curl_config);
    lib.installHeadersDirectory(dep.path("include/curl"), "curl", .{});
    lib.addCSourceFiles(.{
        .root = dep.path("lib"),
        .flags = &.{
            "-D_GNU_SOURCE",
            "-DHAVE_CONFIG_H",
            "-DCURL_STATICLIB",
            "-DBUILDING_LIBCURL",
        },
        .files = &.{
            // You can include all files from lib, libcurl uses #ifdef-guards to exclude code for disabled functions
            "altsvc.c",              "amigaos.c",              "asyn-ares.c",
            "asyn-base.c",           "asyn-thrdd.c",           "bufq.c",
            "bufref.c",              "cf-h1-proxy.c",          "cf-h2-proxy.c",
            "cf-haproxy.c",          "cf-https-connect.c",     "cf-ip-happy.c",
            "cf-socket.c",           "cfilters.c",             "conncache.c",
            "connect.c",             "content_encoding.c",     "cookie.c",
            "cshutdn.c",             "curl_addrinfo.c",        "curl_endian.c",
            "curl_fnmatch.c",        "curl_fopen.c",           "curl_get_line.c",
            "curl_gethostname.c",    "curl_gssapi.c",          "curl_memrchr.c",
            "curl_ntlm_core.c",      "curl_range.c",           "curl_rtmp.c",
            "curl_sasl.c",           "curl_sha512_256.c",      "curl_share.c",
            "curl_sspi.c",           "curl_threads.c",         "curl_trc.c",
            "curlx/base64.c",        "curlx/dynbuf.c",         "curlx/fopen.c",
            "curlx/inet_ntop.c",     "curlx/inet_pton.c",      "curlx/multibyte.c",
            "curlx/nonblock.c",      "curlx/strcopy.c",        "curlx/strerr.c",
            "curlx/strparse.c",      "curlx/timediff.c",       "curlx/timeval.c",
            "curlx/version_win32.c", "curlx/wait.c",           "curlx/warnless.c",
            "curlx/winapi.c",        "cw-out.c",               "cw-pause.c",
            "dict.c",                "dllmain.c",              "doh.c",
            "dynhds.c",              "easy.c",                 "easygetopt.c",
            "easyoptions.c",         "escape.c",               "fake_addrinfo.c",
            "file.c",                "fileinfo.c",             "formdata.c",
            "ftp.c",                 "ftplistparser.c",        "getenv.c",
            "getinfo.c",             "gopher.c",               "hash.c",
            "headers.c",             "hmac.c",                 "hostip.c",
            "hostip4.c",             "hostip6.c",              "hsts.c",
            "http.c",                "http1.c",                "http2.c",
            "http_aws_sigv4.c",      "http_chunks.c",          "http_digest.c",
            "http_negotiate.c",      "http_ntlm.c",            "http_proxy.c",
            "httpsrr.c",             "idn.c",                  "if2ip.c",
            "imap.c",                "ldap.c",                 "llist.c",
            "macos.c",               "md4.c",                  "md5.c",
            "memdebug.c",            "mime.c",                 "mprintf.c",
            "mqtt.c",                "multi.c",                "multi_ev.c",
            "multi_ntfy.c",          "netrc.c",                "noproxy.c",
            "openldap.c",            "parsedate.c",            "pingpong.c",
            "pop3.c",                "progress.c",             "psl.c",
            "rand.c",                "ratelimit.c",            "request.c",
            "rtsp.c",                "select.c",               "sendf.c",
            "setopt.c",              "sha256.c",               "slist.c",
            "smb.c",                 "smtp.c",                 "socketpair.c",
            "socks.c",               "socks_gssapi.c",         "socks_sspi.c",
            "splay.c",               "strcase.c",              "strdup.c",
            "strequal.c",            "strerror.c",             "system_win32.c",
            "telnet.c",              "tftp.c",                 "transfer.c",
            "uint-bset.c",           "uint-hash.c",            "uint-spbset.c",
            "uint-table.c",          "url.c",                  "urlapi.c",
            "vauth/cleartext.c",     "vauth/cram.c",           "vauth/digest.c",
            "vauth/digest_sspi.c",   "vauth/gsasl.c",          "vauth/krb5_gssapi.c",
            "vauth/krb5_sspi.c",     "vauth/ntlm.c",           "vauth/ntlm_sspi.c",
            "vauth/oauth2.c",        "vauth/spnego_gssapi.c",  "vauth/spnego_sspi.c",
            "vauth/vauth.c",         "version.c",              "vquic/curl_ngtcp2.c",
            "vquic/curl_osslq.c",    "vquic/curl_quiche.c",    "vquic/vquic-tls.c",
            "vquic/vquic.c",         "vssh/libssh.c",          "vssh/libssh2.c",
            "vssh/vssh.c",           "vtls/apple.c",           "vtls/cipher_suite.c",
            "vtls/gtls.c",           "vtls/hostcheck.c",       "vtls/keylog.c",
            "vtls/mbedtls.c",        "vtls/openssl.c",         "vtls/rustls.c",
            "vtls/schannel.c",       "vtls/schannel_verify.c", "vtls/vtls.c",
            "vtls/vtls_scache.c",    "vtls/vtls_spack.c",      "vtls/wolfssl.c",
            "vtls/x509asn1.c",       "ws.c",
        },
    });

    return lib;
}

const Manifest = struct {
    version: []const u8,
    minimum_zig_version: []const u8,

    fn init(b: *std.Build) Manifest {
        const input = @embedFile("build.zig.zon");

        var diagnostics: std.zon.parse.Diagnostics = .{};
        defer diagnostics.deinit(b.allocator);

        return std.zon.parse.fromSlice(Manifest, b.allocator, input, &diagnostics, .{
            .free_on_error = true,
            .ignore_unknown_fields = true,
        }) catch |err| {
            switch (err) {
                error.OutOfMemory => @panic("OOM"),
                error.ParseZon => {
                    std.debug.print("Parse diagnostics:\n{f}\n", .{diagnostics});
                    std.process.exit(1);
                },
            }
        };
    }
};


================================================
FILE: build.zig.zon
================================================
.{
    .name = .browser,
    .version = "0.0.0",
    .fingerprint = 0xda130f3af836cea0, // Changing this has security and trust implications.
    .minimum_zig_version = "0.15.2",
    .dependencies = .{
        .v8 = .{
            .url = "https://github.com/lightpanda-io/zig-v8-fork/archive/refs/tags/v0.3.4.tar.gz",
            .hash = "v8-0.0.0-xddH6_F3BAAiFvKY6R1H-gkuQlk19BkDQ0--uZuTrSup",
        },
        // .v8 = .{ .path = "../zig-v8-fork" },
        .brotli = .{
            // v1.2.0
            .url = "https://github.com/google/brotli/archive/028fb5a23661f123017c060daa546b55cf4bde29.tar.gz",
            .hash = "N-V-__8AAJudKgCQCuIiH6MJjAiIJHfg_tT_Ew-0vZwVkCo_",
        },
        .zlib = .{
            .url = "https://github.com/madler/zlib/releases/download/v1.3.2/zlib-1.3.2.tar.gz",
            .hash = "N-V-__8AAJ2cNgAgfBtAw33Bxfu1IWISDeKKSr3DAqoAysIJ",
        },
        .nghttp2 = .{
            .url = "https://github.com/nghttp2/nghttp2/releases/download/v1.68.0/nghttp2-1.68.0.tar.gz",
            .hash = "N-V-__8AAL15vQCI63ZL6Zaz5hJg6JTEgYXGbLnMFSnf7FT3",
        },
        .@"boringssl-zig" = .{
            .url = "git+https://github.com/Syndica/boringssl-zig.git#c53df00d06b02b755ad88bbf4d1202ed9687b096",
            .hash = "boringssl-0.1.0-VtJeWehMAAA4RNnwRnzEvKcS9rjsR1QVRw1uJrwXxmVK",
        },
        .curl = .{
            .url = "https://github.com/curl/curl/releases/download/curl-8_18_0/curl-8.18.0.tar.gz",
            .hash = "N-V-__8AALp9QAGn6CCHZ6fK_FfMyGtG824LSHYHHasM3w-y",
        },
    },
    .paths = .{""},
}


================================================
FILE: flake.nix
================================================
{
  description = "headless browser designed for AI and automation";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/release-25.05";

    zigPkgs.url = "github:mitchellh/zig-overlay";
    zigPkgs.inputs.nixpkgs.follows = "nixpkgs";

    zlsPkg.url = "github:zigtools/zls/0.15.0";
    zlsPkg.inputs.zig-overlay.follows = "zigPkgs";
    zlsPkg.inputs.nixpkgs.follows = "nixpkgs";

    fenix = {
      url = "github:nix-community/fenix";
      inputs.nixpkgs.follows = "nixpkgs";
    };

    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs =
    {
      nixpkgs,
      zigPkgs,
      zlsPkg,
      fenix,
      flake-utils,
      ...
    }:
    flake-utils.lib.eachDefaultSystem (
      system:
      let
        overlays = [
          (final: prev: {
            zigpkgs = zigPkgs.packages.${prev.system};
            zls = zlsPkg.packages.${prev.system}.default;
          })
        ];

        pkgs = import nixpkgs {
          inherit system overlays;
        };

        rustToolchain = fenix.packages.${system}.stable.toolchain;

        # We need crtbeginS.o for building.
        crtFiles = pkgs.runCommand "crt-files" { } ''
          mkdir -p $out/lib
          cp -r ${pkgs.gcc.cc}/lib/gcc $out/lib/gcc
        '';

        # This build pipeline is very unhappy without an FHS-compliant env.
        fhs = pkgs.buildFHSEnv {
          name = "fhs-shell";
          multiArch = true;
          targetPkgs =
            pkgs: with pkgs; [
              # Build Tools
              zigpkgs."0.15.2"
              zls
              rustToolchain
              python3
              pkg-config
              cmake
              gperf

              # GCC
              gcc
              gcc.cc.lib
              crtFiles

              # Libaries
              expat.dev
              glib.dev
              glibc.dev
              zlib
            ];
        };
      in
      {
        devShells.default = fhs.env;
      }
    );
}


================================================
FILE: src/App.zig
================================================
// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const std = @import("std");

const Allocator = std.mem.Allocator;

const log = @import("log.zig");
const Config = @import("Config.zig");
const Snapshot = @import("browser/js/Snapshot.zig");
const Platform = @import("browser/js/Platform.zig");
const Telemetry = @import("telemetry/telemetry.zig").Telemetry;

const Network = @import("network/Runtime.zig");
pub const ArenaPool = @import("ArenaPool.zig");

const App = @This();

network: Network,
config: *const Config,
platform: Platform,
snapshot: Snapshot,
telemetry: Telemetry,
allocator: Allocator,
arena_pool: ArenaPool,
app_dir_path: ?[]const u8,

pub fn init(allocator: Allocator, config: *const Config) !*App {
    const app = try allocator.create(App);
    errdefer allocator.destroy(app);

    app.* = .{
        .config = config,
        .allocator = allocator,
        .network = undefined,
        .platform = undefined,
        .snapshot = undefined,
        .app_dir_path = undefined,
        .telemetry = undefined,
        .arena_pool = undefined,
    };

    app.network = try Network.init(allocator, config);
    errdefer app.network.deinit();

    app.platform = try Platform.init();
    errdefer app.platform.deinit();

    app.snapshot = try Snapshot.load();
    errdefer app.snapshot.deinit();

    app.app_dir_path = getAndMakeAppDir(allocator);

    app.telemetry = try Telemetry.init(app, config.mode);
    errdefer app.telemetry.deinit(allocator);

    app.arena_pool = ArenaPool.init(allocator, 512, 1024 * 16);
    errdefer app.arena_pool.deinit();

    return app;
}

pub fn shutdown(self: *const App) bool {
    return self.network.shutdown.load(.acquire);
}

pub fn deinit(self: *App) void {
    const allocator = self.allocator;
    if (self.app_dir_path) |app_dir_path| {
        allocator.free(app_dir_path);
        self.app_dir_path = null;
    }
    self.telemetry.deinit(allocator);
    self.network.deinit();
    self.snapshot.deinit();
    self.platform.deinit();
    self.arena_pool.deinit();

    allocator.destroy(self);
}

fn getAndMakeAppDir(allocator: Allocator) ?[]const u8 {
    if (@import("builtin").is_test) {
        return allocator.dupe(u8, "/tmp") catch unreachable;
    }
    const app_dir_path = std.fs.getAppDataDir(allocator, "lightpanda") catch |err| {
        log.warn(.app, "get data dir", .{ .err = err });
        return null;
    };

    std.fs.cwd().makePath(app_dir_path) catch |err| switch (err) {
        error.PathAlreadyExists => return app_dir_path,
        else => {
            allocator.free(app_dir_path);
            log.warn(.app, "create data dir", .{ .err = err, .path = app_dir_path });
            return null;
        },
    };
    return app_dir_path;
}


================================================
FILE: src/ArenaPool.zig
================================================
// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const std = @import("std");

const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;

const ArenaPool = @This();

allocator: Allocator,
retain_bytes: usize,
free_list_len: u16 = 0,
free_list: ?*Entry = null,
free_list_max: u16,
entry_pool: std.heap.MemoryPool(Entry),
mutex: std.Thread.Mutex = .{},

const Entry = struct {
    next: ?*Entry,
    arena: ArenaAllocator,
};

pub fn init(allocator: Allocator, free_list_max: u16, retain_bytes: usize) ArenaPool {
    return .{
        .allocator = allocator,
        .free_list_max = free_list_max,
        .retain_bytes = retain_bytes,
        .entry_pool = .init(allocator),
    };
}

pub fn deinit(self: *ArenaPool) void {
    var entry = self.free_list;
    while (entry) |e| {
        entry = e.next;
        e.arena.deinit();
    }
    self.entry_pool.deinit();
}

pub fn acquire(self: *ArenaPool) !Allocator {
    self.mutex.lock();
    defer self.mutex.unlock();

    if (self.free_list) |entry| {
        self.free_list = entry.next;
        self.free_list_len -= 1;
        return entry.arena.allocator();
    }

    const entry = try self.entry_pool.create();
    entry.* = .{
        .next = null,
        .arena = ArenaAllocator.init(self.allocator),
    };

    return entry.arena.allocator();
}

pub fn release(self: *ArenaPool, allocator: Allocator) void {
    const arena: *std.heap.ArenaAllocator = @ptrCast(@alignCast(allocator.ptr));
    const entry: *Entry = @fieldParentPtr("arena", arena);

    // Reset the arena before acquiring the lock to minimize lock hold time
    _ = arena.reset(.{ .retain_with_limit = self.retain_bytes });

    self.mutex.lock();
    defer self.mutex.unlock();

    const free_list_len = self.free_list_len;
    if (free_list_len == self.free_list_max) {
        arena.deinit();
        self.entry_pool.destroy(entry);
        return;
    }

    entry.next = self.free_list;
    self.free_list_len = free_list_len + 1;
    self.free_list = entry;
}

pub fn reset(_: *const ArenaPool, allocator: Allocator, retain: usize) void {
    const arena: *std.heap.ArenaAllocator = @ptrCast(@alignCast(allocator.ptr));
    _ = arena.reset(.{ .retain_with_limit = retain });
}

const testing = std.testing;

test "arena pool - basic acquire and use" {
    var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
    defer pool.deinit();

    const alloc = try pool.acquire();
    const buf = try alloc.alloc(u8, 64);
    @memset(buf, 0xAB);
    try testing.expectEqual(@as(u8, 0xAB), buf[0]);

    pool.release(alloc);
}

test "arena pool - reuse entry after release" {
    var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
    defer pool.deinit();

    const alloc1 = try pool.acquire();
    try testing.expectEqual(@as(u16, 0), pool.free_list_len);

    pool.release(alloc1);
    try testing.expectEqual(@as(u16, 1), pool.free_list_len);

    // The same entry should be returned from the free list.
    const alloc2 = try pool.acquire();
    try testing.expectEqual(@as(u16, 0), pool.free_list_len);
    try testing.expectEqual(alloc1.ptr, alloc2.ptr);

    pool.release(alloc2);
}

test "arena pool - multiple concurrent arenas" {
    var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
    defer pool.deinit();

    const a1 = try pool.acquire();
    const a2 = try pool.acquire();
    const a3 = try pool.acquire();

    // All three must be distinct arenas.
    try testing.expect(a1.ptr != a2.ptr);
    try testing.expect(a2.ptr != a3.ptr);
    try testing.expect(a1.ptr != a3.ptr);

    _ = try a1.alloc(u8, 16);
    _ = try a2.alloc(u8, 32);
    _ = try a3.alloc(u8, 48);

    pool.release(a1);
    pool.release(a2);
    pool.release(a3);

    try testing.expectEqual(@as(u16, 3), pool.free_list_len);
}

test "arena pool - free list respects max limit" {
    // Cap the free list at 1 so the second release discards its arena.
    var pool = ArenaPool.init(testing.allocator, 1, 1024 * 16);
    defer pool.deinit();

    const a1 = try pool.acquire();
    const a2 = try pool.acquire();

    pool.release(a1);
    try testing.expectEqual(@as(u16, 1), pool.free_list_len);

    // The free list is full; a2's arena should be destroyed, not queued.
    pool.release(a2);
    try testing.expectEqual(@as(u16, 1), pool.free_list_len);
}

test "arena pool - reset clears memory without releasing" {
    var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
    defer pool.deinit();

    const alloc = try pool.acquire();

    const buf = try alloc.alloc(u8, 128);
    @memset(buf, 0xFF);

    // reset() frees arena memory but keeps the allocator in-flight.
    pool.reset(alloc, 0);

    // The free list must stay empty; the allocator was not released.
    try testing.expectEqual(@as(u16, 0), pool.free_list_len);

    // Allocating again through the same arena must still work.
    const buf2 = try alloc.alloc(u8, 64);
    @memset(buf2, 0x00);
    try testing.expectEqual(@as(u8, 0x00), buf2[0]);

    pool.release(alloc);
}

test "arena pool - deinit with entries in free list" {
    // Verifies that deinit properly cleans up free-listed arenas (no leaks
    // detected by the test allocator).
    var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);

    const a1 = try pool.acquire();
    const a2 = try pool.acquire();
    _ = try a1.alloc(u8, 256);
    _ = try a2.alloc(u8, 512);
    pool.release(a1);
    pool.release(a2);
    try testing.expectEqual(@as(u16, 2), pool.free_list_len);

    pool.deinit();
}


================================================
FILE: src/Config.zig
================================================
// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;

const log = @import("log.zig");
const dump = @import("browser/dump.zig");

const WebBotAuthConfig = @import("network/WebBotAuth.zig").Config;

pub const RunMode = enum {
    help,
    fetch,
    serve,
    version,
    mcp,
};

pub const MAX_LISTENERS = 16;
pub const CDP_MAX_HTTP_REQUEST_SIZE = 4096;

// max message size
// +14 for max websocket payload overhead
// +140 for the max control packet that might be interleaved in a message
pub const CDP_MAX_MESSAGE_SIZE = 512 * 1024 + 14 + 140;

mode: Mode,
exec_name: []const u8,
http_headers: HttpHeaders,

const Config = @This();

pub fn init(allocator: Allocator, exec_name: []const u8, mode: Mode) !Config {
    var config = Config{
        .mode = mode,
        .exec_name = exec_name,
        .http_headers = undefined,
    };
    config.http_headers = try HttpHeaders.init(allocator, &config);
    return config;
}

pub fn deinit(self: *const Config, allocator: Allocator) void {
    self.http_headers.deinit(allocator);
}

pub fn tlsVerifyHost(self: *const Config) bool {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.tls_verify_host,
        else => unreachable,
    };
}

pub fn obeyRobots(self: *const Config) bool {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.obey_robots,
        else => unreachable,
    };
}

pub fn httpProxy(self: *const Config) ?[:0]const u8 {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.http_proxy,
        else => unreachable,
    };
}

pub fn proxyBearerToken(self: *const Config) ?[:0]const u8 {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.proxy_bearer_token,
        .help, .version => null,
    };
}

pub fn httpMaxConcurrent(self: *const Config) u8 {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.http_max_concurrent orelse 10,
        else => unreachable,
    };
}

pub fn httpMaxHostOpen(self: *const Config) u8 {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.http_max_host_open orelse 4,
        else => unreachable,
    };
}

pub fn httpConnectTimeout(self: *const Config) u31 {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.http_connect_timeout orelse 0,
        else => unreachable,
    };
}

pub fn httpTimeout(self: *const Config) u31 {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.http_timeout orelse 5000,
        else => unreachable,
    };
}

pub fn httpMaxRedirects(_: *const Config) u8 {
    return 10;
}

pub fn httpMaxResponseSize(self: *const Config) ?usize {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.http_max_response_size,
        else => unreachable,
    };
}

pub fn logLevel(self: *const Config) ?log.Level {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.log_level,
        else => unreachable,
    };
}

pub fn logFormat(self: *const Config) ?log.Format {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.log_format,
        else => unreachable,
    };
}

pub fn logFilterScopes(self: *const Config) ?[]const log.Scope {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.log_filter_scopes,
        else => unreachable,
    };
}

pub fn userAgentSuffix(self: *const Config) ?[]const u8 {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| opts.common.user_agent_suffix,
        .help, .version => null,
    };
}

pub fn cdpTimeout(self: *const Config) usize {
    return switch (self.mode) {
        .serve => |opts| if (opts.timeout > 604_800) 604_800_000 else @as(usize, opts.timeout) * 1000,
        else => unreachable,
    };
}

pub fn webBotAuth(self: *const Config) ?WebBotAuthConfig {
    return switch (self.mode) {
        inline .serve, .fetch, .mcp => |opts| WebBotAuthConfig{
            .key_file = opts.common.web_bot_auth_key_file orelse return null,
            .keyid = opts.common.web_bot_auth_keyid orelse return null,
            .domain = opts.common.web_bot_auth_domain orelse return null,
        },
        .help, .version => null,
    };
}

pub fn maxConnections(self: *const Config) u16 {
    return switch (self.mode) {
        .serve => |opts| opts.cdp_max_connections,
        else => unreachable,
    };
}

pub fn maxPendingConnections(self: *const Config) u31 {
    return switch (self.mode) {
        .serve => |opts| opts.cdp_max_pending_connections,
        else => unreachable,
    };
}

pub const Mode = union(RunMode) {
    help: bool, // false when being printed because of an error
    fetch: Fetch,
    serve: Serve,
    version: void,
    mcp: Mcp,
};

pub const Serve = struct {
    host: []const u8 = "127.0.0.1",
    port: u16 = 9222,
    timeout: u31 = 10,
    cdp_max_connections: u16 = 16,
    cdp_max_pending_connections: u16 = 128,
    common: Common = .{},
};

pub const Mcp = struct {
    common: Common = .{},
};

pub const DumpFormat = enum {
    html,
    markdown,
    wpt,
    semantic_tree,
    semantic_tree_text,
};

pub const Fetch = struct {
    url: [:0]const u8,
    dump_mode: ?DumpFormat = null,
    common: Common = .{},
    with_base: bool = false,
    with_frames: bool = false,
    strip: dump.Opts.Strip = .{},
};

pub const Common = struct {
    obey_robots: bool = false,
    proxy_bearer_token: ?[:0]const u8 = null,
    http_proxy: ?[:0]const u8 = null,
    http_max_concurrent: ?u8 = null,
    http_max_host_open: ?u8 = null,
    http_timeout: ?u31 = null,
    http_connect_timeout: ?u31 = null,
    http_max_response_size: ?usize = null,
    tls_verify_host: bool = true,
    log_level: ?log.Level = null,
    log_format: ?log.Format = null,
    log_filter_scopes: ?[]log.Scope = null,
    user_agent_suffix: ?[]const u8 = null,

    web_bot_auth_key_file: ?[]const u8 = null,
    web_bot_auth_keyid: ?[]const u8 = null,
    web_bot_auth_domain: ?[]const u8 = null,
};

/// Pre-formatted HTTP headers for reuse across Http and Client.
/// Must be initialized with an allocator that outlives all HTTP connections.
pub const HttpHeaders = struct {
    const user_agent_base: [:0]const u8 = "Lightpanda/1.0";

    user_agent: [:0]const u8, // User agent value (e.g. "Lightpanda/1.0")
    user_agent_header: [:0]const u8,

    proxy_bearer_header: ?[:0]const u8,

    pub fn init(allocator: Allocator, config: *const Config) !HttpHeaders {
        const user_agent: [:0]const u8 = if (config.userAgentSuffix()) |suffix|
            try std.fmt.allocPrintSentinel(allocator, "{s} {s}", .{ user_agent_base, suffix }, 0)
        else
            user_agent_base;
        errdefer if (config.userAgentSuffix() != null) allocator.free(user_agent);

        const user_agent_header = try std.fmt.allocPrintSentinel(allocator, "User-Agent: {s}", .{user_agent}, 0);
        errdefer allocator.free(user_agent_header);

        const proxy_bearer_header: ?[:0]const u8 = if (config.proxyBearerToken()) |token|
            try std.fmt.allocPrintSentinel(allocator, "Proxy-Authorization: Bearer {s}", .{token}, 0)
        else
            null;

        return .{
            .user_agent = user_agent,
            .user_agent_header = user_agent_header,
            .proxy_bearer_header = proxy_bearer_header,
        };
    }

    pub fn deinit(self: *const HttpHeaders, allocator: Allocator) void {
        if (self.proxy_bearer_header) |hdr| {
            allocator.free(hdr);
        }
        allocator.free(self.user_agent_header);
        if (self.user_agent.ptr != user_agent_base.ptr) {
            allocator.free(self.user_agent);
        }
    }
};

pub fn printUsageAndExit(self: *const Config, success: bool) void {
    //                                                                     MAX_HELP_LEN|
    const common_options =
        \\
        \\--insecure_disable_tls_host_verification
        \\                Disables host verification on all HTTP requests. This is an
        \\                advanced option which should only be set if you understand
        \\                and accept the risk of disabling host verification.
        \\
        \\--obey_robots
        \\                Fetches and obeys the robots.txt (if available) of the web pages
        \\                we make requests towards.
        \\                Defaults to false.
        \\
        \\--http_proxy    The HTTP proxy to use for all HTTP requests.
        \\                A username:password can be included for basic authentication.
        \\                Defaults to none.
        \\
        \\--proxy_bearer_token
        \\                The <token> to send for bearer authentication with the proxy
        \\                Proxy-Authorization: Bearer <token>
        \\
        \\--http_max_concurrent
        \\                The maximum number of concurrent HTTP requests.
        \\                Defaults to 10.
        \\
        \\--http_max_host_open
        \\                The maximum number of open connection to a given host:port.
        \\                Defaults to 4.
        \\
        \\--http_connect_timeout
        \\                The time, in milliseconds, for establishing an HTTP connection
        \\                before timing out. 0 means it never times out.
        \\                Defaults to 0.
        \\
        \\--http_timeout
        \\                The maximum time, in milliseconds, the transfer is allowed
        \\                to complete. 0 means it never times out.
        \\                Defaults to 10000.
        \\
        \\--http_max_response_size
        \\                Limits the acceptable response size for any request
        \\                (e.g. XHR, fetch, script loading, ...).
        \\                Defaults to no limit.
        \\
        \\--log_level     The log level: debug, info, warn, error or fatal.
        \\                Defaults to
    ++ (if (builtin.mode == .Debug) " info." else "warn.") ++
        \\
        \\
        \\--log_format    The log format: pretty or logfmt.
        \\                Defaults to
    ++ (if (builtin.mode == .Debug) " pretty." else " logfmt.") ++
        \\
        \\
        \\--log_filter_scopes
        \\                Filter out too verbose logs per scope:
        \\                http, unknown_prop, event, ...
        \\
        \\--user_agent_suffix
        \\                Suffix to append to the Lightpanda/X.Y User-Agent
        \\
        \\--web_bot_auth_key_file
        \\                Path to the Ed25519 private key PEM file.
        \\
        \\--web_bot_auth_keyid
        \\                The JWK thumbprint of your public key.
        \\
        \\--web_bot_auth_domain
        \\                Your domain e.g. yourdomain.com
    ;

    //                                                                     MAX_HELP_LEN|
    const usage =
        \\usage: {s} command [options] [URL]
        \\
        \\Command can be either 'fetch', 'serve', 'mcp' or 'help'
        \\
        \\fetch command
        \\Fetches the specified URL
        \\Example: {s} fetch --dump html https://lightpanda.io/
        \\
        \\Options:
        \\--dump          Dumps document to stdout.
        \\                Argument must be 'html', 'markdown', 'semantic_tree', or 'semantic_tree_text'.
        \\                Defaults to no dump.
        \\
        \\--strip_mode    Comma separated list of tag groups to remove from dump
        \\                the dump. e.g. --strip_mode js,css
        \\                  - "js" script and link[as=script, rel=preload]
        \\                  - "ui" includes img, picture, video, css and svg
        \\                  - "css" includes style and link[rel=stylesheet]
        \\                  - "full" includes js, ui and css
        \\
        \\--with_base     Add a <base> tag in dump. Defaults to false.
        \\
        \\--with_frames   Includes the contents of iframes. Defaults to false.
        \\
    ++ common_options ++
        \\
        \\serve command
        \\Starts a websocket CDP server
        \\Example: {s} serve --host 127.0.0.1 --port 9222
        \\
        \\Options:
        \\--host          Host of the CDP server
        \\                Defaults to "127.0.0.1"
        \\
        \\--port          Port of the CDP server
        \\                Defaults to 9222
        \\
        \\--timeout       Inactivity timeout in seconds before disconnecting clients
        \\                Defaults to 10 (seconds). Limited to 604800 (1 week).
        \\
        \\--cdp_max_connections
        \\                Maximum number of simultaneous CDP connections.
        \\                Defaults to 16.
        \\
        \\--cdp_max_pending_connections
        \\                Maximum pending connections in the accept queue.
        \\                Defaults to 128.
        \\
    ++ common_options ++
        \\
        \\mcp command
        \\Starts an MCP (Model Context Protocol) server over stdio
        \\Example: {s} mcp
        \\
    ++ common_options ++
        \\
        \\version command
        \\Displays the version of {s}
        \\
        \\help command
        \\Displays this message
        \\
    ;
    std.debug.print(usage, .{ self.exec_name, self.exec_name, self.exec_name, self.exec_name, self.exec_name });
    if (success) {
        return std.process.cleanExit();
    }
    std.process.exit(1);
}

pub fn parseArgs(allocator: Allocator) !Config {
    var args = try std.process.argsWithAllocator(allocator);
    defer args.deinit();

    const exec_name = try allocator.dupe(u8, std.fs.path.basename(args.next().?));

    const mode_string = args.next() orelse "";
    const run_mode = std.meta.stringToEnum(RunMode, mode_string) orelse blk: {
        const inferred_mode = inferMode(mode_string) orelse
            return init(allocator, exec_name, .{ .help = false });
        // "command" wasn't a command but an option. We can't reset args, but
        // we can create a new one. Not great, but this fallback is temporary
        // as we transition to this command mode approach.
        args.deinit();

        args = try std.process.argsWithAllocator(allocator);
        // skip the exec_name
        _ = args.skip();

        break :blk inferred_mode;
    };

    const mode: Mode = switch (run_mode) {
        .help => .{ .help = true },
        .serve => .{ .serve = parseServeArgs(allocator, &args) catch
            return init(allocator, exec_name, .{ .help = false }) },
        .fetch => .{ .fetch = parseFetchArgs(allocator, &args) catch
            return init(allocator, exec_name, .{ .help = false }) },
        .mcp => .{ .mcp = parseMcpArgs(allocator, &args) catch
            return init(allocator, exec_name, .{ .help = false }) },
        .version => .{ .version = {} },
    };
    return init(allocator, exec_name, mode);
}

fn inferMode(opt: []const u8) ?RunMode {
    if (opt.len == 0) {
        return .serve;
    }

    if (std.mem.startsWith(u8, opt, "--") == false) {
        return .fetch;
    }

    if (std.mem.eql(u8, opt, "--dump")) {
        return .fetch;
    }

    if (std.mem.eql(u8, opt, "--noscript")) {
        return .fetch;
    }

    if (std.mem.eql(u8, opt, "--strip_mode")) {
        return .fetch;
    }

    if (std.mem.eql(u8, opt, "--with_base")) {
        return .fetch;
    }

    if (std.mem.eql(u8, opt, "--with_frames")) {
        return .fetch;
    }

    if (std.mem.eql(u8, opt, "--host")) {
        return .serve;
    }

    if (std.mem.eql(u8, opt, "--port")) {
        return .serve;
    }

    if (std.mem.eql(u8, opt, "--timeout")) {
        return .serve;
    }

    return null;
}

fn parseServeArgs(
    allocator: Allocator,
    args: *std.process.ArgIterator,
) !Serve {
    var serve: Serve = .{};

    while (args.next()) |opt| {
        if (std.mem.eql(u8, "--host", opt)) {
            const str = args.next() orelse {
                log.fatal(.app, "missing argument value", .{ .arg = "--host" });
                return error.InvalidArgument;
            };
            serve.host = try allocator.dupe(u8, str);
            continue;
        }

        if (std.mem.eql(u8, "--port", opt)) {
            const str = args.next() orelse {
                log.fatal(.app, "missing argument value", .{ .arg = "--port" });
                return error.InvalidArgument;
            };

            serve.port = std.fmt.parseInt(u16, str, 10) catch |err| {
                log.fatal(.app, "invalid argument value", .{ .arg = "--port", .err = err });
                return error.InvalidArgument;
            };
            continue;
        }

        if (std.mem.eql(u8, "--timeout", opt)) {
            const str = args.next() orelse {
                log.fatal(.app, "missing argument value", .{ .arg = "--timeout" });
                return error.InvalidArgument;
            };

            serve.timeout = std.fmt.parseInt(u31, str, 10) catch |err| {
                log.fatal(.app, "invalid argument value", .{ .arg = "--timeout", .err = err });
                return error.InvalidArgument;
            };
            continue;
        }

        if (std.mem.eql(u8, "--cdp_max_connections", opt)) {
            const str = args.next() orelse {
                log.fatal(.app, "missing argument value", .{ .arg = "--cdp_max_connections" });
                return error.InvalidArgument;
            };

            serve.cdp_max_connections = std.fmt.parseInt(u16, str, 10) catch |err| {
                log.fatal(.app, "invalid argument value", .{ .arg = "--cdp_max_connections", .err = err });
                return error.InvalidArgument;
            };
            continue;
        }

        if (std.mem.eql(u8, "--cdp_max_pending_connections", opt)) {
            const str = args.next() orelse {
                log.fatal(.app, "missing argument value", .{ .arg = "--cdp_max_pending_connections" });
                return error.InvalidArgument;
            };

            serve.cdp_max_pending_connections = std.fmt.parseInt(u16, str, 10) catch |err| {
                log.fatal(.app, "invalid argument value", .{ .arg = "--cdp_max_pending_connections", .err = err });
                return error.InvalidArgument;
            };
            continue;
        }

        if (try parseCommonArg(allocator, opt, args, &serve.common)) {
            continue;
        }

        log.fatal(.app, "unknown argument", .{ .mode = "serve", .arg = opt });
        return error.UnkownOption;
    }

    return serve;
}

fn parseMcpArgs(
    allocator: Allocator,
    args: *std.process.ArgIterator,
) !Mcp {
    var mcp: Mcp = .{};

    while (args.next()) |opt| {
        if (try parseCommonArg(allocator, opt, args, &mcp.common)) {
            continue;
        }

        log.fatal(.mcp, "unknown argument", .{ .mode = "mcp", .arg = opt });
        return error.UnkownOption;
    }

    return mcp;
}

fn parseFetchArgs(
    allocator: Allocator,
    args: *std.process.ArgIterator,
) !Fetch {
    var dump_mode: ?DumpFormat = null;
    var with_base: bool = false;
    var with_frames: bool = false;
    var url: ?[:0]const u8 = null;
    var common: Common = .{};
    var strip: dump.Opts.Strip = .{};

    while (args.next()) |opt| {
        if (std.mem.eql(u8, "--dump", opt)) {
            var peek_args = args.*;
            if (peek_args.next()) |next_arg| {
                if (std.meta.stringToEnum(DumpFormat, next_arg)) |mode| {
                    dump_mode = mode;
                    _ = args.next();
                } else {
                    dump_mode = .html;
                }
            } else {
                dump_mode = .html;
            }
            continue;
        }

        if (std.mem.eql(u8, "--noscript", opt)) {
            log.warn(.app, "deprecation warning", .{
                .feature = "--noscript argument",
                .hint = "use '--strip_mode js' instead",
            });
            strip.js = true;
            continue;
        }

        if (std.mem.eql(u8, "--with_base", opt)) {
            with_base = true;
            continue;
        }

        if (std.mem.eql(u8, "--with_frames", opt)) {
            with_frames = true;
            continue;
        }

        if (std.mem.eql(u8, "--strip_mode", opt)) {
            const str = args.next() orelse {
                log.fatal(.app, "missing argument value", .{ .arg = "--strip_mode" });
                return error.InvalidArgument;
            };

            var it = std.mem.splitScalar(u8, str, ',');
            while (it.next()) |part| {
                const trimmed = std.mem.trim(u8, part, &std.ascii.whitespace);
                if (std.mem.eql(u8, trimmed, "js")) {
                    strip.js = true;
                } else if (std.mem.eql(u8, trimmed, "ui")) {
                    strip.ui = true;
                } else if (std.mem.eql(u8, trimmed, "css")) {
                    strip.css = true;
                } else if (std.mem.eql(u8, trimmed, "full")) {
                    strip.js = true;
                    strip.ui = true;
                    strip.css = true;
                } else {
                    log.fatal(.app, "invalid option choice", .{ .arg = "--strip_mode", .value = trimmed });
                }
            }
            continue;
        }

        if (try parseCommonArg(allocator, opt, args, &common)) {
            continue;
        }

        if (std.mem.startsWith(u8, opt, "--")) {
            log.fatal(.app, "unknown argument", .{ .mode = "fetch", .arg = opt });
            return error.UnkownOption;
        }

        if (url != null) {
            log.fatal(.app, "duplicate fetch url", .{ .help = "only 1 URL can be specified" });
            return error.TooManyURLs;
        }
        url = try allocator.dupeZ(u8, opt);
    }

    if (url == null) {
        log.fatal(.app, "missing fetch url", .{ .help = "URL to fetch must be provided" });
        return error.MissingURL;
    }

    return .{
        .url = url.?,
        .dump_mode = dump_mode,
        .strip = strip,
        .common = common,
        .with_base = with_base,
        .with_frames = with_frames,
    };
}

fn parseCommonArg(
    allocator: Allocator,
    opt: []const u8,
    args: *std.process.ArgIterator,
    common: *Common,
) !bool {
    if (std.mem.eql(u8, "--insecure_disable_tls_host_verification", opt)) {
        common.tls_verify_host = false;
        return true;
    }

    if (std.mem.eql(u8, "--obey_robots", opt)) {
        common.obey_robots = true;
        return true;
    }

    if (std.mem.eql(u8, "--http_proxy", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--http_proxy" });
            return error.InvalidArgument;
        };
        common.http_proxy = try allocator.dupeZ(u8, str);
        return true;
    }

    if (std.mem.eql(u8, "--proxy_bearer_token", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--proxy_bearer_token" });
            return error.InvalidArgument;
        };
        common.proxy_bearer_token = try allocator.dupeZ(u8, str);
        return true;
    }

    if (std.mem.eql(u8, "--http_max_concurrent", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--http_max_concurrent" });
            return error.InvalidArgument;
        };

        common.http_max_concurrent = std.fmt.parseInt(u8, str, 10) catch |err| {
            log.fatal(.app, "invalid argument value", .{ .arg = "--http_max_concurrent", .err = err });
            return error.InvalidArgument;
        };
        return true;
    }

    if (std.mem.eql(u8, "--http_max_host_open", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--http_max_host_open" });
            return error.InvalidArgument;
        };

        common.http_max_host_open = std.fmt.parseInt(u8, str, 10) catch |err| {
            log.fatal(.app, "invalid argument value", .{ .arg = "--http_max_host_open", .err = err });
            return error.InvalidArgument;
        };
        return true;
    }

    if (std.mem.eql(u8, "--http_connect_timeout", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--http_connect_timeout" });
            return error.InvalidArgument;
        };

        common.http_connect_timeout = std.fmt.parseInt(u31, str, 10) catch |err| {
            log.fatal(.app, "invalid argument value", .{ .arg = "--http_connect_timeout", .err = err });
            return error.InvalidArgument;
        };
        return true;
    }

    if (std.mem.eql(u8, "--http_timeout", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--http_timeout" });
            return error.InvalidArgument;
        };

        common.http_timeout = std.fmt.parseInt(u31, str, 10) catch |err| {
            log.fatal(.app, "invalid argument value", .{ .arg = "--http_timeout", .err = err });
            return error.InvalidArgument;
        };
        return true;
    }

    if (std.mem.eql(u8, "--http_max_response_size", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--http_max_response_size" });
            return error.InvalidArgument;
        };

        common.http_max_response_size = std.fmt.parseInt(usize, str, 10) catch |err| {
            log.fatal(.app, "invalid argument value", .{ .arg = "--http_max_response_size", .err = err });
            return error.InvalidArgument;
        };
        return true;
    }

    if (std.mem.eql(u8, "--log_level", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--log_level" });
            return error.InvalidArgument;
        };

        common.log_level = std.meta.stringToEnum(log.Level, str) orelse blk: {
            if (std.mem.eql(u8, str, "error")) {
                break :blk .err;
            }
            log.fatal(.app, "invalid option choice", .{ .arg = "--log_level", .value = str });
            return error.InvalidArgument;
        };
        return true;
    }

    if (std.mem.eql(u8, "--log_format", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--log_format" });
            return error.InvalidArgument;
        };

        common.log_format = std.meta.stringToEnum(log.Format, str) orelse {
            log.fatal(.app, "invalid option choice", .{ .arg = "--log_format", .value = str });
            return error.InvalidArgument;
        };
        return true;
    }

    if (std.mem.eql(u8, "--log_filter_scopes", opt)) {
        if (builtin.mode != .Debug) {
            log.fatal(.app, "experimental", .{ .help = "log scope filtering is only available in debug builds" });
            return false;
        }

        const str = args.next() orelse {
            // disables the default filters
            common.log_filter_scopes = &.{};
            return true;
        };

        var arr: std.ArrayList(log.Scope) = .empty;

        var it = std.mem.splitScalar(u8, str, ',');
        while (it.next()) |part| {
            try arr.append(allocator, std.meta.stringToEnum(log.Scope, part) orelse {
                log.fatal(.app, "invalid option choice", .{ .arg = "--log_filter_scopes", .value = part });
                return false;
            });
        }
        common.log_filter_scopes = arr.items;
        return true;
    }

    if (std.mem.eql(u8, "--user_agent_suffix", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--user_agent_suffix" });
            return error.InvalidArgument;
        };
        for (str) |c| {
            if (!std.ascii.isPrint(c)) {
                log.fatal(.app, "not printable character", .{ .arg = "--user_agent_suffix" });
                return error.InvalidArgument;
            }
        }
        common.user_agent_suffix = try allocator.dupe(u8, str);
        return true;
    }

    if (std.mem.eql(u8, "--web_bot_auth_key_file", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--web_bot_auth_key_file" });
            return error.InvalidArgument;
        };
        common.web_bot_auth_key_file = try allocator.dupe(u8, str);
        return true;
    }

    if (std.mem.eql(u8, "--web_bot_auth_keyid", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--web_bot_auth_keyid" });
            return error.InvalidArgument;
        };
        common.web_bot_auth_keyid = try allocator.dupe(u8, str);
        return true;
    }

    if (std.mem.eql(u8, "--web_bot_auth_domain", opt)) {
        const str = args.next() orelse {
            log.fatal(.app, "missing argument value", .{ .arg = "--web_bot_auth_domain" });
            return error.InvalidArgument;
        };
        common.web_bot_auth_domain = try allocator.dupe(u8, str);
        return true;
    }

    return false;
}


================================================
FILE: src/Notification.zig
================================================
// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const std = @import("std");
const lp = @import("lightpanda");

const log = @import("log.zig");
const Page = @import("browser/Page.zig");
const Transfer = @import("browser/HttpClient.zig").Transfer;

const Allocator = std.mem.Allocator;

const List = std.DoublyLinkedList;

// Allows code to register for and emit events.
// Keeps two lists
// 1 - for a given event type, a linked list of all the listeners
// 2 - for a given listener, a list of all it's registration
// The 2nd one is so that a listener can unregister all of it's listeners
// (there's currently no need for a listener to unregister only 1 or more
// specific listener).
//
// Scoping is important. Imagine we created a global singleton registry, and our
// CDP code registers for the "network_bytes_sent" event, because it needs to
// send messages to the client when this happens. Our HTTP client could then
// emit a "network_bytes_sent" message. It would be easy, and it would work.
// That is, it would work until multiple CDP clients connect, and because
// everything's just one big global, events from one CDP session would be sent
// to all CDP clients.
//
// To avoid this, one way or another, we need scoping. We could still have
// a global registry but every "register" and every "emit" has some type of
// "scope". This would have a run-time cost and still require some coordination
// between components to share a common scope.
//
// Instead, the approach that we take is to have a notification instance per
// CDP connection (BrowserContext). Each CDP connection has its own notification
// that is shared across all Sessions (tabs) within that connection. This ensures
// proper isolation between different CDP clients while allowing a single client
// to receive events from all its tabs.
const Notification = @This();
// Every event type (which are hard-coded), has a list of Listeners.
// When the event happens, we dispatch to those listener.
event_listeners: EventListeners,

// list of listeners for a specified receiver
// @intFromPtr(receiver) -> [listener1, listener2, ...]
// Used when `unregisterAll` is called.
listeners: std.AutoHashMapUnmanaged(usize, std.ArrayList(*Listener)),

allocator: Allocator,
mem_pool: std.heap.MemoryPool(Listener),

const EventListeners = struct {
    page_remove: List = .{},
    page_created: List = .{},
    page_navigate: List = .{},
    page_navigated: List = .{},
    page_network_idle: List = .{},
    page_network_almost_idle: List = .{},
    page_frame_created: List = .{},
    http_request_fail: List = .{},
    http_request_start: List = .{},
    http_request_intercept: List = .{},
    http_request_done: List = .{},
    http_request_auth_required: List = .{},
    http_response_data: List = .{},
    http_response_header_done: List = .{},
};

const Events = union(enum) {
    page_remove: PageRemove,
    page_created: *Page,
    page_navigate: *const PageNavigate,
    page_navigated: *const PageNavigated,
    page_network_idle: *const PageNetworkIdle,
    page_network_almost_idle: *const PageNetworkAlmostIdle,
    page_frame_created: *const PageFrameCreated,
    http_request_fail: *const RequestFail,
    http_request_start: *const RequestStart,
    http_request_intercept: *const RequestIntercept,
    http_request_auth_required: *const RequestAuthRequired,
    http_request_done: *const RequestDone,
    http_response_data: *const ResponseData,
    http_response_header_done: *const ResponseHeaderDone,
};
const EventType = std.meta.FieldEnum(Events);

pub const PageRemove = struct {};

pub const PageNavigate = struct {
    req_id: u32,
    frame_id: u32,
    timestamp: u64,
    url: [:0]const u8,
    opts: Page.NavigateOpts,
};

pub const PageNavigated = struct {
    req_id: u32,
    frame_id: u32,
    timestamp: u64,
    url: [:0]const u8,
    opts: Page.NavigatedOpts,
};

pub const PageNetworkIdle = struct {
    req_id: u32,
    frame_id: u32,
    timestamp: u64,
};

pub const PageNetworkAlmostIdle = struct {
    req_id: u32,
    frame_id: u32,
    timestamp: u64,
};

pub const PageFrameCreated = struct {
    frame_id: u32,
    parent_id: u32,
    timestamp: u64,
};

pub const RequestStart = struct {
    transfer: *Transfer,
};

pub const RequestIntercept = struct {
    transfer: *Transfer,
    wait_for_interception: *bool,
};

pub const RequestAuthRequired = struct {
    transfer: *Transfer,
    wait_for_interception: *bool,
};

pub const ResponseData = struct {
    data: []const u8,
    transfer: *Transfer,
};

pub const ResponseHeaderDone = struct {
    transfer: *Transfer,
};

pub const RequestDone = struct {
    transfer: *Transfer,
};

pub const RequestFail = struct {
    transfer: *Transfer,
    err: anyerror,
};

pub fn init(allocator: Allocator) !*Notification {
    const notification = try allocator.create(Notification);
    errdefer allocator.destroy(notification);

    notification.* = .{
        .listeners = .{},
        .event_listeners = .{},
        .allocator = allocator,
        .mem_pool = std.heap.MemoryPool(Listener).init(allocator),
    };

    return notification;
}

pub fn deinit(self: *Notification) void {
    const allocator = self.allocator;

    var it = self.listeners.valueIterator();
    while (it.next()) |listener| {
        listener.deinit(allocator);
    }
    self.listeners.deinit(allocator);
    self.mem_pool.deinit();
    allocator.destroy(self);
}

pub fn register(self: *Notification, comptime event: EventType, receiver: anytype, func: EventFunc(event)) !void {
    var list = &@field(self.event_listeners, @tagName(event));

    var listener = try self.mem_pool.create();
    errdefer self.mem_pool.destroy(listener);

    listener.* = .{
        .node = .{},
        .list = list,
        .receiver = receiver,
        .event = event,
        .func = @ptrCast(func),
        .struct_name = @typeName(@typeInfo(@TypeOf(receiver)).pointer.child),
    };

    const allocator = self.allocator;
    const gop = try self.listeners.getOrPut(allocator, @intFromPtr(receiver));
    if (gop.found_existing == false) {
        gop.value_ptr.* = .{};
    }
    try gop.value_ptr.append(allocator, listener);

    // we don't add this until we've successfully added the entry to
    // self.listeners
    list.append(&listener.node);
}

pub fn unregister(self: *Notification, comptime event: EventType, receiver: anytype) void {
    var listeners = self.listeners.getPtr(@intFromPtr(receiver)) orelse return;

    var i: usize = 0;
    while (i < listeners.items.len) {
        const listener = listeners.items[i];
        if (listener.event != event) {
            i += 1;
            continue;
        }
        listener.list.remove(&listener.node);
        self.mem_pool.destroy(listener);
        _ = listeners.swapRemove(i);
    }

    if (listeners.items.len == 0) {
        listeners.deinit(self.allocator);
        const removed = self.listeners.remove(@intFromPtr(receiver));
        lp.assert(removed == true, "Notification.unregister", .{ .type = event });
    }
}

pub fn unregisterAll(self: *Notification, receiver: *anyopaque) void {
    var kv = self.listeners.fetchRemove(@intFromPtr(receiver)) orelse return;
    for (kv.value.items) |listener| {
        listener.list.remove(&listener.node);
        self.mem_pool.destroy(listener);
    }
    kv.value.deinit(self.allocator);
}

pub fn dispatch(self: *Notification, comptime event: EventType, data: ArgType(event)) void {
    if (self.listeners.count() == 0) {
        return;
    }
    const list = &@field(self.event_listeners, @tagName(event));

    var node = list.first;
    while (node) |n| {
        const listener: *Listener = @fieldParentPtr("node", n);
        const func: EventFunc(event) = @ptrCast(@alignCast(listener.func));
        func(listener.receiver, data) catch |err| {
            log.err(.app, "dispatch error", .{
                .err = err,
                .event = event,
                .source = "notification",
                .listener = listener.struct_name,
            });
        };
        node = n.next;
    }
}

// Given an event type enum, returns the type of arg the event emits
fn ArgType(comptime event: Notification.EventType) type {
    inline for (std.meta.fields(Notification.Events)) |f| {
        if (std.mem.eql(u8, f.name, @tagName(event))) {
            return f.type;
        }
    }
    unreachable;
}

// Given an event type enum, returns the listening function type
fn EventFunc(comptime event: Notification.EventType) type {
    return *const fn (*anyopaque, ArgType(event)) anyerror!void;
}

// A listener. This is 1 receiver, with its function, and the linked list
// node that goes in the appropriate EventListeners list.
const Listener = struct {
    // the receiver of the event, i.e. the self parameter to `func`
    receiver: *anyopaque,

    // the function to call
    func: *const anyopaque,

    // For logging slightly better error
    struct_name: []const u8,

    event: Notification.EventType,

    // intrusive linked list node
    node: List.Node,

    // The event list this listener belongs to.
    // We need this in order to be able to remove the node from the list
    list: *List,
};

const testing = std.testing;
test "Notification" {
    var notifier = try Notification.init(testing.allocator);
    defer notifier.deinit();

    // noop
    notifier.dispatch(.page_navigate, &.{
        .frame_id = 0,
        .req_id = 1,
        .timestamp = 4,
        .url = undefined,
        .opts = .{},
    });

    var tc = TestClient{};

    try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
    notifier.dispatch(.page_navigate, &.{
        .frame_id = 0,
        .req_id = 1,
        .timestamp = 4,
        .url = undefined,
        .opts = .{},
    });
    try testing.expectEqual(4, tc.page_navigate);

    notifier.unregisterAll(&tc);
    notifier.dispatch(.page_navigate, &.{
        .frame_id = 0,
        .req_id = 1,
        .timestamp = 10,
        .url = undefined,
        .opts = .{},
    });
    try testing.expectEqual(4, tc.page_navigate);

    try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
    try notifier.register(.page_navigated, &tc, TestClient.pageNavigated);
    notifier.dispatch(.page_navigate, &.{
        .frame_id = 0,
        .req_id = 1,
        .timestamp = 10,
        .url = undefined,
        .opts = .{},
    });
    notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 6, .url = undefined, .opts = .{} });
    try testing.expectEqual(14, tc.page_navigate);
    try testing.expectEqual(6, tc.page_navigated);

    notifier.unregisterAll(&tc);
    notifier.dispatch(.page_navigate, &.{
        .frame_id = 0,
        .req_id = 1,
        .timestamp = 100,
        .url = undefined,
        .opts = .{},
    });
    notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
    try testing.expectEqual(14, tc.page_navigate);
    try testing.expectEqual(6, tc.page_navigated);

    {
        // unregister
        try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
        try notifier.register(.page_navigated, &tc, TestClient.pageNavigated);
        notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
        notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
        try testing.expectEqual(114, tc.page_navigate);
        try testing.expectEqual(1006, tc.page_navigated);

        notifier.unregister(.page_navigate, &tc);
        notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
        notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
        try testing.expectEqual(114, tc.page_navigate);
        try testing.expectEqual(2006, tc.page_navigated);

        notifier.unregister(.page_navigated, &tc);
        notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
        notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
        try testing.expectEqual(114, tc.page_navigate);
        try testing.expectEqual(2006, tc.page_navigated);

        // already unregistered, try anyways
        notifier.unregister(.page_navigated, &tc);
        notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
        notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
        try testing.expectEqual(114, tc.page_navigate);
        try testing.expectEqual(2006, tc.page_navigated);
    }
}

const TestClient = struct {
    page_navigate: u64 = 0,
    page_navigated: u64 = 0,

    fn pageNavigate(ptr: *anyopaque, data: *const Notification.PageNavigate) !void {
        const self: *TestClient = @ptrCast(@alignCast(ptr));
        self.page_navigate += data.timestamp;
    }

    fn pageNavigated(ptr: *anyopaque, data: *const Notification.PageNavigated) !void {
        const self: *TestClient = @ptrCast(@alignCast(ptr));
        self.page_navigated += data.timestamp;
    }
};


================================================
FILE: src/SemanticTree.zig
================================================
// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  See <https://www.gnu.org/licenses/>.

const std = @import("std");

const lp = @import("lightpanda");
const log = @import("log.zig");
const isAllWhitespace = @import("string.zig").isAllWhitespace;
const Page = lp.Page;
const interactive = @import("browser/interactive.zig");

const CData = @import("browser/webapi/CData.zig");
const Element = @import("browser/webapi/Element.zig");
const Node = @import("browser/webapi/Node.zig");
const AXNode = @import("cdp/AXNode.zig");
const CDPNode = @import("cdp/Node.zig");

const Self = @This();

dom_node: *Node,
registry: *CDPNode.Registry,
page: *Page,
arena: std.mem.Allocator,
prune: bool = true,
interactive_only: bool = false,
max_depth: u32 = std.math.maxInt(u32) - 1,

pub fn jsonStringify(self: @This(), jw: *std.json.Stringify) error{WriteFailed}!void {
    var visitor = JsonVisitor{ .jw = jw, .tree = self };
    var xpath_buffer: std.ArrayList(u8) = .{};
    const listener_targets = interactive.buildListenerTargetMap(self.page, self.arena) catch |err| {
        log.err(.app, "listener map failed", .{ .err = err });
        return error.WriteFailed;
    };
    self.walk(self.dom_node, &xpath_buffer, null, &visitor, 1, listener_targets, 0) catch |err| {
        log.err(.app, "semantic tree json dump failed", .{ .err = err });
        return error.WriteFailed;
    };
}

pub fn textStringify(self: @This(), writer: *std.Io.Writer) error{WriteFailed}!void {
    var visitor = TextVisitor{ .writer = writer, .tree = self, .depth = 0 };
    var xpath_buffer: std.ArrayList(u8) = .empty;
    const listener_targets = interactive.buildListenerTargetMap(self.page, self.arena) catch |err| {
        log.err(.app, "listener map failed", .{ .err = err });
        return error.WriteFailed;
    };
    self.walk(self.dom_node, &xpath_buffer, null, &visitor, 1, listener_targets, 0) catch |err| {
        log.err(.app, "semantic tree text dump failed", .{ .err = err });
        return error.WriteFailed;
    };
}

const OptionData = struct {
    value: []const u8,
    text: []const u8,
    selected: bool,
};

const NodeData = struct {
    id: CDPNode.Id,
    axn: AXNode,
    role: []const u8,
    name: ?[]const u8,
    value: ?[]const u8,
    options: ?[]OptionData = null,
    xpath: []const u8,
    is_interactive: bool,
    node_name: []const u8,
};

fn walk(self: @This(), node: *Node, xpath_buffer: *std.ArrayList(u8), parent_name: ?[]const u8, visitor: anytype, index: usize, listener_targets: interactive.ListenerTargetMap, current_depth: u32) !void {
    if (current_depth > self.max_depth) return;

    // 1. Skip non-content nodes
    if (node.is(Element)) |el| {
        const tag = el.getTag();
        if (tag.isMetadata() or tag == .svg) return;

        // We handle options/optgroups natively inside their parents, skip them in the general walk
        if (tag == .datalist or tag == .option or tag == .optgroup) return;

        // Check visibility using the engine's checkVisibility which handles CSS display: none
        if (!el.checkVisibility(self.page)) {
            return;
        }

        if (el.is(Element.Html)) |html_el| {
            if (html_el.getHidden()) return;
        }
    } else if (node.is(CData.Text)) |text_node| {
        const text = text_node.getWholeText();
        if (isAllWhitespace(text)) {
            return;
        }
    } else if (node._type != .document and node._type != .document_fragment) {
        return;
    }

    const cdp_node = try self.registry.register(node);
    const axn = AXNode.fromNode(node);
    const role = try axn.getRole();

    var is_interactive = false;
    var value: ?[]const u8 = null;
    var options: ?[]OptionData = null;
    var node_name: []const u8 = "text";

    if (node.is(Element)) |el| {
        node_name = el.getTagNameLower();

        if (el.is(Element.Html.Input)) |input| {
            value = input.getValue();
            if (el.getAttributeSafe(comptime lp.String.wrap("list"))) |list_id| {
                options = try extractDataListOptions(list_id, self.page, self.arena);
            }
        } else if (el.is(Element.Html.TextArea)) |textarea| {
            value = textarea.getValue();
        } else if (el.is(Element.Html.Select)) |select| {
            value = select.getValue(self.page);
            options = try extractSelectOptions(el.asNode(), self.page, self.arena);
        }

        if (el.is(Element.Html)) |html_el| {
            if (interactive.classifyInteractivity(el, html_el, listener_targets) != null) {
                is_interactive = true;
            }
        }
    } else if (node._type == .document or node._type == .document_fragment) {
        node_name = "root";
    }

    const initial_xpath_len = xpath_buffer.items.len;
    try appendXPathSegment(node, xpath_buffer.writer(self.arena), index);
    const xpath = xpath_buffer.items;

    var name = try axn.getName(self.page, self.arena);

    const has_explicit_label = if (node.is(Element)) |el|
        el.getAttributeSafe(.wrap("aria-label")) != null or el.getAttributeSafe(.wrap("title")) != null
    else
        false;

    const structural = isStructuralRole(role);

    // Filter out computed concatenated names for generic containers without explicit labels.
    // This prevents token bloat and ensures their StaticText children aren't incorrectly pruned.
    // We ignore interactivity because a generic wrapper with an event listener still shouldn't hoist all text.
    if (name != null and structural and !has_explicit_label) {
        name = null;
    }

    var data = NodeData{
        .id = cdp_node.id,
        .axn = axn,
        .role = role,
        .name = name,
        .value = value,
        .options = options,
        .xpath = xpath,
        .is_interactive = is_interactive,
        .node_name = node_name,
    };

    var should_visit = true;
    if (self.interactive_only) {
        var keep = false;
        if (interactive.isInteractiveRole(role)) {
            keep = true;
        } else if (interactive.isContentRole(role)) {
            if (name != null and name.?.len > 0) {
                keep = true;
            }
        } else if (std.mem.eql(u8, role, "RootWebArea")) {
            keep = true;
        } else if (is_interactive) {
            keep = true;
        }
        if (!keep) {
            should_visit = false;
        }
    } else if (self.prune) {
        if (structural and !is_interactive and !has_explicit_label) {
            should_visit = false;
        }

        if (std.mem.eql(u8, role, "StaticText") and node._parent != null) {
            if (parent_name != null and name != null and std.mem.indexOf(u8, parent_name.?, name.?) != null) {
                should_visit = false;
            }
        }
    }

    var did_visit = false;
    var should_walk_children = true;
    if (should_visit) {
        should_walk_children = try visitor.visit(node, &data);
        did_visit = true; // Always true if should_visit was true, because visit() executed and opened structures
    } else {
        // If we skip the node, we must NOT tell the visitor to close it later
        did_visit = false;
    }

    if (should_walk_children) {
        // If we are printing this node normally OR skipping it and unrolling its children,
        // we walk the children iterator.
        var it = node.childrenIterator();
        var tag_counts = std.StringArrayHashMap(usize).init(self.arena);
        while (it.next()) |child| {
            var tag: []const u8 = "text()";
            if (child.is(Element)) |el| {
                tag = el.getTagNameLower();
            }

            const gop = try tag_counts.getOrPut(tag);
            if (!gop.found_existing) {
                gop.value_ptr.* = 0;
            }
            gop.value_ptr.* += 1;

            try self.walk(child, xpath_buffer, name, visitor, gop.value_ptr.*, listener_targets, current_depth + 1);
        }
    }

    if (did_visit) {
        try visitor.leave();
    }

    xpath_buffer.shrinkRetainingCapacity(initial_xpath_len);
}

fn extractSelectOptions(node: *Node, page: *Page, arena: std.mem.Allocator) ![]OptionData {
    var options = std.ArrayListUnmanaged(OptionData){};
    var it = node.childrenIterator();
    while (it.next()) |child| {
        if (child.is(Element)) |el| {
            if (el.getTag() == .option) {
                if (el.is(Element.Html.Option)) |opt| {
                    const text = opt.getText(page);
                    const value = opt.getValue(page);
                    const selected = opt.getSelected();
                    try options.append(arena, .{ .text = text, .value = value, .selected = selected });
                }
            } else if (el.getTag() == .optgroup) {
                var group_it = child.childrenIterator();
                while (group_it.next()) |group_child| {
                    if (group_child.is(Element.Html.Option)) |opt| {
                        const text = opt.getText(page);
                        const value = opt.getValue(page);
                        const selected = opt.getSelected();
                        try options.append(arena, .{ .text = text, .value = value, .selected = selected });
                    }
                }
            }
        }
    }
    return options.toOwnedSlice(arena);
}

fn extractDataListOptions(list_id: []const u8, page: *Page, arena: std.mem.Allocator) !?[]OptionData {
    if (page.document.getElementById(list_id, page)) |referenced_el| {
        if (referenced_el.getTag() == .datalist) {
            return try extractSelectOptions(referenced_el.asNode(), page, arena);
        }
    }
    return null;
}

fn appendXPathSegment(node: *Node, writer: anytype, index: usize) !void {
    if (node.is(Element)) |el| {
        const tag = el.getTagNameLower();
        try std.fmt.format(writer, "/{s}[{d}]", .{ tag, index });
    } else if (node.is(CData.Text)) |_| {
        try std.fmt.format(writer, "/text()[{d}]", .{index});
    }
}

const JsonVisitor = struct {
    jw: *std.json.Stringify,
    tree: Self,

    pub fn visit(self: *JsonVisitor, node: *Node, data: *NodeData) !bool {
        try self.jw.beginObject();

        try self.jw.objectField("nodeId");
        try self.jw.write(try std.fmt.allocPrint(self.tree.arena, "{d}", .{data.id}));

        try self.jw.objectField("backendDOMNodeId");
        try self.jw.write(data.id);

        try self.jw.objectField("nodeName");
        try self.jw.write(data.node_name);

        try self.jw.objectField("xpath");
        try self.jw.write(data.xpath);

        if (node.is(Element)) |el| {
            try self.jw.objectField("nodeType");
            try self.jw.write(1);

            try self.jw.objectField("isInteractive");
            try self.jw.write(data.is_interactive);

            try self.jw.objectField("role");
            try self.jw.write(data.role);

            if (data.name) |name| {
                if (name.len > 0) {
                    try self.jw.objectField("name");
                    try self.jw.write(name);
                }
            }

            if (data.value) |value| {
                try self.jw.objectField("value");
                try self.jw.write(value);
            }

            if (el._attributes) |attrs| {
                try self.jw.objectField("attributes");
                try self.jw.beginObject();
                var iter = attrs.iterator();
                while (iter.next()) |attr| {
                    try self.jw.objectField(attr._name.str());
                    try self.jw.write(attr._value.str());
                }
                try self.jw.endObject();
            }

            if (data.options) |options| {
                try self.jw.objectField("options");
                try self.jw.beginArray();
                for (options) |opt| {
                    try self.jw.beginObject();
                    try self.jw.objectField("value");
                    try self.jw.write(opt.value);
                    try self.jw.objectField("text");
                    try self.jw.write(opt.text);
                    try self.jw.objectField("selected");
                    try self.jw.write(opt.selected);
                    try self.jw.endObject();
                }
                try self.jw.endArray();
            }
        } else if (node.is(CData.Text)) |text_node| {
            try self.jw.objectField("nodeType");
            try self.jw.write(3);
            try self.jw.objectField("nodeValue");
            try self.jw.write(text_node.getWholeText());
        } else {
            try self.jw.objectField("nodeType");
            try self.jw.write(9);
        }

        try self.jw.objectField("children");
        try self.jw.beginArray();

        if (data.options != null) {
            // Signal to not walk children, as we handled them natively
            return false;
        }

        return true;
    }

    pub fn leave(self: *JsonVisitor) !void {
        try self.jw.endArray();
        try self.jw.endObject();
    }
};

fn isStructuralRole(role: []const u8) bool {
    const structural_roles = std.StaticStringMap(void).initComptime(.{
        .{ "none", {} },
        .{ "generic", {} },
        .{ "InlineTextBox", {} },
        .{ "banner", {} },
        .{ "navigation", {} },
        .{ "main", {} },
        .{ "list", {} },
        .{ "listitem", {} },
        .{ "table", {} },
        .{ "rowgroup", {} },
        .{ "row", {} },
        .{ "cell", {} },
        .{ "region", {} },
    });
    return structural_roles.has(role);
}

const TextVisitor = struct {
    writer: *std.Io.Writer,
    tree: Self,
    depth: usize,

    pub fn visit(self: *TextVisitor, node: *Node, data: *NodeData) !bool {
        for (0..self.depth) |_| {
            try self.writer.writeByte(' ');
        }

        var name_to_print: ?[]const u8 = null;
        if (data.name) |n| {
            if (n.len > 0) {
                name_to_print = n;
            }
        } else if (node.is(CData.Text)) |text_node| {
            const trimmed = std.mem.trim(u8, text_node.getWholeText(), " \t\r\n");
            if (trimmed.len > 0) {
                name_to_print = trimmed;
            }
        }

        const is_text_only = std.mem.eql(u8, data.role, "StaticText") or std.mem.eql(u8, data.role, "none") or std.mem.eql(u8, data.role, "generic");

        try self.writer.print("{d}", .{data.id});
        if (!is_text_only) {
            try self.writer.print(" {s}", .{data.role});
        }
        if (name_to_print) |n| {
            try self.writer.print(" '{s}'", .{n});
        }

        if (data.value) |v| {
            if (v.len > 0) {
                try self.writer.print(" value='{s}'", .{v});
            }
        }

        if (data.options) |options| {
            try self.writer.writeAll(" options=[");
            for (options, 0..) |opt, i| {
                if (i > 0) try self.writer.writeAll(",");
                try self.writer.print("'{s}'", .{opt.value});
                if (opt.selected) {
                    try self.writer.writeAll("*");
                }
            }
            try self.writer.writeAll("]\n");
            self.depth += 1;
            return false; // Native handling complete, do not walk children
        }

        try self.writer.writeByte('\n');
        self.depth += 1;

        // If this is a leaf-like semantic node and we already have a name,
        // skip children to avoid redundant StaticText or noise.
        const is_leaf_semantic = std.mem.eql(u8, data.role, "link") or
            std.mem.eql(u8, data.role, "button") or
            std.mem.eql(u8, data.role, "heading") or
            std.mem.eql(u8, data.role, "code");
        if (is_leaf_semantic and data.name != null and data.name.?.len > 0) {
            return false;
        }

        return true;
    }

    pub fn leave(self: *TextVisitor) !void {
        if (self.depth > 0) {
            self.depth -= 1;
        }
    }
};

const testing = @import("testing.zig");

test "SemanticTree backendDOMNodeId" {
    var registry: CDPNode.Registry = .init(testing.allocator);
    defer registry.deinit();

    var page = try testing.pageTest("cdp/registry1.html");
    defer testing.reset();
    defer page._session.removePage();

    const st: Self = .{
        .dom_node = page.window._document.asNode(),
        .registry = &registry,
        .page = page,
        .arena = testing.arena_allocator,
        .prune = false,
        .interactive_only = false,
        .max_depth = std.math.maxInt(u32) - 1,
    };

    const json_str = try std.json.Stringify.valueAlloc(testing.allocator, st, .{});
    defer testing.allocator.free(json_str);

    try testing.expect(std.mem.indexOf(u8, json_str, "\"backendDOMNodeId\":") != null);
}

test "SemanticTree max_depth" {
    var registry: CDPNode.Registry = .init(testing.allocator);
    defer registry.deinit();

    var page = try testing.pageTest("cdp/registry1.html");
    defer testing.reset();
    defer page._session.removePage();

    const st: Self = .{
        .dom_node = page.window._document.asNode(),
        .registry = &registry,
        .page = page,
        .arena = testing.arena_allocator,
        .prune = false,
        .interactive_only = false,
        .max_depth = 1,
    };

    var aw: std.Io.Writer.Allocating = .init(testing.allocator);
    defer aw.deinit();

    try st.textStringify(&aw.writer);
    const text_str = aw.written();

    try testing.expect(std.mem.indexOf(u8, text_str, "other") == null);
}


================================================
FILE: src/Server.zig
================================================
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
//
// Francis Bouvier <francis@lightpanda.io>
// Pierre Tachoire <pierre@lightpanda.io>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

const std = @import("std");
const lp = @import("lightpanda");
const net = std.net;
const posix = std.posix;

const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;

const log = @import("log.zig");
const App = @import("App.zig");
const Config = @import("Config.zig");
const CDP = @import("cdp/cdp.zig").CDP;
const Net = @import("network/websocket.zig");
const HttpClient = @import("browser/HttpClient.zig");

const Server = @This();

app: *App,
allocator: Allocator,
json_version_response: []const u8,

// Thread management
active_threads: std.atomic.Value(u32) = .init(0),
clients: std.ArrayList(*Client) = .{},
client_mutex: std.Thread.Mutex = .{},
clients_pool: std.heap.MemoryPool(Client),

pub fn init(app: *App, address: net.Address) !*Server {
    const allocator = app.allocator;
    const json_version_response = try buildJSONVersionResponse(allocator, address);
    errdefer allocator.free(json_version_response);

    const self = try allocator.create(Server);
    errdefer allocator.destroy(self);

    self.* = .{
        .app = app,
        .allocator = allocator,
        .json_version_response = json_version_response,
        .clients_pool = std.heap.MemoryPool(Client).init(allocator),
    };

    try self.app.network.bind(address, self, onAccept);
    log.info(.app, "server running", .{ .address = address });

    return self;
}

pub fn shutdown(self: *Server) void {
    self.client_mutex.lock();
    defer self.client_mutex.unlock();

    for (self.clients.items) |client| {
        client.stop();
    }
}

pub fn deinit(self: *Server) void {
    self.shutdown();
    self.joinThreads();
    self.clients.deinit(self.allocator);
    self.clients_pool.deinit();
    self.allocator.free(self.json_version_response);
    self.allocator.destroy(self);
}

fn onAccept(ctx: *anyopaque, socket: posix.socket_t) void {
    const self: *Server = @ptrCast(@alignCast(ctx));
    const timeout_ms: u32 = @intCast(self.app.config.cdpTimeout());
    self.spawnWorker(socket, timeout_ms) catch |err| {
        log.err(.app, "CDP spawn", .{ .err = err });
        posix.close(socket);
    };
}

fn handleConnection(self: *Server, socket: posix.socket_t, timeout_ms: u32) void {
    defer posix.close(socket);

    // Client is HUGE (> 512KB) because it has a large rea
Download .txt
gitextract_h4l2nhcz/

├── .github/
│   ├── actions/
│   │   └── install/
│   │       └── action.yml
│   └── workflows/
│       ├── cla.yml
│       ├── e2e-integration-test.yml
│       ├── e2e-test.yml
│       ├── nightly.yml
│       ├── wpt.yml
│       └── zig-test.yml
├── .gitignore
├── CLA.md
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── LICENSING.md
├── Makefile
├── README.md
├── build.zig
├── build.zig.zon
├── flake.nix
└── src/
    ├── App.zig
    ├── ArenaPool.zig
    ├── Config.zig
    ├── Notification.zig
    ├── SemanticTree.zig
    ├── Server.zig
    ├── Sighandler.zig
    ├── TestHTTPServer.zig
    ├── browser/
    │   ├── Browser.zig
    │   ├── EventManager.zig
    │   ├── Factory.zig
    │   ├── HttpClient.zig
    │   ├── Mime.zig
    │   ├── Page.zig
    │   ├── ScriptManager.zig
    │   ├── Session.zig
    │   ├── URL.zig
    │   ├── actions.zig
    │   ├── color.zig
    │   ├── css/
    │   │   ├── Parser.zig
    │   │   └── Tokenizer.zig
    │   ├── dump.zig
    │   ├── interactive.zig
    │   ├── js/
    │   │   ├── Array.zig
    │   │   ├── BigInt.zig
    │   │   ├── Caller.zig
    │   │   ├── Context.zig
    │   │   ├── Env.zig
    │   │   ├── Function.zig
    │   │   ├── HandleScope.zig
    │   │   ├── Inspector.zig
    │   │   ├── Integer.zig
    │   │   ├── Isolate.zig
    │   │   ├── Local.zig
    │   │   ├── Module.zig
    │   │   ├── Number.zig
    │   │   ├── Object.zig
    │   │   ├── Origin.zig
    │   │   ├── Platform.zig
    │   │   ├── Private.zig
    │   │   ├── Promise.zig
    │   │   ├── PromiseRejection.zig
    │   │   ├── PromiseResolver.zig
    │   │   ├── Scheduler.zig
    │   │   ├── Snapshot.zig
    │   │   ├── String.zig
    │   │   ├── TaggedOpaque.zig
    │   │   ├── TryCatch.zig
    │   │   ├── Value.zig
    │   │   ├── bridge.zig
    │   │   └── js.zig
    │   ├── markdown.zig
    │   ├── parser/
    │   │   ├── Parser.zig
    │   │   └── html5ever.zig
    │   ├── reflect.zig
    │   ├── structured_data.zig
    │   ├── tests/
    │   │   ├── animation/
    │   │   │   └── animation.html
    │   │   ├── blob.html
    │   │   ├── canvas/
    │   │   │   ├── canvas_rendering_context_2d.html
    │   │   │   ├── offscreen_canvas.html
    │   │   │   └── webgl_rendering_context.html
    │   │   ├── cdata/
    │   │   │   ├── cdata_section.html
    │   │   │   ├── character_data.html
    │   │   │   ├── comment.html
    │   │   │   ├── data.html
    │   │   │   └── text.html
    │   │   ├── cdp/
    │   │   │   ├── dom1.html
    │   │   │   ├── dom2.html
    │   │   │   ├── dom3.html
    │   │   │   ├── registry1.html
    │   │   │   ├── registry2.html
    │   │   │   └── registry3.html
    │   │   ├── collections/
    │   │   │   └── radio_node_list.html
    │   │   ├── console/
    │   │   │   └── console.html
    │   │   ├── crypto.html
    │   │   ├── css/
    │   │   │   ├── font_face.html
    │   │   │   ├── font_face_set.html
    │   │   │   ├── media_query_list.html
    │   │   │   └── stylesheet.html
    │   │   ├── css.html
    │   │   ├── custom_elements/
    │   │   │   ├── attribute_changed.html
    │   │   │   ├── built_in.html
    │   │   │   ├── connected.html
    │   │   │   ├── connected_from_parser.html
    │   │   │   ├── constructor.html
    │   │   │   ├── disconnected.html
    │   │   │   ├── registry.html
    │   │   │   ├── throw_on_dynamic_markup_insertion.html
    │   │   │   └── upgrade.html
    │   │   ├── document/
    │   │   │   ├── adopt_import.html
    │   │   │   ├── all_collection.html
    │   │   │   ├── children.html
    │   │   │   ├── collections.html
    │   │   │   ├── create_element.html
    │   │   │   ├── create_element_ns.html
    │   │   │   ├── document-title.html
    │   │   │   ├── document.html
    │   │   │   ├── element_from_point.html
    │   │   │   ├── focus.html
    │   │   │   ├── get_element_by_id.html
    │   │   │   ├── get_elements_by_class_name-multiple.html
    │   │   │   ├── get_elements_by_class_name.html
    │   │   │   ├── get_elements_by_name.html
    │   │   │   ├── get_elements_by_tag_name-wildcard.html
    │   │   │   ├── get_elements_by_tag_name.html
    │   │   │   ├── insert_adjacent_element.html
    │   │   │   ├── insert_adjacent_html.html
    │   │   │   ├── insert_adjacent_text.html
    │   │   │   ├── query_selector.html
    │   │   │   ├── query_selector_all.html
    │   │   │   ├── query_selector_attributes.html
    │   │   │   ├── query_selector_edge_cases.html
    │   │   │   ├── query_selector_not.html
    │   │   │   ├── replace_children.html
    │   │   │   └── write.html
    │   │   ├── document_fragment/
    │   │   │   ├── document_fragment.html
    │   │   │   └── insertion.html
    │   │   ├── document_head_body.html
    │   │   ├── domexception.html
    │   │   ├── domimplementation.html
    │   │   ├── domparser.html
    │   │   ├── element/
    │   │   │   ├── append.html
    │   │   │   ├── attributes.html
    │   │   │   ├── bounding_rect.html
    │   │   │   ├── class_list.html
    │   │   │   ├── closest.html
    │   │   │   ├── css_style_properties.html
    │   │   │   ├── dataset.html
    │   │   │   ├── duplicate_ids.html
    │   │   │   ├── element.html
    │   │   │   ├── get_elements_by_class_name.html
    │   │   │   ├── get_elements_by_tag_name.html
    │   │   │   ├── get_elements_by_tag_name_ns.html
    │   │   │   ├── html/
    │   │   │   │   ├── anchor.html
    │   │   │   │   ├── button.html
    │   │   │   │   ├── details.html
    │   │   │   │   ├── dialog.html
    │   │   │   │   ├── event_listeners.html
    │   │   │   │   ├── fieldset.html
    │   │   │   │   ├── form.html
    │   │   │   │   ├── htmlelement-props.html
    │   │   │   │   ├── image.html
    │   │   │   │   ├── input-attrs.html
    │   │   │   │   ├── input.html
    │   │   │   │   ├── input_click.html
    │   │   │   │   ├── input_radio.html
    │   │   │   │   ├── label.html
    │   │   │   │   ├── li.html
    │   │   │   │   ├── link.html
    │   │   │   │   ├── media.html
    │   │   │   │   ├── ol.html
    │   │   │   │   ├── optgroup.html
    │   │   │   │   ├── option.html
    │   │   │   │   ├── picture.html
    │   │   │   │   ├── quote.html
    │   │   │   │   ├── script/
    │   │   │   │   │   ├── async_text.html
    │   │   │   │   │   ├── dynamic.html
    │   │   │   │   │   ├── dynamic1.js
    │   │   │   │   │   ├── dynamic2.js
    │   │   │   │   │   ├── dynamic_inline.html
    │   │   │   │   │   ├── empty.js
    │   │   │   │   │   ├── order.html
    │   │   │   │   │   ├── order.js
    │   │   │   │   │   ├── order_async.js
    │   │   │   │   │   ├── order_defer.js
    │   │   │   │   │   └── script.html
    │   │   │   │   ├── select.html
    │   │   │   │   ├── slot.html
    │   │   │   │   ├── style.html
    │   │   │   │   ├── tablecell.html
    │   │   │   │   ├── template.html
    │   │   │   │   ├── textarea.html
    │   │   │   │   ├── time.html
    │   │   │   │   └── track.html
    │   │   │   ├── inner.html
    │   │   │   ├── inner.js
    │   │   │   ├── matches.html
    │   │   │   ├── outer.html
    │   │   │   ├── position.html
    │   │   │   ├── pseudo_classes.html
    │   │   │   ├── query_selector.html
    │   │   │   ├── query_selector_all.html
    │   │   │   ├── query_selector_scope.html
    │   │   │   ├── remove.html
    │   │   │   ├── replace_with.html
    │   │   │   ├── selector_invalid.html
    │   │   │   ├── styles.html
    │   │   │   └── svg/
    │   │   │       └── svg.html
    │   │   ├── encoding/
    │   │   │   ├── text_decoder.html
    │   │   │   └── text_encoder.html
    │   │   ├── event/
    │   │   │   ├── abort_controller.html
    │   │   │   ├── composition.html
    │   │   │   ├── custom_event.html
    │   │   │   ├── error.html
    │   │   │   ├── focus.html
    │   │   │   ├── keyboard.html
    │   │   │   ├── listener_removal.html
    │   │   │   ├── message.html
    │   │   │   ├── message_multiple_listeners.html
    │   │   │   ├── mouse.html
    │   │   │   ├── pointer.html
    │   │   │   ├── promise_rejection.html
    │   │   │   ├── report_error.html
    │   │   │   ├── text.html
    │   │   │   ├── ui.html
    │   │   │   └── wheel.html
    │   │   ├── events.html
    │   │   ├── file.html
    │   │   ├── file_reader.html
    │   │   ├── frames/
    │   │   │   ├── frames.html
    │   │   │   ├── post_message.html
    │   │   │   ├── support/
    │   │   │   │   ├── after_link.html
    │   │   │   │   ├── message_receiver.html
    │   │   │   │   ├── page.html
    │   │   │   │   ├── sub 1.html
    │   │   │   │   ├── sub2.html
    │   │   │   │   └── with_link.html
    │   │   │   └── target.html
    │   │   ├── history.html
    │   │   ├── history_after_nav.skip.html
    │   │   ├── image_data.html
    │   │   ├── integration/
    │   │   │   └── custom_element_composition.html
    │   │   ├── intersection_observer/
    │   │   │   ├── basic.html
    │   │   │   ├── disconnect.html
    │   │   │   ├── multiple_targets.html
    │   │   │   └── unobserve.html
    │   │   ├── legacy/
    │   │   │   ├── browser.html
    │   │   │   ├── crypto.html
    │   │   │   ├── css.html
    │   │   │   ├── cssom/
    │   │   │   │   ├── css_style_declaration.html
    │   │   │   │   └── css_stylesheet.html
    │   │   │   ├── dom/
    │   │   │   │   ├── animation.html
    │   │   │   │   ├── attribute.html
    │   │   │   │   ├── character_data.html
    │   │   │   │   ├── comment.html
    │   │   │   │   ├── document.html
    │   │   │   │   ├── document_fragment.html
    │   │   │   │   ├── document_type.html
    │   │   │   │   ├── dom_parser.html
    │   │   │   │   ├── element.html
    │   │   │   │   ├── event_target.html
    │   │   │   │   ├── exceptions.html
    │   │   │   │   ├── html_collection.html
    │   │   │   │   ├── implementation.html
    │   │   │   │   ├── intersection_observer.html
    │   │   │   │   ├── named_node_map.html
    │   │   │   │   ├── node_filter.html
    │   │   │   │   ├── node_list.html
    │   │   │   │   ├── node_owner.html
    │   │   │   │   ├── performance.html
    │   │   │   │   ├── performance_observer.html
    │   │   │   │   ├── processing_instruction.html
    │   │   │   │   ├── range.html
    │   │   │   │   ├── text.html
    │   │   │   │   └── token_list.html
    │   │   │   ├── encoding/
    │   │   │   │   ├── decoder.html
    │   │   │   │   └── encoder.html
    │   │   │   ├── events/
    │   │   │   │   ├── composition.html
    │   │   │   │   ├── custom.html
    │   │   │   │   ├── event.html
    │   │   │   │   ├── keyboard.html
    │   │   │   │   └── mouse.html
    │   │   │   ├── fetch/
    │   │   │   │   ├── fetch.html
    │   │   │   │   ├── headers.html
    │   │   │   │   ├── request.html
    │   │   │   │   └── response.html
    │   │   │   ├── file/
    │   │   │   │   ├── blob.html
    │   │   │   │   └── file.html
    │   │   │   ├── html/
    │   │   │   │   ├── abort_controller.html
    │   │   │   │   ├── canvas.html
    │   │   │   │   ├── dataset.html
    │   │   │   │   ├── document.html
    │   │   │   │   ├── element.html
    │   │   │   │   ├── error_event.html
    │   │   │   │   ├── history/
    │   │   │   │   │   ├── history.html
    │   │   │   │   │   ├── history2.html
    │   │   │   │   │   └── history_after_nav.skip.html
    │   │   │   │   ├── image.html
    │   │   │   │   ├── input.html
    │   │   │   │   ├── link.html
    │   │   │   │   ├── location.html
    │   │   │   │   ├── navigation/
    │   │   │   │   │   ├── navigation.html
    │   │   │   │   │   ├── navigation_after_nav.skip.html
    │   │   │   │   │   └── navigation_currententrychange.html
    │   │   │   │   ├── navigator.html
    │   │   │   │   ├── screen.html
    │   │   │   │   ├── script/
    │   │   │   │   │   ├── dynamic_import.html
    │   │   │   │   │   ├── import.html
    │   │   │   │   │   ├── import.js
    │   │   │   │   │   ├── import2.js
    │   │   │   │   │   ├── importmap.html
    │   │   │   │   │   ├── inline_defer.html
    │   │   │   │   │   ├── inline_defer.js
    │   │   │   │   │   ├── order.html
    │   │   │   │   │   ├── order.js
    │   │   │   │   │   ├── order_async.js
    │   │   │   │   │   ├── order_defer.js
    │   │   │   │   │   └── script.html
    │   │   │   │   ├── select.html
    │   │   │   │   ├── slot.html
    │   │   │   │   ├── style.html
    │   │   │   │   └── svg.html
    │   │   │   ├── storage/
    │   │   │   │   └── local_storage.html
    │   │   │   ├── streams/
    │   │   │   │   └── readable_stream.html
    │   │   │   ├── testing.js
    │   │   │   ├── url/
    │   │   │   │   ├── url.html
    │   │   │   │   └── url_search_params.html
    │   │   │   ├── window/
    │   │   │   │   ├── frames.html
    │   │   │   │   └── window.html
    │   │   │   ├── xhr/
    │   │   │   │   ├── form_data.html
    │   │   │   │   ├── progress_event.html
    │   │   │   │   └── xhr.html
    │   │   │   └── xmlserializer.html
    │   │   ├── mcp_actions.html
    │   │   ├── media/
    │   │   │   ├── mediaerror.html
    │   │   │   └── vttcue.html
    │   │   ├── message_channel.html
    │   │   ├── mutation_observer/
    │   │   │   ├── attribute_filter.html
    │   │   │   ├── character_data.html
    │   │   │   ├── childlist.html
    │   │   │   ├── multiple_observers.html
    │   │   │   ├── mutation_observer.html
    │   │   │   ├── mutations_during_callback.html
    │   │   │   ├── observe_multiple_targets.html
    │   │   │   ├── reobserve_same_target.html
    │   │   │   └── subtree.html
    │   │   ├── navigator/
    │   │   │   └── navigator.html
    │   │   ├── net/
    │   │   │   ├── fetch.html
    │   │   │   ├── form_data.html
    │   │   │   ├── headers.html
    │   │   │   ├── request.html
    │   │   │   ├── response.html
    │   │   │   ├── url_search_params.html
    │   │   │   └── xhr.html
    │   │   ├── node/
    │   │   │   ├── adoption.html
    │   │   │   ├── append_child.html
    │   │   │   ├── base_uri.html
    │   │   │   ├── child_nodes.html
    │   │   │   ├── clone_node.html
    │   │   │   ├── compare_document_position.html
    │   │   │   ├── insert_before.html
    │   │   │   ├── is_connected.html
    │   │   │   ├── is_equal_node.html
    │   │   │   ├── node.html
    │   │   │   ├── node_iterator.html
    │   │   │   ├── normalize.html
    │   │   │   ├── noscript_serialization.html
    │   │   │   ├── owner.html
    │   │   │   ├── remove_child.html
    │   │   │   ├── replace_child.html
    │   │   │   ├── text_content.html
    │   │   │   ├── tree.html
    │   │   │   └── tree_walker.html
    │   │   ├── page/
    │   │   │   ├── blob.html
    │   │   │   ├── load_event.html
    │   │   │   ├── meta.html
    │   │   │   ├── mod1.js
    │   │   │   ├── module.html
    │   │   │   └── modules/
    │   │   │       ├── base.js
    │   │   │       ├── circular-a.js
    │   │   │       ├── circular-b.js
    │   │   │       ├── dynamic-chain-a.js
    │   │   │       ├── dynamic-chain-b.js
    │   │   │       ├── dynamic-chain-c.js
    │   │   │       ├── dynamic-circular-x.js
    │   │   │       ├── dynamic-circular-y.js
    │   │   │       ├── importer.js
    │   │   │       ├── mixed-circular-dynamic.js
    │   │   │       ├── mixed-circular-static.js
    │   │   │       ├── re-exporter.js
    │   │   │       ├── self_async.js
    │   │   │       ├── shared.js
    │   │   │       ├── syntax-error.js
    │   │   │       ├── test-404.js
    │   │   │       └── test-syntax-error.js
    │   │   ├── performance.html
    │   │   ├── performance_observer/
    │   │   │   └── performance_observer.html
    │   │   ├── polyfill/
    │   │   │   └── webcomponents.html
    │   │   ├── processing_instruction.html
    │   │   ├── range.html
    │   │   ├── range_mutations.html
    │   │   ├── selection.html
    │   │   ├── shadowroot/
    │   │   │   ├── basic.html
    │   │   │   ├── custom_elements.html
    │   │   │   ├── dom_traversal.html
    │   │   │   ├── dump.html
    │   │   │   ├── edge_cases.html
    │   │   │   ├── events.html
    │   │   │   ├── id_collision.html
    │   │   │   ├── id_management.html
    │   │   │   ├── innerHTML_spec.html
    │   │   │   └── scoping.html
    │   │   ├── storage.html
    │   │   ├── streams/
    │   │   │   ├── readable_stream.html
    │   │   │   ├── text_decoder_stream.html
    │   │   │   └── transform_stream.html
    │   │   ├── support/
    │   │   │   └── history.html
    │   │   ├── testing.js
    │   │   ├── url.html
    │   │   ├── window/
    │   │   │   ├── body_onload1.html
    │   │   │   ├── body_onload2.html
    │   │   │   ├── body_onload3.html
    │   │   │   ├── location.html
    │   │   │   ├── named_access.html
    │   │   │   ├── onerror.html
    │   │   │   ├── report_error.html
    │   │   │   ├── screen.html
    │   │   │   ├── scroll.html
    │   │   │   ├── stubs.html
    │   │   │   ├── timers.html
    │   │   │   ├── visual_viewport.html
    │   │   │   ├── window.html
    │   │   │   └── window_event.html
    │   │   ├── window_scroll.html
    │   │   └── xmlserializer.html
    │   └── webapi/
    │       ├── AbortController.zig
    │       ├── AbortSignal.zig
    │       ├── AbstractRange.zig
    │       ├── Blob.zig
    │       ├── CData.zig
    │       ├── CSS.zig
    │       ├── Console.zig
    │       ├── Crypto.zig
    │       ├── CustomElementDefinition.zig
    │       ├── CustomElementRegistry.zig
    │       ├── DOMException.zig
    │       ├── DOMImplementation.zig
    │       ├── DOMNodeIterator.zig
    │       ├── DOMParser.zig
    │       ├── DOMRect.zig
    │       ├── DOMTreeWalker.zig
    │       ├── Document.zig
    │       ├── DocumentFragment.zig
    │       ├── DocumentType.zig
    │       ├── Element.zig
    │       ├── Event.zig
    │       ├── EventTarget.zig
    │       ├── File.zig
    │       ├── FileList.zig
    │       ├── FileReader.zig
    │       ├── HTMLDocument.zig
    │       ├── History.zig
    │       ├── IdleDeadline.zig
    │       ├── ImageData.zig
    │       ├── IntersectionObserver.zig
    │       ├── KeyValueList.zig
    │       ├── Location.zig
    │       ├── MessageChannel.zig
    │       ├── MessagePort.zig
    │       ├── MutationObserver.zig
    │       ├── Navigator.zig
    │       ├── Node.zig
    │       ├── NodeFilter.zig
    │       ├── Performance.zig
    │       ├── PerformanceObserver.zig
    │       ├── Permissions.zig
    │       ├── PluginArray.zig
    │       ├── Range.zig
    │       ├── ResizeObserver.zig
    │       ├── Screen.zig
    │       ├── Selection.zig
    │       ├── ShadowRoot.zig
    │       ├── StorageManager.zig
    │       ├── SubtleCrypto.zig
    │       ├── TreeWalker.zig
    │       ├── URL.zig
    │       ├── VisualViewport.zig
    │       ├── Window.zig
    │       ├── XMLDocument.zig
    │       ├── XMLSerializer.zig
    │       ├── animation/
    │       │   └── Animation.zig
    │       ├── canvas/
    │       │   ├── CanvasRenderingContext2D.zig
    │       │   ├── OffscreenCanvas.zig
    │       │   ├── OffscreenCanvasRenderingContext2D.zig
    │       │   └── WebGLRenderingContext.zig
    │       ├── cdata/
    │       │   ├── CDATASection.zig
    │       │   ├── Comment.zig
    │       │   ├── ProcessingInstruction.zig
    │       │   └── Text.zig
    │       ├── children.zig
    │       ├── collections/
    │       │   ├── ChildNodes.zig
    │       │   ├── DOMTokenList.zig
    │       │   ├── HTMLAllCollection.zig
    │       │   ├── HTMLCollection.zig
    │       │   ├── HTMLFormControlsCollection.zig
    │       │   ├── HTMLOptionsCollection.zig
    │       │   ├── NodeList.zig
    │       │   ├── RadioNodeList.zig
    │       │   ├── iterator.zig
    │       │   └── node_live.zig
    │       ├── collections.zig
    │       ├── css/
    │       │   ├── CSSRule.zig
    │       │   ├── CSSRuleList.zig
    │       │   ├── CSSStyleDeclaration.zig
    │       │   ├── CSSStyleProperties.zig
    │       │   ├── CSSStyleRule.zig
    │       │   ├── CSSStyleSheet.zig
    │       │   ├── FontFace.zig
    │       │   ├── FontFaceSet.zig
    │       │   ├── MediaQueryList.zig
    │       │   └── StyleSheetList.zig
    │       ├── element/
    │       │   ├── Attribute.zig
    │       │   ├── DOMStringMap.zig
    │       │   ├── Html.zig
    │       │   ├── Svg.zig
    │       │   ├── html/
    │       │   │   ├── Anchor.zig
    │       │   │   ├── Area.zig
    │       │   │   ├── Audio.zig
    │       │   │   ├── BR.zig
    │       │   │   ├── Base.zig
    │       │   │   ├── Body.zig
    │       │   │   ├── Button.zig
    │       │   │   ├── Canvas.zig
    │       │   │   ├── Custom.zig
    │       │   │   ├── DList.zig
    │       │   │   ├── Data.zig
    │       │   │   ├── DataList.zig
    │       │   │   ├── Details.zig
    │       │   │   ├── Dialog.zig
    │       │   │   ├── Directory.zig
    │       │   │   ├── Div.zig
    │       │   │   ├── Embed.zig
    │       │   │   ├── FieldSet.zig
    │       │   │   ├── Font.zig
    │       │   │   ├── Form.zig
    │       │   │   ├── Generic.zig
    │       │   │   ├── HR.zig
    │       │   │   ├── Head.zig
    │       │   │   ├── Heading.zig
    │       │   │   ├── Html.zig
    │       │   │   ├── IFrame.zig
    │       │   │   ├── Image.zig
    │       │   │   ├── Input.zig
    │       │   │   ├── LI.zig
    │       │   │   ├── Label.zig
    │       │   │   ├── Legend.zig
    │       │   │   ├── Link.zig
    │       │   │   ├── Map.zig
    │       │   │   ├── Media.zig
    │       │   │   ├── Meta.zig
    │       │   │   ├── Meter.zig
    │       │   │   ├── Mod.zig
    │       │   │   ├── OL.zig
    │       │   │   ├── Object.zig
    │       │   │   ├── OptGroup.zig
    │       │   │   ├── Option.zig
    │       │   │   ├── Output.zig
    │       │   │   ├── Paragraph.zig
    │       │   │   ├── Param.zig
    │       │   │   ├── Picture.zig
    │       │   │   ├── Pre.zig
    │       │   │   ├── Progress.zig
    │       │   │   ├── Quote.zig
    │       │   │   ├── Script.zig
    │       │   │   ├── Select.zig
    │       │   │   ├── Slot.zig
    │       │   │   ├── Source.zig
    │       │   │   ├── Span.zig
    │       │   │   ├── Style.zig
    │       │   │   ├── Table.zig
    │       │   │   ├── TableCaption.zig
    │       │   │   ├── TableCell.zig
    │       │   │   ├── TableCol.zig
    │       │   │   ├── TableRow.zig
    │       │   │   ├── TableSection.zig
    │       │   │   ├── Template.zig
    │       │   │   ├── TextArea.zig
    │       │   │   ├── Time.zig
    │       │   │   ├── Title.zig
    │       │   │   ├── Track.zig
    │       │   │   ├── UL.zig
    │       │   │   ├── Unknown.zig
    │       │   │   └── Video.zig
    │       │   └── svg/
    │       │       ├── Generic.zig
    │       │       └── Rect.zig
    │       ├── encoding/
    │       │   ├── TextDecoder.zig
    │       │   ├── TextDecoderStream.zig
    │       │   ├── TextEncoder.zig
    │       │   └── TextEncoderStream.zig
    │       ├── event/
    │       │   ├── CompositionEvent.zig
    │       │   ├── CustomEvent.zig
    │       │   ├── ErrorEvent.zig
    │       │   ├── FocusEvent.zig
    │       │   ├── InputEvent.zig
    │       │   ├── KeyboardEvent.zig
    │       │   ├── MessageEvent.zig
    │       │   ├── MouseEvent.zig
    │       │   ├── NavigationCurrentEntryChangeEvent.zig
    │       │   ├── PageTransitionEvent.zig
    │       │   ├── PointerEvent.zig
    │       │   ├── PopStateEvent.zig
    │       │   ├── ProgressEvent.zig
    │       │   ├── PromiseRejectionEvent.zig
    │       │   ├── TextEvent.zig
    │       │   ├── UIEvent.zig
    │       │   └── WheelEvent.zig
    │       ├── global_event_handlers.zig
    │       ├── media/
    │       │   ├── MediaError.zig
    │       │   ├── TextTrackCue.zig
    │       │   └── VTTCue.zig
    │       ├── navigation/
    │       │   ├── Navigation.zig
    │       │   ├── NavigationActivation.zig
    │       │   ├── NavigationHistoryEntry.zig
    │       │   └── root.zig
    │       ├── net/
    │       │   ├── Fetch.zig
    │       │   ├── FormData.zig
    │       │   ├── Headers.zig
    │       │   ├── Request.zig
    │       │   ├── Response.zig
    │       │   ├── URLSearchParams.zig
    │       │   ├── XMLHttpRequest.zig
    │       │   └── XMLHttpRequestEventTarget.zig
    │       ├── selector/
    │       │   ├── List.zig
    │       │   ├── Parser.zig
    │       │   └── Selector.zig
    │       ├── storage/
    │       │   ├── Cookie.zig
    │       │   └── storage.zig
    │       └── streams/
    │           ├── ReadableStream.zig
    │           ├── ReadableStreamDefaultController.zig
    │           ├── ReadableStreamDefaultReader.zig
    │           ├── TransformStream.zig
    │           ├── WritableStream.zig
    │           ├── WritableStreamDefaultController.zig
    │           └── WritableStreamDefaultWriter.zig
    ├── cdp/
    │   ├── AXNode.zig
    │   ├── Node.zig
    │   ├── cdp.zig
    │   ├── domains/
    │   │   ├── accessibility.zig
    │   │   ├── browser.zig
    │   │   ├── css.zig
    │   │   ├── dom.zig
    │   │   ├── emulation.zig
    │   │   ├── fetch.zig
    │   │   ├── input.zig
    │   │   ├── inspector.zig
    │   │   ├── log.zig
    │   │   ├── lp.zig
    │   │   ├── network.zig
    │   │   ├── page.zig
    │   │   ├── performance.zig
    │   │   ├── runtime.zig
    │   │   ├── security.zig
    │   │   ├── storage.zig
    │   │   └── target.zig
    │   ├── id.zig
    │   └── testing.zig
    ├── crash_handler.zig
    ├── crypto.zig
    ├── data/
    │   ├── public_suffix_list.zig
    │   └── public_suffix_list_gen.go
    ├── datetime.zig
    ├── html5ever/
    │   ├── Cargo.toml
    │   ├── lib.rs
    │   ├── sink.rs
    │   └── types.rs
    ├── id.zig
    ├── lightpanda.zig
    ├── log.zig
    ├── main.zig
    ├── main_legacy_test.zig
    ├── main_snapshot_creator.zig
    ├── mcp/
    │   ├── Server.zig
    │   ├── protocol.zig
    │   ├── resources.zig
    │   ├── router.zig
    │   └── tools.zig
    ├── mcp.zig
    ├── network/
    │   ├── Robots.zig
    │   ├── Runtime.zig
    │   ├── WebBotAuth.zig
    │   ├── http.zig
    │   └── websocket.zig
    ├── slab.zig
    ├── string.zig
    ├── sys/
    │   └── libcurl.zig
    ├── telemetry/
    │   ├── lightpanda.zig
    │   └── telemetry.zig
    ├── test_runner.zig
    └── testing.zig
Download .txt
SYMBOL INDEX (101 symbols across 15 files)

FILE: src/browser/tests/legacy/testing.js
  function expectEqual (line 14) | function expectEqual(expected, actual) {
  function expectError (line 29) | function expectError(expected, fn) {
  function withError (line 35) | function withError(cb, fn) {
  function skip (line 45) | function skip() {
  function assertOk (line 50) | function assertOk() {
  function eventually (line 91) | function eventually(fn) {
  function async (line 102) | async function async(promise, cb) {
  function _recordExecution (line 113) | function _recordExecution() {
  function _registerErrorCallback (line 128) | function _registerErrorCallback() {
  function _equal (line 151) | function _equal(a, b) {

FILE: src/browser/tests/page/modules/circular-a.js
  function getFromB (line 5) | function getFromB() {

FILE: src/browser/tests/page/modules/circular-b.js
  function getBValue (line 5) | function getBValue() {
  function getFromA (line 9) | function getFromA() {

FILE: src/browser/tests/page/modules/dynamic-chain-a.js
  function loadChain (line 1) | async function loadChain() {

FILE: src/browser/tests/page/modules/dynamic-chain-b.js
  function loadNext (line 1) | async function loadNext() {

FILE: src/browser/tests/page/modules/dynamic-circular-x.js
  function loadY (line 3) | async function loadY() {

FILE: src/browser/tests/page/modules/dynamic-circular-y.js
  function loadX (line 3) | async function loadX() {

FILE: src/browser/tests/page/modules/mixed-circular-dynamic.js
  function getStaticValue (line 5) | function getStaticValue() {

FILE: src/browser/tests/page/modules/mixed-circular-static.js
  function loadDynamicSide (line 3) | async function loadDynamicSide() {

FILE: src/browser/tests/page/modules/shared.js
  function increment (line 3) | function increment() {
  function getCount (line 7) | function getCount() {

FILE: src/browser/tests/testing.js
  function expectTrue (line 8) | function expectTrue(actual) {
  function expectFalse (line 12) | function expectFalse(actual) {
  function expectEqual (line 16) | function expectEqual(expected, actual, opts) {
  function fail (line 31) | function fail(reason) {
  function expectError (line 37) | function expectError(expected, fn) {
  function withError (line 43) | function withError(cb, fn) {
  function eventually (line 55) | function eventually(cb) {
  function async (line 66) | async function async(cb) {
  function assertOk (line 72) | function assertOk() {
  function _equal (line 140) | function _equal(expected, actual) {
  function _registerObservation (line 174) | function _registerObservation(status, opts) {
  function _currentScriptId (line 195) | function _currentScriptId() {
  function _displayValue (line 212) | function _displayValue(value) {

FILE: src/data/public_suffix_list_gen.go
  function main (line 10) | func main() {

FILE: src/html5ever/lib.rs
  function html5ever_parse_document (line 35) | pub extern "C" fn html5ever_parse_document(
  function html5ever_parse_fragment (line 89) | pub extern "C" fn html5ever_parse_fragment(
  function html5ever_attribute_iterator_next (line 149) | pub extern "C" fn html5ever_attribute_iterator_next(
  function html5ever_attribute_iterator_count (line 171) | pub extern "C" fn html5ever_attribute_iterator_count(c_iter: *const c_vo...
  type Memory (line 178) | pub struct Memory {
  function html5ever_get_memory_usage (line 185) | pub extern "C" fn html5ever_get_memory_usage() -> Memory {
  type StreamingParser (line 199) | pub struct StreamingParser {
  function html5ever_streaming_parser_create (line 206) | pub extern "C" fn html5ever_streaming_parser_create(
  function html5ever_streaming_parser_feed (line 265) | pub extern "C" fn html5ever_streaming_parser_feed(
  function html5ever_streaming_parser_finish (line 300) | pub extern "C" fn html5ever_streaming_parser_finish(parser_ptr: *mut c_v...
  function html5ever_streaming_parser_destroy (line 320) | pub extern "C" fn html5ever_streaming_parser_destroy(parser_ptr: *mut c_...
  function xml5ever_parse_document (line 333) | pub extern "C" fn xml5ever_parse_document(

FILE: src/html5ever/sink.rs
  type Arena (line 30) | type Arena<'arena> = &'arena typed_arena::Arena<ElementData>;
  type ElementData (line 33) | pub struct ElementData {
    method new (line 38) | fn new(qname: QualName, flags: ElementFlags) -> Self {
  type Sink (line 46) | pub struct Sink<'arena> {
  type Handle (line 68) | type Handle = *const c_void;
  type Output (line 69) | type Output = ();
  type ElemName (line 70) | type ElemName<'a>
  method finish (line 75) | fn finish(self) -> () {
  method parse_error (line 79) | fn parse_error(&self, err: Cow<'static, str>) {
  method get_document (line 91) | fn get_document(&self) -> *const c_void {
  method set_quirks_mode (line 95) | fn set_quirks_mode(&self, mode: QuirksMode) {
  method same_node (line 99) | fn same_node(&self, x: &Ref, y: &Ref) -> bool {
  method elem_name (line 103) | fn elem_name(&self, target: &Ref) -> Self::ElemName<'_> {
  method get_template_contents (line 109) | fn get_template_contents(&self, target: &Ref) -> Ref {
  method is_mathml_annotation_xml_integration_point (line 115) | fn is_mathml_annotation_xml_integration_point(&self, target: &Ref) -> bo...
  method pop (line 121) | fn pop(&self, node: &Ref) {
  method create_element (line 127) | fn create_element(&self, name: QualName, attrs: Vec<Attribute>, flags: E...
  method create_comment (line 142) | fn create_comment(&self, txt: StrTendril) -> Ref {
  method create_pi (line 149) | fn create_pi(&self, target: StrTendril, data: StrTendril) -> Ref {
  method append (line 157) | fn append(&self, parent: &Ref, child: NodeOrText<Ref>) {
  method append_before_sibling (line 193) | fn append_before_sibling(&self, sibling: &Ref, child: NodeOrText<Ref>) {
  method append_based_on_parent_node (line 220) | fn append_based_on_parent_node(
  method append_doctype_to_document (line 252) | fn append_doctype_to_document(
  method add_attrs_if_missing (line 266) | fn add_attrs_if_missing(&self, target: &Ref, attrs: Vec<Attribute>) {
  method remove_from_parent (line 278) | fn remove_from_parent(&self, target: &Ref) {
  method reparent_children (line 284) | fn reparent_children(&self, node: &Ref, new_parent: &Ref) {

FILE: src/html5ever/types.rs
  type CreateElementCallback (line 23) | pub type CreateElementCallback = unsafe extern "C" fn(
  type CreateCommentCallback (line 30) | pub type CreateCommentCallback = unsafe extern "C" fn(
  type AppendDoctypeToDocumentCallback (line 35) | pub type AppendDoctypeToDocumentCallback = unsafe extern "C" fn(
  type CreateProcessingInstruction (line 42) | pub type CreateProcessingInstruction = unsafe extern "C" fn(
  type GetDataCallback (line 48) | pub type GetDataCallback = unsafe extern "C" fn(ctx: Ref) -> *mut c_void;
  type AppendCallback (line 50) | pub type AppendCallback = unsafe extern "C" fn(
  type ParseErrorCallback (line 56) | pub type ParseErrorCallback = unsafe extern "C" fn(ctx: Ref, str: String...
  type PopCallback (line 58) | pub type PopCallback = unsafe extern "C" fn(ctx: Ref, node: Ref) -> ();
  type AddAttrsIfMissingCallback (line 60) | pub type AddAttrsIfMissingCallback = unsafe extern "C" fn(
  type GetTemplateContentsCallback (line 66) | pub type GetTemplateContentsCallback = unsafe extern "C" fn(ctx: Ref, ta...
  type RemoveFromParentCallback (line 68) | pub type RemoveFromParentCallback = unsafe extern "C" fn(ctx: Ref, targe...
  type ReparentChildrenCallback (line 70) | pub type ReparentChildrenCallback = unsafe extern "C" fn(ctx: Ref, node:...
  type AppendBeforeSiblingCallback (line 72) | pub type AppendBeforeSiblingCallback = unsafe extern "C" fn(
  type AppendBasedOnParentNodeCallback (line 78) | pub type AppendBasedOnParentNodeCallback = unsafe extern "C" fn(
  type Ref (line 85) | pub type Ref = *const c_void;
  type CNullable (line 88) | pub struct CNullable<T> {
  function none (line 93) | pub fn none() -> CNullable<T> {
  function some (line 97) | pub fn some(v: T) -> CNullable<T> {
  type Slice (line 103) | pub struct Slice<T> {
  method default (line 108) | fn default() -> Self {
  type StringSlice (line 113) | pub type StringSlice = Slice<c_uchar>;
  type CQualName (line 116) | pub struct CQualName {
    method create (line 122) | pub fn create(q: &QualName) -> Self {
  method default (line 138) | fn default() -> Self {
  type CAttribute (line 148) | pub struct CAttribute {
  method default (line 153) | fn default() -> Self {
  type CAttributeIterator (line 158) | pub struct CAttributeIterator {
  type CNodeOrText (line 164) | pub struct CNodeOrText {
Condensed preview — 697 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (5,060K chars).
[
  {
    "path": ".github/actions/install/action.yml",
    "chars": 2013,
    "preview": "name: \"Browsercore install\"\ndescription: \"Install deps for the project browsercore\"\n\ninputs:\n  arch:\n    description: 'C"
  },
  {
    "path": ".github/workflows/cla.yml",
    "chars": 1108,
    "preview": "name: \"CLA Assistant\"\non:\n  issue_comment:\n    types: [created]\n  pull_request_target:\n    types: [opened,closed,synchro"
  },
  {
    "path": ".github/workflows/e2e-integration-test.yml",
    "chars": 1559,
    "preview": "name: e2e-integration-test\n\nenv:\n  LIGHTPANDA_DISABLE_TELEMETRY: true\n\non:\n  schedule:\n    - cron: \"4 4 * * *\"\n  # Allow"
  },
  {
    "path": ".github/workflows/e2e-test.yml",
    "chars": 11228,
    "preview": "name: e2e-test\n\nenv:\n  AWS_ACCESS_KEY_ID: ${{ vars.LPD_PERF_AWS_ACCESS_KEY_ID }}\n  AWS_SECRET_ACCESS_KEY: ${{ secrets.LP"
  },
  {
    "path": ".github/workflows/nightly.yml",
    "chars": 5979,
    "preview": "name: nightly build\n\nenv:\n  AWS_ACCESS_KEY_ID: ${{ vars.NIGHTLY_BUILD_AWS_ACCESS_ID }}\n  AWS_SECRET_ACCESS_KEY: ${{ secr"
  },
  {
    "path": ".github/workflows/wpt.yml",
    "chars": 3828,
    "preview": "name: wpt\n\nenv:\n  AWS_ACCESS_KEY_ID: ${{ vars.LPD_PERF_AWS_ACCESS_KEY_ID }}\n  AWS_SECRET_ACCESS_KEY: ${{ secrets.LPD_PER"
  },
  {
    "path": ".github/workflows/zig-test.yml",
    "chars": 3837,
    "preview": "name: zig-test\n\nenv:\n  AWS_ACCESS_KEY_ID: ${{ vars.LPD_PERF_AWS_ACCESS_KEY_ID }}\n  AWS_SECRET_ACCESS_KEY: ${{ secrets.LP"
  },
  {
    "path": ".gitignore",
    "chars": 87,
    "preview": "/.zig-cache/\n/.lp-cache/\nzig-out\nlightpanda.id\n/src/html5ever/target/\nsrc/snapshot.bin\n"
  },
  {
    "path": "CLA.md",
    "chars": 6047,
    "preview": "# Lightpanda (Selecy SAS) Grant and Contributor License Agreement (“Agreement”)\n\nThis agreement is based on the Apache S"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 408,
    "preview": "# Contributing\n\nLightpanda accepts pull requests through GitHub.\n\nYou have to sign our [CLA](CLA.md) during your first p"
  },
  {
    "path": "Dockerfile",
    "chars": 2770,
    "preview": "FROM debian:stable-slim\n\nARG MINISIG=0.12\nARG ZIG_MINISIG=RWSGOq2NVecA2UPNdBUZykf1CCb147pkmdtYxgb3Ti+JO/wCYvhbAb/U\nARG V"
  },
  {
    "path": "LICENSE",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "LICENSING.md",
    "chars": 309,
    "preview": "# Licensing\n\nLicense names used in this document are as per [SPDX License\nList](https://spdx.org/licenses/).\n\nThe defaul"
  },
  {
    "path": "Makefile",
    "chars": 2848,
    "preview": "# Variables\n# ---------\n\nZIG := zig\nBC := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))\n# option test filter make test "
  },
  {
    "path": "README.md",
    "chars": 12326,
    "preview": "<p align=\"center\">\n  <a href=\"https://lightpanda.io\"><img src=\"https://cdn.lightpanda.io/assets/images/logo/lpd-logo.png"
  },
  {
    "path": "build.zig",
    "chars": 28891,
    "preview": "// Copyright (C) 2023-2024  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "build.zig.zon",
    "chars": 1568,
    "preview": ".{\n    .name = .browser,\n    .version = \"0.0.0\",\n    .fingerprint = 0xda130f3af836cea0, // Changing this has security an"
  },
  {
    "path": "flake.nix",
    "chars": 1960,
    "preview": "{\n  description = \"headless browser designed for AI and automation\";\n\n  inputs = {\n    nixpkgs.url = \"github:nixos/nixpk"
  },
  {
    "path": "src/App.zig",
    "chars": 3500,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/ArenaPool.zig",
    "chars": 6298,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/Config.zig",
    "chars": 30390,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/Notification.zig",
    "chars": 14164,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/SemanticTree.zig",
    "chars": 18258,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/Server.zig",
    "chars": 29337,
    "preview": "// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pie"
  },
  {
    "path": "src/Sighandler.zig",
    "chars": 3575,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/TestHTTPServer.zig",
    "chars": 4954,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/Browser.zig",
    "chars": 3266,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/EventManager.zig",
    "chars": 32449,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/Factory.zig",
    "chars": 15503,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/HttpClient.zig",
    "chars": 55579,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/Mime.zig",
    "chars": 26074,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/Page.zig",
    "chars": 138566,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/ScriptManager.zig",
    "chars": 36606,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/Session.zig",
    "chars": 24363,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/URL.zig",
    "chars": 49259,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/actions.zig",
    "chars": 4121,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/color.zig",
    "chars": 14603,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/css/Parser.zig",
    "chars": 8394,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/css/Tokenizer.zig",
    "chars": 23865,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/dump.zig",
    "chars": 13348,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/interactive.zig",
    "chars": 19697,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Array.zig",
    "chars": 2004,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/BigInt.zig",
    "chars": 1493,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Caller.zig",
    "chars": 30601,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Context.zig",
    "chars": 40839,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Env.zig",
    "chars": 20961,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Function.zig",
    "chars": 8858,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/HandleScope.zig",
    "chars": 1520,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Inspector.zig",
    "chars": 15726,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Integer.zig",
    "chars": 1317,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Isolate.zig",
    "chars": 3475,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Local.zig",
    "chars": 57088,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Module.zig",
    "chars": 3988,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Number.zig",
    "chars": 1094,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Object.zig",
    "chars": 6518,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Origin.zig",
    "chars": 8666,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Platform.zig",
    "chars": 1441,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Private.zig",
    "chars": 1483,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Promise.zig",
    "chars": 2914,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/PromiseRejection.zig",
    "chars": 1371,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/PromiseResolver.zig",
    "chars": 3987,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Scheduler.zig",
    "chars": 4654,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Snapshot.zig",
    "chars": 26811,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/String.zig",
    "chars": 4131,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/TaggedOpaque.zig",
    "chars": 5084,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/TryCatch.zig",
    "chars": 4972,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/Value.zig",
    "chars": 10949,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/bridge.zig",
    "chars": 34436,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/js/js.zig",
    "chars": 15612,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/markdown.zig",
    "chars": 22493,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/parser/Parser.zig",
    "chars": 17278,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/parser/html5ever.zig",
    "chars": 9647,
    "preview": "// Copyright (C) 2023-2025  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/reflect.zig",
    "chars": 1077,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/structured_data.zig",
    "chars": 18108,
    "preview": "// Copyright (C) 2023-2026  Lightpanda (Selecy SAS)\n//\n// Francis Bouvier <francis@lightpanda.io>\n// Pierre Tachoire <pi"
  },
  {
    "path": "src/browser/tests/animation/animation.html",
    "chars": 1951,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=animation>\n  let a1 = document.createElement('div').an"
  },
  {
    "path": "src/browser/tests/blob.html",
    "chars": 6745,
    "preview": "<!DOCTYPE html>\n<meta charset=\"UTF-8\">\n<script src=\"./testing.js\"></script>\n\n<script id=basic>\n  {\n    const parts = [\"\\"
  },
  {
    "path": "src/browser/tests/canvas/canvas_rendering_context_2d.html",
    "chars": 4526,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=CanvasRenderingContext2D>\n{\n  const element = document"
  },
  {
    "path": "src/browser/tests/canvas/offscreen_canvas.html",
    "chars": 2697,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=OffscreenCanvas>\n{\n  const canvas = new OffscreenCanva"
  },
  {
    "path": "src/browser/tests/canvas/webgl_rendering_context.html",
    "chars": 2884,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=WebGLRenderingContext#getSupportedExtensions>\n{\n  cons"
  },
  {
    "path": "src/browser/tests/cdata/cdata_section.html",
    "chars": 5279,
    "preview": "cdataClassName<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\"></div>\n\n<script id=\"createInHTM"
  },
  {
    "path": "src/browser/tests/cdata/character_data.html",
    "chars": 19966,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\"></div>\n\n<script id=\"lengthProperty\">\n{\n  // l"
  },
  {
    "path": "src/browser/tests/cdata/comment.html",
    "chars": 259,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=comment>\n  testing.expectEqual('', new Comment().data)"
  },
  {
    "path": "src/browser/tests/cdata/data.html",
    "chars": 250,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=a><!-- spice --></div>\n<div id=b>flow</div>\n\n<script id=d"
  },
  {
    "path": "src/browser/tests/cdata/text.html",
    "chars": 570,
    "preview": "<!DOCTYPE html>\n<a id=\"link\" href=\"foo\" class=\"ok\">OK</a>\n\n<script src=\"../testing.js\"></script>\n<script id=text>\n  let "
  },
  {
    "path": "src/browser/tests/cdp/dom1.html",
    "chars": 18,
    "preview": "<p>1</p> <p>2</p>\n"
  },
  {
    "path": "src/browser/tests/cdp/dom2.html",
    "chars": 20,
    "preview": "<div><p>2</p></div>\n"
  },
  {
    "path": "src/browser/tests/cdp/dom3.html",
    "chars": 720,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Test Page</title>\n</head>\n<body>\n    <h1>Test Page</h1>\n    <nav>\n        <a hr"
  },
  {
    "path": "src/browser/tests/cdp/registry1.html",
    "chars": 48,
    "preview": "<a id=a1>link1</a><div id=d2><p>other</p></div>\n"
  },
  {
    "path": "src/browser/tests/cdp/registry2.html",
    "chars": 27,
    "preview": "<a id=a1></a><a id=a2></a>\n"
  },
  {
    "path": "src/browser/tests/cdp/registry3.html",
    "chars": 44,
    "preview": "<a id=a1></a><div id=d2><a id=a2></a></div>\n"
  },
  {
    "path": "src/browser/tests/collections/radio_node_list.html",
    "chars": 5256,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<!-- Test fixtures for RadioNodeList -->\n<form id=\"test_form\">\n  "
  },
  {
    "path": "src/browser/tests/console/console.html",
    "chars": 545,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=\"time\">\n    // should not crash\n    console.time();\n  "
  },
  {
    "path": "src/browser/tests/crypto.html",
    "chars": 3882,
    "preview": "<!DOCTYPE html>\n<script src=\"testing.js\"></script>\n\n<script id=getRandomValues>\n  function isRandom(ta) {\n    let uniq ="
  },
  {
    "path": "src/browser/tests/css/font_face.html",
    "chars": 1523,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=\"constructor_basic\">\n{\n    const face = new FontFace(\""
  },
  {
    "path": "src/browser/tests/css/font_face_set.html",
    "chars": 1830,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=\"document_fonts_exists\">\n{\n    testing.expectTrue(docu"
  },
  {
    "path": "src/browser/tests/css/media_query_list.html",
    "chars": 1026,
    "preview": "<!DOCTYPE html>\n<head>\n  <script src=\"../testing.js\"></script>\n</head>\n\n<body>\n</body>\n\n<script id=matchMedia_basic>\n{\n "
  },
  {
    "path": "src/browser/tests/css/stylesheet.html",
    "chars": 13880,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<script id=\"document_styleSheets\">\n{\n    const sheets = document."
  },
  {
    "path": "src/browser/tests/css.html",
    "chars": 2813,
    "preview": "<!DOCTYPE html>\n<script src=\"testing.js\"></script>\n\n<script id=\"exists\">\n  testing.expectEqual('object', typeof CSS);\n  "
  },
  {
    "path": "src/browser/tests/custom_elements/attribute_changed.html",
    "chars": 5179,
    "preview": "<!DOCTYPE html>\n<body>\n<script src=\"../testing.js\"></script>\n<script id=\"attribute_changed\">\n{\n    let callbackCalls = ["
  },
  {
    "path": "src/browser/tests/custom_elements/built_in.html",
    "chars": 3586,
    "preview": "<!DOCTYPE html>\n<body>\n<script src=\"../testing.js\"></script>\n<script id=\"built_in\">\n{\n    class FancyButton extends HTML"
  },
  {
    "path": "src/browser/tests/custom_elements/connected.html",
    "chars": 2237,
    "preview": "<!DOCTYPE html>\n<body>\n<script src=\"../testing.js\"></script>\n<script id=\"connected\">\n{\n    let connectedCount = 0;\n\n    "
  },
  {
    "path": "src/browser/tests/custom_elements/connected_from_parser.html",
    "chars": 3420,
    "preview": "<!DOCTYPE html>\n<head>\n<script src=\"../testing.js\"></script>\n<script>\n{\n    // Define the custom element BEFORE the HTML"
  },
  {
    "path": "src/browser/tests/custom_elements/constructor.html",
    "chars": 3880,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<script id=\"constructor\">\n{\n    let constructorCalled = false;\n   "
  },
  {
    "path": "src/browser/tests/custom_elements/disconnected.html",
    "chars": 3788,
    "preview": "<!DOCTYPE html>\n<body>\n<script src=\"../testing.js\"></script>\n<script id=\"disconnected\">\n{\n    let disconnectedCount = 0;"
  },
  {
    "path": "src/browser/tests/custom_elements/registry.html",
    "chars": 4598,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<script id=\"registry\">\n{\n    testing.expectEqual(true, window.cust"
  },
  {
    "path": "src/browser/tests/custom_elements/throw_on_dynamic_markup_insertion.html",
    "chars": 2149,
    "preview": "<!DOCTYPE html>\n<head>\n<script src=\"../testing.js\"></script>\n<script>\n// Test that document.open/write/close throw Inval"
  },
  {
    "path": "src/browser/tests/custom_elements/upgrade.html",
    "chars": 11278,
    "preview": "<!DOCTYPE html>\n<body>\n<my-early id=\"early\"></my-early>\n<script src=\"../testing.js\"></script>\n<script id=\"upgrade\">\n{\n  "
  },
  {
    "path": "src/browser/tests/document/adopt_import.html",
    "chars": 6670,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<div id=\"test-container\">\n  <p id=\"test-p\" class=\"test-class\" data"
  },
  {
    "path": "src/browser/tests/document/all_collection.html",
    "chars": 2783,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n  <title>Test Page</title>\n</head>\n<body>\n  <div id=\"first\">First</div>\n  <span name=\"seco"
  },
  {
    "path": "src/browser/tests/document/children.html",
    "chars": 647,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<head>\n  <title>Test</title>\n</head>\n<body>\n  <div id=\"test\">Cont"
  },
  {
    "path": "src/browser/tests/document/collections.html",
    "chars": 907,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<form id=\"form1\"></form>\n<img id=\"img1\" src=\"about:blank\">\n<scrip"
  },
  {
    "path": "src/browser/tests/document/create_element.html",
    "chars": 590,
    "preview": "<!DOCTYPE html>\n<body></body>\n<script src=\"../testing.js\"></script>\n<script id=createElement>\n  testing.expectEqual(1, d"
  },
  {
    "path": "src/browser/tests/document/create_element_ns.html",
    "chars": 2530,
    "preview": "<!DOCTYPE html>\n<body></body>\n<script src=\"../testing.js\"></script>\n<script id=createElementNS>\n  const htmlDiv1 = docum"
  },
  {
    "path": "src/browser/tests/document/document-title.html",
    "chars": 937,
    "preview": "<!DOCTYPE html>\n<head id=\"the_head\">\n  <script src=\"../testing.js\"></script>\n</head>\n\n<body id=the_body>\n</body>\n\n<scrip"
  },
  {
    "path": "src/browser/tests/document/document.html",
    "chars": 13406,
    "preview": "<!DOCTYPE html>\n<head id=\"the_head\">\n  <meta charset=\"UTF-8\">\n  <title>Test Document Title</title>\n  <script src=\"../tes"
  },
  {
    "path": "src/browser/tests/document/element_from_point.html",
    "chars": 7393,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<body>\n  <div id=\"div1\" style=\"width: 100px; height: 50px;\">Div 1"
  },
  {
    "path": "src/browser/tests/document/focus.html",
    "chars": 8315,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<body>\n  <input id=\"input1\" type=\"text\">\n  <input id=\"input2\" type"
  },
  {
    "path": "src/browser/tests/document/get_element_by_id.html",
    "chars": 1419,
    "preview": "<!DOCTYPE html>\n<body>\n  <script src=\"../testing.js\"></script>\n  <div id=\"div-1\">x: <p id=p1>d1</p></div>\n</body>\n\n<scri"
  },
  {
    "path": "src/browser/tests/document/get_elements_by_class_name-multiple.html",
    "chars": 1542,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"div1\" class=\"foo bar\">Div 1</div>\n<div id=\"div2\" class=\""
  },
  {
    "path": "src/browser/tests/document/get_elements_by_class_name.html",
    "chars": 3226,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div class=\"foo\">foo1</div>\n<span class=\"foo\">foo2</span>\n<p clas"
  },
  {
    "path": "src/browser/tests/document/get_elements_by_name.html",
    "chars": 1931,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<input name=\"username\" value=\"john\">\n<input name=\"password\" type="
  },
  {
    "path": "src/browser/tests/document/get_elements_by_tag_name-wildcard.html",
    "chars": 1059,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<head>\n  <title>Test</title>\n</head>\n<body>\n  <div id=\"div1\">\n   "
  },
  {
    "path": "src/browser/tests/document/get_elements_by_tag_name.html",
    "chars": 5558,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<div>0</div>\n<div>1</div>\n<div>2</div>\n\n<p id=p1></p>\n<p id=p2></p"
  },
  {
    "path": "src/browser/tests/document/insert_adjacent_element.html",
    "chars": 1934,
    "preview": "<!DOCTYPE html>\n<head id=\"the_head\">\n  <title>Test Document Title</title>\n  <script src=\"../testing.js\"></script>\n</head"
  },
  {
    "path": "src/browser/tests/document/insert_adjacent_html.html",
    "chars": 4573,
    "preview": "<!DOCTYPE html>\n<head id=\"the_head\">\n  <title>Test Document Title</title>\n  <script src=\"../testing.js\"></script>\n</head"
  },
  {
    "path": "src/browser/tests/document/insert_adjacent_text.html",
    "chars": 1450,
    "preview": "<!DOCTYPE html>\n<head id=\"the_head\">\n  <title>Test Document Title</title>\n  <script src=\"../testing.js\"></script>\n</head"
  },
  {
    "path": "src/browser/tests/document/query_selector.html",
    "chars": 13406,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div class=\"test-class\">div1</div>\n<span class=\"test-class\">span1"
  },
  {
    "path": "src/browser/tests/document/query_selector_all.html",
    "chars": 16405,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div class=\"test-class\">div1</div>\n<span class=\"test-class\">span1"
  },
  {
    "path": "src/browser/tests/document/query_selector_attributes.html",
    "chars": 5513,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\">\n  <div data-test=\"value1\">First</div>\n  <div"
  },
  {
    "path": "src/browser/tests/document/query_selector_edge_cases.html",
    "chars": 6904,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"root\">\n  <div id=\"a\" class=\"x\">\n    <p id=\"b\" class=\"y\">"
  },
  {
    "path": "src/browser/tests/document/query_selector_not.html",
    "chars": 3626,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"root\">\n  <div id=\"container\" class=\"parent\">\n    <p id=\""
  },
  {
    "path": "src/browser/tests/document/replace_children.html",
    "chars": 9588,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<head>\n  <title>document.replaceChildren Tests</title>\n</head>\n<b"
  },
  {
    "path": "src/browser/tests/document/write.html",
    "chars": 5179,
    "preview": "<!DOCTYPE html>\n<head>\n  <title>document.write Tests</title>\n  <script src=\"../testing.js\"></script>\n</head>\n\n<body>\n\n<!"
  },
  {
    "path": "src/browser/tests/document_fragment/document_fragment.html",
    "chars": 6032,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<body></body>\n\n<script id=document_fragment>\n  {\n    const df = n"
  },
  {
    "path": "src/browser/tests/document_fragment/insertion.html",
    "chars": 7769,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\"></div>\n\n<script id=\"appendChildBasic\">\n{\n  //"
  },
  {
    "path": "src/browser/tests/document_head_body.html",
    "chars": 300,
    "preview": "<head id=\"the_head\">\n  <script src=\"testing.js\"></script>\n</head>\n<body id=\"the_body\">\n  <script id=\"test-document-head-"
  },
  {
    "path": "src/browser/tests/domexception.html",
    "chars": 3862,
    "preview": "<!DOCTYPE html>\n<head>\n  <title>DOMException Test</title>\n  <script src=\"testing.js\"></script>\n</head>\n\n<body>\n</body>\n\n"
  },
  {
    "path": "src/browser/tests/domimplementation.html",
    "chars": 7686,
    "preview": "<!DOCTYPE html>\n<head>\n  <title>DOMImplementation Test</title>\n  <script src=\"testing.js\"></script>\n</head>\n\n<body>\n</bo"
  },
  {
    "path": "src/browser/tests/domparser.html",
    "chars": 14266,
    "preview": "<!DOCTYPE html>\n<script src=\"testing.js\"></script>\n<body></body>\n\n<script id=basic>\n{\n  {\n    const parser = new DOMPars"
  },
  {
    "path": "src/browser/tests/element/append.html",
    "chars": 1042,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<div id=\"test-container\"></div>\n<script id=\"append-prepend-tests\">"
  },
  {
    "path": "src/browser/tests/element/attributes.html",
    "chars": 9688,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=attr1 ClasS=\"sHow\"></div>\n\n<script id=attributes>\n  const"
  },
  {
    "path": "src/browser/tests/element/bounding_rect.html",
    "chars": 1388,
    "preview": "<!DOCTYPE html>\n<head>\n  <title>Lightpanda Browser demo</title>\n  <meta charset=\"UTF-8\">\n</head>\n<body>\n  <h1>Lightpanda"
  },
  {
    "path": "src/browser/tests/element/class_list.html",
    "chars": 16504,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=test1></div>\n<div id=test2 class=\"foo bar\"></div>\n\n<scrip"
  },
  {
    "path": "src/browser/tests/element/closest.html",
    "chars": 2709,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<body></body>\n\n<div id=\"outer\" class=\"container\">\n  <div id=\"middl"
  },
  {
    "path": "src/browser/tests/element/css_style_properties.html",
    "chars": 4496,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"test-div\"></div>\n\n<script id=\"camelCaseAccess\">\n{\n  cons"
  },
  {
    "path": "src/browser/tests/element/dataset.html",
    "chars": 3997,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"test\" data-foo=\"bar\" data-hello-world=\"test\"></div>\n<div"
  },
  {
    "path": "src/browser/tests/element/duplicate_ids.html",
    "chars": 458,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"test\">first</div>\n<div id=\"test\">second</div>\n\n<script i"
  },
  {
    "path": "src/browser/tests/element/element.html",
    "chars": 5547,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\">\n    <!-- comment -->\n    <p id=\"p1\">Paragrap"
  },
  {
    "path": "src/browser/tests/element/get_elements_by_class_name.html",
    "chars": 5771,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\" class=\"container-class\">\n  <div class=\"foo\" i"
  },
  {
    "path": "src/browser/tests/element/get_elements_by_tag_name.html",
    "chars": 5515,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\">\n  <div id=\"div1\">div1</div>\n  <p id=\"p1\">p1<"
  },
  {
    "path": "src/browser/tests/element/get_elements_by_tag_name_ns.html",
    "chars": 3920,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\" xmlns=\"http://www.w3.org/1999/xhtml\">\n  <div "
  },
  {
    "path": "src/browser/tests/element/html/anchor.html",
    "chars": 7058,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- Test anchors with various href values -->\n<a id=a0></a>\n<"
  },
  {
    "path": "src/browser/tests/element/html/button.html",
    "chars": 3759,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- Button elements -->\n<button id=\"button1\">Click me</button"
  },
  {
    "path": "src/browser/tests/element/html/details.html",
    "chars": 1466,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- Details elements -->\n<details id=\"details1\">\n  <summary>S"
  },
  {
    "path": "src/browser/tests/element/html/dialog.html",
    "chars": 2231,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- Dialog elements -->\n<dialog id=\"dialog1\">Dialog content</"
  },
  {
    "path": "src/browser/tests/element/html/event_listeners.html",
    "chars": 18674,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- Test inline event listeners set via HTML attributes -->\n<"
  },
  {
    "path": "src/browser/tests/element/html/fieldset.html",
    "chars": 784,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<fieldset id=\"fs1\" disabled name=\"group1\">\n  <input type=\"text"
  },
  {
    "path": "src/browser/tests/element/html/form.html",
    "chars": 12999,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- Test fixtures for form.name -->\n<form id=\"form_with_name\""
  },
  {
    "path": "src/browser/tests/element/html/htmlelement-props.html",
    "chars": 1461,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<div id=\"d1\" hidden>Hidden div</div>\n<div id=\"d2\">Visible div<"
  },
  {
    "path": "src/browser/tests/element/html/image.html",
    "chars": 5215,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<script id=\"Image\">\n{\n    let i1 = new Image()\n    testing.exp"
  },
  {
    "path": "src/browser/tests/element/html/input-attrs.html",
    "chars": 2005,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<input id=\"i1\" placeholder=\"Enter name\" min=\"0\" max=\"100\" step"
  },
  {
    "path": "src/browser/tests/element/html/input.html",
    "chars": 16455,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<input id=\"text1\" type=\"text\" value=\"initial\">\n<input id=\"text"
  },
  {
    "path": "src/browser/tests/element/html/input_click.html",
    "chars": 7985,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- Checkbox click tests -->\n<input id=\"checkbox1\" type=\"chec"
  },
  {
    "path": "src/browser/tests/element/html/input_radio.html",
    "chars": 5035,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<input id=\"radio1\" type=\"radio\" name=\"group1\" checked>\n<input "
  },
  {
    "path": "src/browser/tests/element/html/label.html",
    "chars": 2482,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<label id=\"l1\" for=\"input1\">Name</label>\n<input id=\"input1\">\n\n"
  },
  {
    "path": "src/browser/tests/element/html/li.html",
    "chars": 465,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<ol>\n  <li id=\"li1\" value=\"5\">Item</li>\n  <li id=\"li2\">Item</l"
  },
  {
    "path": "src/browser/tests/element/html/link.html",
    "chars": 3168,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<script id=link>\n  let l2 = document.createElement('link');\n  "
  },
  {
    "path": "src/browser/tests/element/html/media.html",
    "chars": 8881,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<audio id=\"audio1\" src=\"test.mp3\"></audio>\n<video id=\"video1\" "
  },
  {
    "path": "src/browser/tests/element/html/ol.html",
    "chars": 1083,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<ol id=\"ol1\" start=\"5\" reversed type=\"a\">\n  <li>Item</li>\n</ol"
  },
  {
    "path": "src/browser/tests/element/html/optgroup.html",
    "chars": 910,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<select>\n  <optgroup id=\"og1\" label=\"Group 1\" disabled>\n    <o"
  },
  {
    "path": "src/browser/tests/element/html/option.html",
    "chars": 3137,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<select id=\"select1\">\n  <option id=\"opt1\" value=\"val1\">Text 1<"
  },
  {
    "path": "src/browser/tests/element/html/picture.html",
    "chars": 1652,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- <script id=\"createElement\">\n{\n    const picture = documen"
  },
  {
    "path": "src/browser/tests/element/html/quote.html",
    "chars": 478,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<blockquote id=\"q1\" cite=\"https://example.com/source\">Quote</b"
  },
  {
    "path": "src/browser/tests/element/html/script/async_text.html",
    "chars": 1989,
    "preview": "<!DOCTYPE html>\n<script src=\"../../../testing.js\"></script>\n\n<script id=force_async>\n{\n   // Dynamically created scripts"
  },
  {
    "path": "src/browser/tests/element/html/script/dynamic.html",
    "chars": 1149,
    "preview": "<!DOCTYPE html>\n<head></head>\n<script src=\"../../../testing.js\"></script>\n\n<script id=append_before_src1>\n  loaded1 = 0;"
  },
  {
    "path": "src/browser/tests/element/html/script/dynamic1.js",
    "chars": 14,
    "preview": "loaded1 += 1;\n"
  },
  {
    "path": "src/browser/tests/element/html/script/dynamic2.js",
    "chars": 14,
    "preview": "loaded2 += 1;\n"
  },
  {
    "path": "src/browser/tests/element/html/script/dynamic_inline.html",
    "chars": 1624,
    "preview": "<!DOCTYPE html>\n<head></head>\n<script src=\"../../../testing.js\"></script>\n\n<script id=textContent_inline>\n  window.inlin"
  },
  {
    "path": "src/browser/tests/element/html/script/empty.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "src/browser/tests/element/html/script/order.html",
    "chars": 805,
    "preview": "<!DOCTYPE html>\n<script src=\"../../../testing.js\"></script>\n\n<script defer id=\"remote_defer\" src=\"order_defer.js\"></scri"
  },
  {
    "path": "src/browser/tests/element/html/script/order.js",
    "chars": 45,
    "preview": "list += 'a';\ntesting.expectEqual('a', list);\n"
  },
  {
    "path": "src/browser/tests/element/html/script/order_async.js",
    "chars": 50,
    "preview": "list += 'f';\ntesting.expectEqual('abcdef', list);\n"
  },
  {
    "path": "src/browser/tests/element/html/script/order_defer.js",
    "chars": 49,
    "preview": "list += 'e';\ntesting.expectEqual('abcde', list);\n"
  },
  {
    "path": "src/browser/tests/element/html/script/script.html",
    "chars": 742,
    "preview": "<!DOCTYPE html>\n<script src=\"../../../testing.js\"></script>\n\n<script id=\"script\">\n{\n   let dom_load = false;\n   let attr"
  },
  {
    "path": "src/browser/tests/element/html/select.html",
    "chars": 11608,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<select id=\"select1\">\n  <option value=\"val1\">Option 1</option>"
  },
  {
    "path": "src/browser/tests/element/html/slot.html",
    "chars": 14749,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<script id=\"Slot#basic_creation\">\n{\n    const slot = document."
  },
  {
    "path": "src/browser/tests/element/html/style.html",
    "chars": 4048,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<script id=\"sheet\">\n  {\n    // Disconnected style element shou"
  },
  {
    "path": "src/browser/tests/element/html/tablecell.html",
    "chars": 1162,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<table>\n  <tr>\n    <td id=\"td1\" colspan=\"3\" rowspan=\"2\">Cell</"
  },
  {
    "path": "src/browser/tests/element/html/template.html",
    "chars": 6492,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n<body>\n<template id=\"basic\">\n  <div class=\"container\">\n    <h1>"
  },
  {
    "path": "src/browser/tests/element/html/textarea.html",
    "chars": 9476,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<!-- TextArea elements -->\n<textarea id=\"textarea1\">initial te"
  },
  {
    "path": "src/browser/tests/element/html/time.html",
    "chars": 435,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<time id=\"t1\" datetime=\"2024-01-15\">January 15</time>\n\n<script"
  },
  {
    "path": "src/browser/tests/element/html/track.html",
    "chars": 1770,
    "preview": "<!DOCTYPE html>\n<script src=\"../../testing.js\"></script>\n\n<video id=\"video1\">\n  <track id=\"track1\" kind=\"subtitles\">\n  <"
  },
  {
    "path": "src/browser/tests/element/inner.html",
    "chars": 6564,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<div id=d1>hello <em>world</em></div>\n<div id=d2>\n  <style>h1 { fo"
  },
  {
    "path": "src/browser/tests/element/inner.js",
    "chars": 21,
    "preview": "inner_loaded = true;\n"
  },
  {
    "path": "src/browser/tests/element/matches.html",
    "chars": 2352,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"test-container\" class=\"container main\">\n  <p class=\"text"
  },
  {
    "path": "src/browser/tests/element/outer.html",
    "chars": 1040,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n<div id=d1>hello <em>world</em></div>\n\n<script id=outerHTML>\n  con"
  },
  {
    "path": "src/browser/tests/element/position.html",
    "chars": 3346,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"test1\">Test Element</div>\n<div id=\"test2\">Another Elemen"
  },
  {
    "path": "src/browser/tests/element/pseudo_classes.html",
    "chars": 2727,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=\"container\">\n    <p id=\"first\">First</p>\n    <input type="
  },
  {
    "path": "src/browser/tests/element/query_selector.html",
    "chars": 2103,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=p1>\n  <div id=c2>\n    <div id=c3></div>\n  </div>\n</div>\n<"
  },
  {
    "path": "src/browser/tests/element/query_selector_all.html",
    "chars": 6052,
    "preview": "<!DOCTYPE html>\n<script src=\"../testing.js\"></script>\n\n<div id=root>\n  <div class=\"item\">Item 1</div>\n  <span class=\"ite"
  }
]

// ... and 497 more files (download for full content)

About this extraction

This page contains the full source code of the lightpanda-io/browser GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 697 files (4.6 MB), approximately 1.2M tokens, and a symbol index with 101 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!