From de689a554d1b86b97dcc71140bfbee250eff1d4e Mon Sep 17 00:00:00 2001 From: windloom <257951420+windloom@users.noreply.github.com> Date: Mon, 6 Jul 2026 04:18:54 +0800 Subject: [PATCH] Assemble source-integrated VoHive --- .dockerignore | 21 + .github/workflows/binary-release.yml | 181 + .github/workflows/docker-build.yml | 74 + .github/workflows/docker-publish.yml | 88 + .github/workflows/web-ci.yml | 40 + .gitignore | 65 + DOCKERHUB.md | 90 + Dockerfile | 101 + Dockerfile.github | 101 + LICENSE | 137 + Makefile | 55 + README.md | 100 + THIRD_PARTY_NOTICES.md | 48 + cmd/mbimprobe/main.go | 306 + cmd/vohive/main.go | 277 + config/config.example.yaml | 18 + docker-compose.yml | 15 + go.mod | 108 + go.sum | 249 + go.work | 9 + internal/apduarbiter/arbiter.go | 940 +++ internal/apduarbiter/arbiter_test.go | 781 +++ internal/apduarbiter/simauth_ready.go | 115 + internal/api/auth_security_test.go | 64 + internal/api/card_policy.go | 106 + internal/api/card_policy_test.go | 274 + internal/api/device_e911.go | 54 + internal/api/device_e911_test.go | 28 + internal/api/device_mgmt.go | 2716 +++++++ internal/api/device_mgmt_add_imei_test.go | 60 + internal/api/device_mgmt_at_test.go | 144 + internal/api/device_mgmt_backend_mode_test.go | 32 + ...evice_mgmt_cardpolicy_writethrough_test.go | 88 + internal/api/device_mgmt_discovery_test.go | 247 + internal/api/device_mgmt_flightmode_test.go | 52 + internal/api/device_mgmt_ipversion_test.go | 36 + internal/api/device_mgmt_lifecycle_test.go | 89 + .../api/device_mgmt_overview_display_test.go | 52 + .../api/device_mgmt_overview_stream_test.go | 184 + internal/api/device_mgmt_overview_test.go | 40 + internal/api/device_mgmt_phone_test.go | 752 ++ internal/api/device_mgmt_qmi_proxy_test.go | 114 + internal/api/device_mgmt_restart.go | 73 + internal/api/device_mgmt_restart_test.go | 128 + internal/api/device_mgmt_test_helpers_test.go | 17 + internal/api/device_mgmt_ussd_test.go | 426 ++ internal/api/device_operator_selection.go | 200 + .../api/device_operator_selection_test.go | 110 + internal/api/device_policy_display.go | 68 + internal/api/device_policy_display_test.go | 53 + internal/api/device_traffic.go | 68 + internal/api/device_traffic_test.go | 54 + internal/api/docs_assets/swagger-ui/LICENSE | 202 + internal/api/docs_assets/swagger-ui/NOTICE | 2 + .../swagger-ui/swagger-ui-bundle.js | 2 + .../swagger-ui-bundle.js.LICENSE.txt | 106 + .../swagger-ui-standalone-preset.js | 2 + ...wagger-ui-standalone-preset.js.LICENSE.txt | 22 + .../api/docs_assets/swagger-ui/swagger-ui.css | 3 + internal/api/openapi.go | 455 ++ internal/api/openapi.vohive.yaml | 3176 +++++++++ internal/api/openapi_test.go | 22 + internal/api/path_params.go | 35 + internal/api/proxy.go | 377 + internal/api/proxy_test.go | 275 + internal/api/route_adapters.go | 86 + internal/api/server.go | 1815 +++++ internal/api/settings.go | 349 + internal/api/settings_bark.go | 92 + internal/api/settings_email.go | 87 + internal/api/settings_webhook.go | 105 + internal/api/sms_inbox_test.go | 49 + internal/api/system.go | 133 + internal/api/system_test.go | 150 + internal/api/traffic.go | 33 + internal/api/upstream_proxy.go | 277 + .../api/upstream_proxy_country_rules_test.go | 124 + internal/api/websheet.go | 133 + internal/api/websheet_test.go | 125 + internal/backend/at_backend.go | 283 + internal/backend/at_operator_selection.go | 139 + internal/backend/backend.go | 17 + internal/backend/check.go | 9 + internal/backend/discovery.go | 11 + internal/backend/factory.go | 76 + internal/backend/info.go | 60 + internal/backend/mbim_backend.go | 292 + internal/backend/mbim_backend_aka.go | 31 + internal/backend/mbim_backend_capability.go | 7 + internal/backend/mbim_backend_identity.go | 24 + internal/backend/mbim_backend_simauth.go | 47 + internal/backend/mbim_backend_simfiles.go | 127 + .../backend/mbim_backend_simfiles_test.go | 238 + internal/backend/mbim_backend_sms.go | 68 + internal/backend/mbim_backend_test.go | 723 ++ internal/backend/mbim_backend_ussd.go | 37 + internal/backend/mbim_backend_ussd_test.go | 77 + internal/backend/mbim_operator_selection.go | 87 + .../backend/mbim_operator_selection_test.go | 115 + internal/backend/mbim_source.go | 54 + internal/backend/operator_selection.go | 162 + internal/backend/operator_selection_test.go | 60 + internal/backend/opmode.go | 21 + internal/backend/qmi_backend.go | 1046 +++ internal/backend/qmi_backend_msisdn_test.go | 47 + internal/backend/qmi_backend_send_test.go | 1428 ++++ .../backend/qmi_backend_shortcode_test.go | 55 + internal/backend/qmi_backend_ussd.go | 594 ++ internal/backend/qmi_operator_selection.go | 169 + internal/backend/qmi_signal_test.go | 25 + internal/backend/registration.go | 8 + internal/backend/simauth.go | 25 + internal/backend/sms.go | 31 + internal/backend/smsc.go | 9 + internal/backend/types.go | 100 + internal/backend/ussd.go | 37 + internal/cardpolicy/policy.go | 16 + internal/cardpolicy/policy_test.go | 15 + internal/config/config.go | 290 + internal/config/config_test.go | 197 + internal/config/esim_transport_test.go | 33 + internal/config/imei.go | 27 + internal/config/imei_test.go | 45 + internal/config/ipversion_test.go | 33 + internal/config/manager.go | 69 + internal/config/mbim_transport_test.go | 18 + internal/config/persist.go | 133 + internal/config/persist_devices.go | 283 + internal/config/persist_devices_imei_test.go | 52 + .../config/persist_devices_slimming_test.go | 68 + internal/data/repo/db_repo.go | 90 + internal/data/repo/repo.go | 13 + internal/db/card_policy.go | 130 + .../db/card_policy_canonical_migration.go | 69 + internal/db/card_policy_canonical_test.go | 105 + internal/db/card_policy_resolver.go | 21 + internal/db/card_policy_test.go | 106 + internal/db/check_test.go | 22 + internal/db/db.go | 1125 +++ internal/db/db_ipv6_test.go | 38 + internal/db/iccid_rekey_migration.go | 112 + internal/db/iccid_rekey_migration_test.go | 96 + internal/db/pending_phone_e2e_test.go | 31 + internal/db/pending_phone_test.go | 119 + internal/db/phone_number_test.go | 262 + internal/db/phone_number_validation_test.go | 27 + internal/db/proxy_instance.go | 112 + internal/db/sms_delete_test.go | 103 + internal/db/sms_delivery.go | 334 + internal/db/sms_iccid_query_test.go | 184 + internal/db/sms_query.go | 128 + internal/db/sqlite_dialector.go | 21 + internal/db/traffic.go | 308 + internal/db/traffic_latest.go | 93 + internal/db/traffic_rollup.go | 171 + internal/db/traffic_test.go | 366 + internal/db/upstream_proxy.go | 149 + internal/db/upstream_proxy_test.go | 86 + internal/device/at_port_resolver.go | 82 + internal/device/at_port_resolver_test.go | 102 + internal/device/at_radio_snapshot.go | 191 + internal/device/at_radio_snapshot_test.go | 156 + internal/device/backend_init.go | 26 + internal/device/device_limit.go | 41 + internal/device/discovery_compat.go | 432 ++ internal/device/discovery_compat_test.go | 383 + internal/device/discovery_enrichment.go | 293 + internal/device/discovery_enrichment_test.go | 337 + internal/device/health_watchdog.go | 159 + internal/device/health_watchdog_test.go | 305 + internal/device/identity_resolver.go | 170 + internal/device/identity_resolver_test.go | 260 + internal/device/lifecycle.go | 146 + internal/device/lifecycle_test.go | 65 + internal/device/mbim_bootstrap_test.go | 101 + internal/device/mbim_discovery_test.go | 37 + internal/device/mbim_imei_probe.go | 116 + internal/device/mbim_imei_probe_test.go | 35 + internal/device/mbim_registration.go | 240 + internal/device/mbim_registration_test.go | 145 + internal/device/network_controller.go | 37 + internal/device/network_controller_test.go | 155 + internal/device/notifier.go | 15 + internal/device/notifier_nil_test.go | 59 + internal/device/operator_selection.go | 295 + internal/device/operator_selection_test.go | 325 + internal/device/phone_number_sync_test.go | 320 + internal/device/policy_projection.go | 150 + internal/device/policy_projection_test.go | 179 + internal/device/pool.go | 2310 ++++++ internal/device/pool_apdu_cleanup.go | 122 + internal/device/pool_apdu_cleanup_test.go | 56 + internal/device/pool_at_radio_warmup.go | 46 + internal/device/pool_attachment_persist.go | 49 + .../device/pool_attachment_persist_test.go | 143 + internal/device/pool_bootstrap.go | 726 ++ internal/device/pool_bootstrap_test.go | 72 + internal/device/pool_device_limit_test.go | 202 + internal/device/pool_esim_imei_test.go | 148 + internal/device/pool_esim_manager_test.go | 149 + internal/device/pool_esim_switch.go | 1105 +++ .../device/pool_esim_switch_restore_test.go | 1712 +++++ internal/device/pool_health_ip.go | 630 ++ internal/device/pool_health_ip_test.go | 112 + internal/device/pool_health_ip_v6_test.go | 15 + internal/device/pool_lifecycle_test.go | 57 + internal/device/pool_mbim_indications_test.go | 124 + internal/device/pool_mbim_recovery_test.go | 29 + internal/device/pool_migration_test.go | 94 + internal/device/pool_policy_sync_test.go | 59 + internal/device/pool_proxy_reconcile_test.go | 28 + internal/device/pool_qmi_mode_test.go | 878 +++ internal/device/pool_qmi_reconnect_test.go | 405 ++ internal/device/pool_qmi_sms_test.go | 302 + .../device/pool_qmi_startup_network_test.go | 48 + internal/device/pool_reboot_recovery.go | 616 ++ internal/device/pool_reboot_recovery_test.go | 543 ++ .../pool_rescan_characterization_test.go | 48 + internal/device/pool_rescan_collect_test.go | 116 + internal/device/pool_rescan_nonqmi_test.go | 91 + internal/device/pool_sms.go | 449 ++ internal/device/pool_sms_mbim.go | 79 + internal/device/pool_sms_mbim_test.go | 173 + internal/device/pool_smsc_test.go | 63 + internal/device/pool_state.go | 408 ++ internal/device/pool_uim_indication_test.go | 23 + internal/device/pool_vowifi_autostart.go | 61 + .../device/pool_vowifi_controller_test.go | 572 ++ .../device/pool_vowifi_country_proxy_test.go | 55 + internal/device/pool_vowifi_host.go | 13 + internal/device/pool_vowifi_identity_test.go | 154 + internal/device/pool_vowifi_lock_test.go | 438 ++ internal/device/pool_vowifi_policy_test.go | 20 + internal/device/pool_vowifi_reconcile.go | 240 + internal/device/pool_vowifi_reconcile_test.go | 365 + internal/device/pool_vowifi_runtime.go | 162 + internal/device/pool_vowifi_runtime_test.go | 94 + internal/device/pool_vowifi_voice_test.go | 68 + internal/device/pool_vowifi_wiring.go | 20 + internal/device/post_switch_convergence.go | 387 + .../device/post_switch_convergence_test.go | 578 ++ internal/device/qmi_core_start.go | 126 + internal/device/qmi_core_start_test.go | 106 + internal/device/qmi_modem_adapter.go | 125 + internal/device/qmi_recovery_attachment.go | 34 + .../device/qmi_recovery_attachment_test.go | 160 + internal/device/qmi_recovery_readiness.go | 116 + .../device/qmi_recovery_readiness_test.go | 94 + internal/device/qmi_registration.go | 466 ++ internal/device/qmi_registration_test.go | 665 ++ internal/device/qmi_static_discovery.go | 747 ++ internal/device/qmi_static_discovery_test.go | 438 ++ internal/device/qmi_transport_error.go | 82 + internal/device/qmi_transport_error_test.go | 27 + internal/device/switch_reinit.go | 157 + internal/device/switch_reinit_test.go | 148 + .../device/transport_recovery_controller.go | 143 + .../transport_recovery_controller_test.go | 168 + internal/device/udev.go | 171 + internal/device/udev_test.go | 21 + internal/device/vowifi_delivery_store.go | 85 + internal/device/vowifi_dispatcher.go | 69 + .../device/vowifi_eventhost_boundary_test.go | 27 + .../device/vowifi_external_boundary_test.go | 99 + internal/device/vowifi_host_boundary_test.go | 150 + internal/device/vowifi_modem_adapter.go | 91 + internal/device/vowifi_plmn_format.go | 19 + internal/device/vowifi_plmn_format_test.go | 23 + internal/device/vowifi_runtime_store_test.go | 50 + .../device/vowifi_sms_history_recorder.go | 124 + .../vowifi_sms_history_recorder_test.go | 295 + internal/device/vowifi_start_errors.go | 113 + internal/device/vowifi_start_orchestrator.go | 333 + internal/device/vowifi_start_profile.go | 144 + internal/device/vowifi_state_api.go | 139 + internal/device/vowifi_teardown.go | 132 + .../vowifi_voice_lifecycle_boundary_test.go | 37 + internal/device/worker_atport.go | 22 + internal/device/worker_atport_test.go | 42 + internal/e911/artifact_boundary_test.go | 17 + internal/e911/availability.go | 33 + internal/e911/availability_test.go | 29 + internal/e911/coordinator.go | 165 + internal/e911/coordinator_test.go | 95 + internal/e911/trace.go | 281 + internal/e911/trace_test.go | 135 + internal/esim/apdu_coordinator.go | 144 + internal/esim/apdu_coordinator_test.go | 65 + internal/esim/channel.go | 89 + internal/esim/download_error.go | 134 + internal/esim/errors.go | 83 + internal/esim/euicc_info.go | 102 + internal/esim/manager.go | 4115 +++++++++++ internal/esim/manager_test.go | 3113 +++++++++ internal/esim/mbim_apdu_transport.go | 102 + internal/esim/mbim_apdu_transport_test.go | 97 + internal/esim/pki/accredited.json | 503 ++ internal/esim/pki/ci.json | 120 + internal/esim/pki/pki.go | 112 + internal/esim/qmi_channel.go | 198 + internal/esim/qmi_channel_log_test.go | 15 + internal/esim/qmi_channel_test.go | 290 + internal/esim/qmi_uim_transport.go | 244 + internal/global/version.go | 9 + internal/mbim/dataconn.go | 410 ++ internal/mbim/dataconn_test.go | 446 ++ internal/mbim/healthprobe.go | 135 + internal/mbim/healthprobe_test.go | 137 + internal/mbim/manager.go | 1010 +++ internal/mbim/manager_arbiter_test.go | 16 + internal/mbim/manager_capability_test.go | 38 + internal/mbim/manager_ef_test.go | 393 ++ internal/mbim/manager_providers_test.go | 150 + internal/mbim/manager_registration_test.go | 51 + internal/mbim/manager_test.go | 196 + internal/mbim/manager_uicc_probe_test.go | 30 + internal/mbim/manager_ussd_test.go | 189 + internal/mbim/netcfg_adapter.go | 47 + internal/mbim/post_switch.go | 125 + internal/mbim/post_switch_test.go | 422 ++ internal/mbim/recovery.go | 129 + internal/mbim/recovery_test.go | 138 + internal/mbim/testsupport.go | 20 + internal/modem/at_parse.go | 694 ++ internal/modem/at_parse_test.go | 196 + internal/modem/commands.go | 706 ++ internal/modem/commands_apdu_test.go | 573 ++ internal/modem/imei_probe.go | 114 + internal/modem/manager.go | 2270 ++++++ internal/modem/manager_execute_at_test.go | 473 ++ internal/modem/manager_force_release_test.go | 53 + internal/modem/manager_pure_backend_test.go | 22 + internal/modem/manager_sms_storage_test.go | 51 + internal/modem/operator_name.go | 71 + internal/modem/operator_name_test.go | 50 + internal/modem/operator_selection.go | 56 + internal/modem/operator_selection_test.go | 35 + internal/modem/phone_number_parse_test.go | 46 + internal/modem/serial_at.go | 113 + internal/modem/sim_metadata.go | 329 + internal/modem/sim_metadata_test.go | 144 + internal/modem/spn.go | 147 + internal/modem/spn_test.go | 61 + internal/modem/urc_format.go | 238 + internal/netprobe/netprobe.go | 195 + internal/netprobe/netprobe_test.go | 41 + internal/notify/bark.go | 173 + internal/notify/channel.go | 29 + internal/notify/commands.go | 692 ++ internal/notify/email.go | 110 + internal/notify/feishu.go | 276 + internal/notify/feishu_linux_arm.go | 32 + internal/notify/manager.go | 323 + internal/notify/manager_test.go | 241 + internal/notify/pushplus.go | 88 + internal/notify/qq.go | 235 + internal/notify/qq_test.go | 223 + internal/notify/telegram.go | 177 + internal/notify/telegram_test.go | 31 + internal/notify/webhook.go | 331 + internal/notify/webhook_test.go | 424 ++ internal/proxy/server/http_proxy.go | 224 + internal/proxy/server/manager.go | 422 ++ internal/proxy/server/server.go | 287 + internal/proxy/server/server_bind_test.go | 25 + internal/proxy/server/stats.go | 119 + internal/proxy/traffic/qmi_wds.go | 23 + internal/proxy/traffic/realtime.go | 309 + internal/proxy/traffic/realtime_test.go | 160 + internal/proxy/traffic/sampler.go | 306 + internal/proxy/traffic/sampler_test.go | 246 + internal/qmi/client_options.go | 144 + internal/qmi/client_options_test.go | 254 + internal/qmi/control_device_holders_linux.go | 121 + internal/qmi/manager.go | 2413 +++++++ internal/qmi/manager_apdu_lease_test.go | 94 + internal/qmi/manager_events_test.go | 541 ++ .../qmi/manager_existing_connection_test.go | 104 + internal/qmi/manager_ipfamily_test.go | 30 + internal/qmi/manager_privateip_test.go | 18 + internal/qmi/manager_publicip_test.go | 264 + .../qmi/manager_recovery_exhausted_test.go | 24 + internal/qmi/manager_transport_test.go | 26 + internal/sim/aka_provider.go | 375 + internal/sim/aka_provider_test.go | 219 + internal/sim/apdu.go | 165 + internal/sim/diag.go | 26 + internal/sim/factory.go | 129 + internal/sim/factory_test.go | 223 + internal/sim/types.go | 23 + internal/simaid/aid.go | 73 + internal/simaid/apdu.go | 31 + internal/simaid/dir.go | 129 + internal/simaid/select.go | 39 + internal/simaid/simaid_test.go | 87 + internal/simaid/tlv.go | 56 + internal/smsnotify/policy.go | 30 + internal/smsnotify/policy_test.go | 47 + internal/updater/updater.go | 46 + internal/upstreamproxy/country_table.go | 363 + internal/upstreamproxy/country_table_test.go | 246 + internal/upstreamproxy/probe.go | 374 + internal/upstreamproxy/probe_test.go | 167 + internal/vowifihost/adapter.go | 90 + internal/vowifihost/controller.go | 287 + internal/vowifihost/controller_test.go | 151 + internal/vowifihost/lifecycle_api.go | 76 + internal/vowifihost/lifecycle_run.go | 286 + internal/vowifihost/manager.go | 148 + internal/vowifihost/manager_lifecycle_test.go | 150 + internal/vowifihost/reconcile.go | 73 + internal/vowifihost/reconcile_test.go | 92 + internal/vowifihost/recover_state.go | 152 + internal/vowifihost/recover_state_test.go | 39 + internal/vowifihost/runtime_access.go | 65 + internal/vowifihost/runtime_access_test.go | 34 + .../vowifihost/runtime_sim_select_test.go | 22 + internal/vowifihost/runtime_start.go | 133 + internal/vowifihost/runtime_start_test.go | 115 + internal/vowifihost/start.go | 76 + internal/vowifihost/start_test.go | 72 + internal/vowifihost/state_pubsub.go | 80 + internal/vowifihost/state_pubsub_test.go | 72 + internal/vowifihost/store.go | 323 + internal/vowifihost/teardown.go | 114 + internal/vowifihost/teardown_test.go | 70 + internal/web/fs.go | 14 + internal/websheet/bridge.js | 264 + internal/websheet/websheet.go | 844 +++ internal/websheet/websheet_test.go | 247 + packaging/openwrt/vohive/files/config.yaml | 15 + packaging/openwrt/vohive/files/vohive.init | 28 + pkg/logger/log_broadcaster.go | 147 + pkg/logger/logger.go | 313 + pkg/logger/run_mode.go | 49 + pkg/logger/slog_adapter.go | 191 + pkg/mbim/auth.go | 100 + pkg/mbim/auth_test.go | 191 + pkg/mbim/basicconnect.go | 52 + pkg/mbim/basicconnect_test.go | 52 + pkg/mbim/capability.go | 51 + pkg/mbim/capability_test.go | 65 + pkg/mbim/connect.go | 105 + pkg/mbim/connect_indication_test.go | 26 + pkg/mbim/connect_test.go | 76 + pkg/mbim/databuffer.go | 118 + pkg/mbim/databuffer_test.go | 131 + pkg/mbim/device.go | 293 + pkg/mbim/device_test.go | 336 + pkg/mbim/deviceservices.go | 81 + pkg/mbim/deviceservices_test.go | 73 + pkg/mbim/fragment.go | 125 + pkg/mbim/fragment_test.go | 136 + pkg/mbim/ipconfig.go | 94 + pkg/mbim/ipconfig_test.go | 63 + pkg/mbim/message.go | 69 + pkg/mbim/message_test.go | 64 + pkg/mbim/packet.go | 65 + pkg/mbim/packet_test.go | 51 + pkg/mbim/protocol.go | 178 + pkg/mbim/protocol_test.go | 92 + pkg/mbim/providers.go | 104 + pkg/mbim/providers_test.go | 147 + pkg/mbim/radio.go | 56 + pkg/mbim/radio_test.go | 53 + pkg/mbim/register.go | 96 + pkg/mbim/register_test.go | 153 + pkg/mbim/reset.go | 21 + pkg/mbim/reset_test.go | 53 + pkg/mbim/signal.go | 120 + pkg/mbim/signal_test.go | 59 + pkg/mbim/slotinfo.go | 53 + pkg/mbim/slotinfo_test.go | 55 + pkg/mbim/sms.go | 184 + pkg/mbim/sms_test.go | 287 + pkg/mbim/snapshot.go | 204 + pkg/mbim/snapshot_test.go | 186 + pkg/mbim/subscribe.go | 67 + pkg/mbim/subscribe_test.go | 68 + pkg/mbim/subscriber.go | 52 + pkg/mbim/subscriber_test.go | 95 + pkg/mbim/testsupport.go | 785 +++ pkg/mbim/transport.go | 89 + pkg/mbim/transport_proxy.go | 75 + pkg/mbim/transport_test.go | 83 + pkg/mbim/uicc.go | 149 + pkg/mbim/uicc_fileaccess.go | 153 + pkg/mbim/uicc_fileaccess_test.go | 180 + pkg/mbim/uicc_qmi.go | 210 + pkg/mbim/uicc_qmi_power.go | 127 + pkg/mbim/uicc_qmi_power_test.go | 36 + pkg/mbim/uicc_qmi_read.go | 124 + pkg/mbim/uicc_qmi_read_test.go | 217 + pkg/mbim/uicc_test.go | 232 + pkg/mbim/ussd.go | 115 + pkg/mbim/ussd_test.go | 205 + pkg/mbim/version.go | 43 + pkg/mbim/version_test.go | 53 + pkg/smscodec/binary_classifier.go | 462 ++ pkg/smscodec/binary_classifier_test.go | 131 + pkg/smscodec/pdu.go | 448 ++ pkg/smscodec/pdu_encoding_test.go | 47 + pkg/smscodec/pdu_rp_test.go | 50 + pkg/smscodec/pdu_trim.go | 148 + pkg/smscodec/pdu_trim_test.go | 94 + pkg/smscodec/reassembler.go | 81 + pkg/smscodec/reassembler_test.go | 93 + pkg/smscodec/wbxml_omacp.go | 878 +++ pkg/smscodec/wbxml_omacp_test.go | 321 + pkg/smsutil/compat.go | 66 + pkg/smsutil/compat_test.go | 63 + .../netlink/.github/scripts/modprobe.sh | 9 + .../netlink/.github/workflows/main.yml | 44 + third_party/netlink/.gitignore | 2 + third_party/netlink/CHANGELOG.md | 5 + third_party/netlink/LICENSE | 192 + third_party/netlink/Makefile | 30 + third_party/netlink/README.md | 91 + third_party/netlink/addr.go | 58 + third_party/netlink/addr_linux.go | 453 ++ third_party/netlink/addr_test.go | 369 + third_party/netlink/bpf_linux.go | 77 + third_party/netlink/bridge_linux.go | 444 ++ third_party/netlink/bridge_linux_test.go | 459 ++ third_party/netlink/chain.go | 22 + third_party/netlink/chain_linux.go | 120 + third_party/netlink/chain_test.go | 76 + third_party/netlink/class.go | 241 + third_party/netlink/class_linux.go | 406 ++ third_party/netlink/class_test.go | 680 ++ third_party/netlink/cmd/ipset-test/main.go | 165 + third_party/netlink/conntrack_linux.go | 934 +++ third_party/netlink/conntrack_test.go | 1801 +++++ third_party/netlink/conntrack_unspecified.go | 73 + third_party/netlink/devlink.go | 124 + third_party/netlink/devlink_linux.go | 1114 +++ third_party/netlink/devlink_test.go | 627 ++ third_party/netlink/devlink_unspecified.go | 68 + third_party/netlink/filter.go | 514 ++ third_party/netlink/filter_linux.go | 1317 ++++ third_party/netlink/filter_test.go | 2766 ++++++++ third_party/netlink/fou.go | 16 + third_party/netlink/fou_linux.go | 203 + third_party/netlink/fou_test.go | 132 + third_party/netlink/fou_unspecified.go | 16 + third_party/netlink/genetlink_linux.go | 180 + third_party/netlink/genetlink_unspecified.go | 26 + third_party/netlink/go.mod | 15 + third_party/netlink/go.sum | 14 + third_party/netlink/gtp_linux.go | 248 + third_party/netlink/gtp_test.go | 115 + third_party/netlink/handle_linux.go | 201 + third_party/netlink/handle_linux_test.go | 17 + third_party/netlink/handle_test.go | 352 + third_party/netlink/handle_unspecified.go | 305 + third_party/netlink/inet_diag.go | 40 + third_party/netlink/ioctl_linux.go | 90 + third_party/netlink/ipset_linux.go | 645 ++ third_party/netlink/ipset_linux_test.go | 829 +++ third_party/netlink/link.go | 1467 ++++ third_party/netlink/link_linux.go | 4328 ++++++++++++ third_party/netlink/link_test.go | 3979 +++++++++++ third_party/netlink/link_tuntap_linux.go | 151 + third_party/netlink/neigh.go | 41 + third_party/netlink/neigh_linux.go | 499 ++ third_party/netlink/neigh_test.go | 635 ++ third_party/netlink/netlink.go | 40 + third_party/netlink/netlink_linux.go | 14 + third_party/netlink/netlink_test.go | 313 + third_party/netlink/netlink_unspecified.go | 286 + third_party/netlink/netns_linux.go | 141 + third_party/netlink/netns_test.go | 80 + third_party/netlink/netns_unspecified.go | 20 + third_party/netlink/nexthop.go | 27 + third_party/netlink/nexthop_linux.go | 286 + third_party/netlink/nexthop_test.go | 155 + third_party/netlink/nl/addr_linux.go | 71 + third_party/netlink/nl/addr_linux_test.go | 69 + third_party/netlink/nl/bridge_linux.go | 158 + third_party/netlink/nl/bridge_linux_test.go | 35 + third_party/netlink/nl/conntrack_linux.go | 258 + third_party/netlink/nl/devlink_linux.go | 148 + third_party/netlink/nl/genetlink_linux.go | 89 + third_party/netlink/nl/ip6tnl_linux.go | 17 + third_party/netlink/nl/ipset_linux.go | 227 + third_party/netlink/nl/link_linux.go | 854 +++ third_party/netlink/nl/link_linux_test.go | 199 + third_party/netlink/nl/lwt_linux.go | 29 + third_party/netlink/nl/mpls_linux.go | 36 + third_party/netlink/nl/nexthop_linux.go | 33 + third_party/netlink/nl/nl_linux.go | 1103 +++ third_party/netlink/nl/nl_linux_test.go | 215 + third_party/netlink/nl/nl_unspecified.go | 11 + third_party/netlink/nl/parse_attr_linux.go | 79 + third_party/netlink/nl/rdma_link_linux.go | 49 + third_party/netlink/nl/route_linux.go | 109 + third_party/netlink/nl/route_linux_test.go | 67 + third_party/netlink/nl/seg6_linux.go | 154 + third_party/netlink/nl/seg6local_linux.go | 82 + third_party/netlink/nl/syscall.go | 77 + third_party/netlink/nl/tc_linux.go | 1794 +++++ third_party/netlink/nl/tc_linux_test.go | 368 + third_party/netlink/nl/vdpa_linux.go | 41 + third_party/netlink/nl/xfrm_linux.go | 318 + third_party/netlink/nl/xfrm_linux_test.go | 161 + third_party/netlink/nl/xfrm_monitor_linux.go | 32 + .../netlink/nl/xfrm_monitor_linux_test.go | 34 + third_party/netlink/nl/xfrm_policy_linux.go | 119 + .../netlink/nl/xfrm_policy_linux_test.go | 109 + third_party/netlink/nl/xfrm_state_linux.go | 361 + .../netlink/nl/xfrm_state_linux_test.go | 304 + third_party/netlink/order.go | 32 + third_party/netlink/proc_event_linux.go | 208 + third_party/netlink/proc_event_test.go | 81 + third_party/netlink/protinfo.go | 74 + third_party/netlink/protinfo_linux.go | 86 + third_party/netlink/protinfo_test.go | 198 + third_party/netlink/qdisc.go | 396 ++ third_party/netlink/qdisc_linux.go | 795 +++ third_party/netlink/qdisc_test.go | 628 ++ third_party/netlink/rdma_link_linux.go | 562 ++ third_party/netlink/rdma_link_test.go | 235 + third_party/netlink/route.go | 257 + third_party/netlink/route_linux.go | 1954 ++++++ third_party/netlink/route_test.go | 2827 ++++++++ third_party/netlink/route_unspecified.go | 22 + third_party/netlink/rule.go | 82 + third_party/netlink/rule_linux.go | 378 + third_party/netlink/rule_nonlinux.go | 8 + third_party/netlink/rule_test.go | 697 ++ third_party/netlink/socket.go | 104 + third_party/netlink/socket_linux.go | 624 ++ third_party/netlink/socket_linux_test.go | 145 + third_party/netlink/socket_test.go | 176 + third_party/netlink/socket_unspecified.go | 40 + third_party/netlink/socket_xdp_linux.go | 207 + third_party/netlink/socket_xdp_linux_test.go | 53 + third_party/netlink/socket_xdp_unspecified.go | 12 + third_party/netlink/tcp.go | 92 + third_party/netlink/tcp_linux.go | 368 + third_party/netlink/tcp_linux_test.go | 153 + .../netlink/testdata/ipset_list_result | Bin 0 -> 228 bytes .../netlink/testdata/ipset_protocol_result | Bin 0 -> 12 bytes third_party/netlink/unix_diag.go | 27 + third_party/netlink/vdpa_linux.go | 491 ++ third_party/netlink/vdpa_linux_test.go | 270 + third_party/netlink/virtio.go | 132 + third_party/netlink/xdp_diag.go | 34 + third_party/netlink/xdp_linux.go | 46 + third_party/netlink/xfrm_linux.go | 83 + third_party/netlink/xfrm_monitor_linux.go | 101 + .../netlink/xfrm_monitor_linux_test.go | 52 + third_party/netlink/xfrm_policy_linux.go | 371 + third_party/netlink/xfrm_policy_linux_test.go | 285 + third_party/netlink/xfrm_state_linux.go | 704 ++ third_party/netlink/xfrm_state_linux_test.go | 529 ++ third_party/netlink/xfrm_unspecified.go | 7 + third_party/qqbot/LICENSE | 176 + third_party/qqbot/README.md | 57 + third_party/qqbot/app.go | 305 + third_party/qqbot/app_test.go | 336 + third_party/qqbot/go.mod | 5 + third_party/qqbot/go.sum | 2 + third_party/qqbot/handler.go | 7 + third_party/qqbot/internal/auth/source.go | 145 + .../qqbot/internal/auth/source_test.go | 52 + third_party/qqbot/internal/dispatch/engine.go | 131 + .../qqbot/internal/dispatch/engine_test.go | 75 + third_party/qqbot/internal/dispatch/store.go | 44 + third_party/qqbot/internal/rest/client.go | 311 + .../qqbot/internal/rest/client_test.go | 102 + third_party/qqbot/internal/stream/pump.go | 304 + third_party/qqbot/model.go | 74 + third_party/qqbot/settings.go | 135 + third_party/quectel-qmi-go/LICENSE | 21 + third_party/quectel-qmi-go/README.md | 322 + third_party/quectel-qmi-go/cmd/cm/main.go | 182 + .../quectel-qmi-go/cmd/dms-tool/main.go | 216 + .../quectel-qmi-go/cmd/info-tool/main.go | 124 + .../quectel-qmi-go/cmd/nas-tool/main.go | 188 + .../quectel-qmi-go/cmd/sms-tool/main.go | 176 + .../quectel-qmi-go/cmd/wda-tool/main.go | 147 + .../quectel-qmi-go/cmd/wds-tool/main.go | 163 + third_party/quectel-qmi-go/go.mod | 18 + third_party/quectel-qmi-go/go.sum | 32 + .../quectel-qmi-go/pkg/device/discovery.go | 462 ++ .../pkg/device/discovery_static_test.go | 120 + .../pkg/manager/allocate_services_test.go | 268 + .../quectel-qmi-go/pkg/manager/callbacks.go | 773 ++ .../pkg/manager/callbacks_test.go | 29 + .../pkg/manager/cleanup_test.go | 85 + .../pkg/manager/core_ready_test.go | 283 + .../quectel-qmi-go/pkg/manager/device.go | 40 + .../pkg/manager/device_query.go | 1161 +++ .../pkg/manager/existing_data_cleanup_test.go | 259 + .../pkg/manager/health_check_jitter_test.go | 46 + .../pkg/manager/indication_log_test.go | 16 + .../quectel-qmi-go/pkg/manager/logger.go | 119 + .../quectel-qmi-go/pkg/manager/manager.go | 4692 +++++++++++++ .../pkg/manager/nas_indication_test.go | 569 ++ .../quectel-qmi-go/pkg/manager/pool.go | 591 ++ .../pkg/manager/raw_sms_decode_test.go | 114 + .../pkg/manager/raw_sms_event_test.go | 99 + .../pkg/manager/recovery_exhausted_test.go | 141 + .../pkg/manager/service_recovery.go | 867 +++ .../pkg/manager/service_recovery_test.go | 869 +++ .../pkg/manager/sms_send_encoding_test.go | 51 + .../quectel-qmi-go/pkg/manager/sms_trim.go | 63 + .../pkg/manager/sms_trim_test.go | 28 + .../quectel-qmi-go/pkg/manager/smsc.go | 676 ++ .../quectel-qmi-go/pkg/manager/smsc_test.go | 306 + .../quectel-qmi-go/pkg/manager/snapshot.go | 648 ++ .../pkg/manager/uim_apdu_context_test.go | 101 + .../manager/uim_post_switch_reload_test.go | 69 + .../pkg/manager/uim_provisioning.go | 129 + .../pkg/manager/uim_provisioning_test.go | 161 + .../pkg/manager/uim_readiness.go | 221 + .../pkg/manager/uim_readiness_test.go | 330 + .../pkg/manager/uim_recovery.go | 246 + .../quectel-qmi-go/pkg/manager/voice_test.go | 238 + .../quectel-qmi-go/pkg/netcfg/configurator.go | 89 + .../quectel-qmi-go/pkg/netcfg/darwin.go | 118 + .../pkg/netcfg/factory_darwin.go | 10 + .../pkg/netcfg/factory_linux.go | 10 + .../pkg/netcfg/factory_windows.go | 10 + .../quectel-qmi-go/pkg/netcfg/linux.go | 363 + .../quectel-qmi-go/pkg/netcfg/netcfg.go | 103 + .../quectel-qmi-go/pkg/netcfg/windows.go | 138 + third_party/quectel-qmi-go/pkg/qmi/client.go | 1093 +++ .../pkg/qmi/client_indication_test.go | 158 + third_party/quectel-qmi-go/pkg/qmi/ctl.go | 72 + .../quectel-qmi-go/pkg/qmi/ctl_test.go | 190 + third_party/quectel-qmi-go/pkg/qmi/dms.go | 1028 +++ .../quectel-qmi-go/pkg/qmi/dms_test.go | 246 + third_party/quectel-qmi-go/pkg/qmi/errors.go | 187 + .../quectel-qmi-go/pkg/qmi/errors_test.go | 12 + third_party/quectel-qmi-go/pkg/qmi/frame.go | 549 ++ third_party/quectel-qmi-go/pkg/qmi/ims.go | 231 + .../quectel-qmi-go/pkg/qmi/ims_test.go | 278 + third_party/quectel-qmi-go/pkg/qmi/imsa.go | 267 + .../pkg/qmi/imsdcm_compat_test.go | 70 + third_party/quectel-qmi-go/pkg/qmi/imsp.go | 62 + .../pkg/qmi/mapping_regression_test.go | 72 + third_party/quectel-qmi-go/pkg/qmi/nas.go | 1653 +++++ .../quectel-qmi-go/pkg/qmi/nas_test.go | 553 ++ .../pkg/qmi/proxy_client_test.go | 416 ++ .../pkg/qmi/proxy_transport_linux.go | 103 + .../pkg/qmi/proxy_transport_linux_test.go | 134 + .../pkg/qmi/proxy_transport_unsupported.go | 13 + .../pkg/qmi/test_helpers_test.go | 9 + .../quectel-qmi-go/pkg/qmi/transport.go | 34 + third_party/quectel-qmi-go/pkg/qmi/uim.go | 1910 +++++ .../pkg/qmi/uim_feature_test.go | 704 ++ .../pkg/qmi/uim_metadata_test.go | 29 + .../quectel-qmi-go/pkg/qmi/uim_spn_test.go | 54 + .../quectel-qmi-go/pkg/qmi/uim_test.go | 24 + third_party/quectel-qmi-go/pkg/qmi/voice.go | 916 +++ .../quectel-qmi-go/pkg/qmi/voice_test.go | 441 ++ third_party/quectel-qmi-go/pkg/qmi/wda.go | 271 + third_party/quectel-qmi-go/pkg/qmi/wds.go | 1066 +++ .../quectel-qmi-go/pkg/qmi/wds_stop_test.go | 40 + .../quectel-qmi-go/pkg/qmi/wds_test.go | 202 + third_party/quectel-qmi-go/pkg/qmi/wms.go | 952 +++ .../quectel-qmi-go/pkg/qmi/wms_test.go | 512 ++ .../vowifi-go/.github/workflows/ci.yml | 30 + third_party/vowifi-go/AGENTS.md | 121 + third_party/vowifi-go/LICENSE | 661 ++ third_party/vowifi-go/Makefile | 39 + third_party/vowifi-go/README.md | 63 + third_party/vowifi-go/README.zh-CN.md | 47 + third_party/vowifi-go/docs/ARCHITECTURE.md | 51 + third_party/vowifi-go/docs/DEVELOPMENT.md | 47 + third_party/vowifi-go/docs/DISCLAIMER.md | 60 + .../vowifi-go/docs/DISCLAIMER.zh-CN.md | 33 + third_party/vowifi-go/docs/FEATURES.md | 200 + third_party/vowifi-go/engine/sim/sim.go | 23 + .../vowifi-go/engine/swu/eap_reauth.go | 43 + .../vowifi-go/engine/swu/eapaka/crypto.go | 994 +++ .../engine/swu/eapaka/crypto_test.go | 1085 +++ .../vowifi-go/engine/swu/eapaka/eapaka.go | 551 ++ .../engine/swu/eapaka/eapaka_test.go | 332 + third_party/vowifi-go/engine/swu/esp/esp.go | 351 + .../vowifi-go/engine/swu/esp/esp_test.go | 146 + .../vowifi-go/engine/swu/ike_control.go | 216 + .../vowifi-go/engine/swu/ike_control_test.go | 312 + .../engine/swu/ike_tunnel_manager.go | 645 ++ .../engine/swu/ike_tunnel_manager_test.go | 423 ++ .../vowifi-go/engine/swu/ikev2/auth.go | 1021 +++ .../vowifi-go/engine/swu/ikev2/auth_test.go | 1601 +++++ .../vowifi-go/engine/swu/ikev2/childsa.go | 183 + .../engine/swu/ikev2/childsa_test.go | 76 + .../engine/swu/ikev2/create_child.go | 263 + .../engine/swu/ikev2/create_child_test.go | 185 + .../vowifi-go/engine/swu/ikev2/crypto.go | 65 + .../vowifi-go/engine/swu/ikev2/crypto_test.go | 40 + .../engine/swu/ikev2/informational.go | 163 + .../engine/swu/ikev2/informational_test.go | 215 + .../vowifi-go/engine/swu/ikev2/init.go | 396 ++ .../vowifi-go/engine/swu/ikev2/init_test.go | 220 + .../vowifi-go/engine/swu/ikev2/keys.go | 167 + .../vowifi-go/engine/swu/ikev2/payloads.go | 339 + .../engine/swu/ikev2/payloads_test.go | 213 + third_party/vowifi-go/engine/swu/ikev2/sa.go | 313 + .../vowifi-go/engine/swu/ikev2/sa_test.go | 56 + .../engine/swu/ikev2/session_payloads.go | 291 + .../engine/swu/ikev2/session_payloads_test.go | 69 + third_party/vowifi-go/engine/swu/ikev2/sk.go | 221 + .../vowifi-go/engine/swu/ikev2/sk_test.go | 186 + .../vowifi-go/engine/swu/ikev2/types.go | 208 + .../vowifi-go/engine/swu/ikev2/types_test.go | 68 + .../vowifi-go/engine/swu/packet_pump.go | 279 + .../vowifi-go/engine/swu/packet_pump_test.go | 242 + .../vowifi-go/engine/swu/packet_session.go | 510 ++ .../engine/swu/packet_session_test.go | 260 + third_party/vowifi-go/engine/swu/swu.go | 149 + third_party/vowifi-go/engine/swu/swu_test.go | 49 + third_party/vowifi-go/engine/swu/tun_linux.go | 172 + .../vowifi-go/engine/swu/tun_linux_test.go | 51 + .../vowifi-go/engine/swu/tun_routing.go | 419 ++ .../vowifi-go/engine/swu/tun_routing_test.go | 177 + .../engine/swu/tun_tunnel_manager.go | 391 ++ .../engine/swu/tun_tunnel_manager_test.go | 422 ++ .../vowifi-go/engine/swu/tun_unsupported.go | 34 + .../vowifi-go/engine/swu/udp_esp_transport.go | 220 + .../engine/swu/udp_esp_transport_test.go | 100 + third_party/vowifi-go/engine/swu/xfrm.go | 366 + third_party/vowifi-go/engine/swu/xfrm_test.go | 173 + third_party/vowifi-go/go.mod | 22 + third_party/vowifi-go/go.sum | 35 + .../vowifi-go/runtimehost/carrier/carrier.go | 209 + .../runtimehost/carrier/carrier_test.go | 59 + .../vowifi-go/runtimehost/e911/e911.go | 866 +++ .../vowifi-go/runtimehost/e911/e911_test.go | 1087 +++ .../runtimehost/eventhost/eventhost.go | 52 + .../runtimehost/identity/identity.go | 273 + .../runtimehost/identity/identity_test.go | 140 + .../vowifi-go/runtimehost/imsregistrar.go | 750 ++ .../runtimehost/imsregistrar_test.go | 924 +++ .../runtimehost/messaging/ims_inbound_sms.go | 321 + .../runtimehost/messaging/ims_sms.go | 179 + .../runtimehost/messaging/ims_sms_test.go | 176 + .../runtimehost/messaging/ims_ussd.go | 470 ++ .../runtimehost/messaging/ims_ussd_inbound.go | 164 + .../runtimehost/messaging/ims_ussd_test.go | 283 + .../runtimehost/messaging/messaging.go | 621 ++ .../runtimehost/messaging/messaging_test.go | 478 ++ .../runtimehost/messaging/sms_pdu.go | 819 +++ .../runtimehost/messaging/sms_pdu_test.go | 166 + .../runtimehost/messaging/ussd_xml.go | 229 + .../runtimehost/messaging/ussd_xml_test.go | 52 + .../vowifi-go/runtimehost/simauth/aka.go | 193 + .../vowifi-go/runtimehost/simauth/apdu.go | 222 + .../runtimehost/simauth/apdu_test.go | 144 + .../vowifi-go/runtimehost/simauth/tlv.go | 150 + third_party/vowifi-go/runtimehost/types.go | 1301 ++++ .../vowifi-go/runtimehost/types_test.go | 1207 ++++ .../runtimehost/voiceclient/dialog.go | 237 + .../runtimehost/voiceclient/security.go | 315 + .../runtimehost/voiceclient/sip_resolver.go | 392 ++ .../voiceclient/sip_resolver_test.go | 38 + .../runtimehost/voiceclient/voiceclient.go | 1453 ++++ .../voiceclient/voiceclient_test.go | 1200 ++++ .../runtimehost/voiceclient/wire_flow.go | 427 ++ .../runtimehost/voiceclient/wire_flow_test.go | 306 + .../voiceclient/wire_sip_transport.go | 254 + .../runtimehost/voiceclient/wire_transport.go | 784 +++ .../voiceclient/wire_transport_test.go | 777 +++ .../runtimehost/voicehost/ims_agent.go | 1095 +++ .../runtimehost/voicehost/ims_agent_test.go | 1193 ++++ .../voicehost/ims_inbound_agent.go | 590 ++ .../voicehost/ims_inbound_agent_test.go | 494 ++ .../runtimehost/voicehost/ims_inbound_wire.go | 645 ++ .../voicehost/ims_inbound_wire_test.go | 754 ++ .../runtimehost/voicehost/ims_message.go | 93 + .../runtimehost/voicehost/rtcp_feedback.go | 230 + .../runtimehost/voicehost/rtp_relay.go | 542 ++ .../runtimehost/voicehost/rtp_relay_test.go | 348 + .../runtimehost/voicehost/sdp_rewrite.go | 82 + .../runtimehost/voicehost/sdp_rewrite_test.go | 46 + .../runtimehost/voicehost/srtp_media.go | 260 + .../runtimehost/voicehost/srtp_media_test.go | 216 + .../runtimehost/voicehost/voicehost.go | 739 ++ .../runtimehost/voicehost/voicehost_test.go | 392 ++ third_party/vowifi-go/scripts/ci.sh | 122 + web/.gitignore | 27 + web/README.md | 35 + web/eslint.config.js | 72 + web/go.mod | 3 + web/index.html | 48 + web/package-lock.json | 6210 +++++++++++++++++ web/package.json | 48 + web/postcss.config.js | 7 + web/public/favicon.svg | 12 + web/public/vite.svg | 1 + web/src/App.vue | 205 + web/src/assets/vue.svg | 1 + web/src/auto-imports.d.ts | 90 + web/src/components.d.ts | 78 + web/src/components/CardPolicyPanel.vue | 215 + web/src/components/CarrierWebsheetDialog.vue | 158 + web/src/components/DebugPanel.vue | 143 + web/src/components/DeviceAddDialog.vue | 197 + web/src/components/DeviceAtTab.vue | 183 + web/src/components/DeviceCard.vue | 151 + web/src/components/DeviceConfigTab.vue | 121 + web/src/components/DeviceDetailHeader.vue | 77 + web/src/components/DeviceDetailLoading.vue | 81 + web/src/components/DeviceEsimTab.vue | 868 +++ web/src/components/DeviceListPanel.vue | 167 + web/src/components/DeviceOverviewTab.vue | 385 + web/src/components/DeviceUssdTab.vue | 213 + web/src/components/EmptyState.vue | 21 + web/src/components/ErrorBoundary.vue | 55 + web/src/components/ErrorState.vue | 45 + web/src/components/EsimCardPolicyInline.vue | 163 + web/src/components/FieldRow.vue | 55 + web/src/components/HelloWorld.vue | 43 + web/src/components/ListSkeleton.vue | 11 + web/src/components/LoadingScreen.vue | 47 + .../components/OperatorSelectionDialog.vue | 196 + web/src/components/PageHeader.vue | 16 + web/src/components/RefreshButton.vue | 19 + web/src/components/StatusLight.vue | 30 + web/src/components/SwitchDark.vue | 22 + web/src/components/TrafficAnalysisPanel.vue | 556 ++ web/src/components/deviceEsimNotifications.ts | 69 + .../components/deviceEsimOperationNotice.ts | 64 + web/src/components/deviceEsimOptimistic.ts | 37 + .../components/deviceEsimOverviewRefresh.ts | 10 + .../components/deviceOverviewActiveEsim.ts | 5 + web/src/components/statusLight.ts | 23 + web/src/composables/useCardPolicyToggles.ts | 145 + .../useCardPolicyToggles.typecheck.ts | 16 + web/src/composables/useEventStream.ts | 140 + web/src/composables/usePollingScheduler.ts | 99 + web/src/composables/useSensitiveVisibility.ts | 36 + .../useSensitiveVisibility.typecheck.ts | 6 + web/src/composables/useSmartPoll.ts | 109 + web/src/constants/atTemplates.ts | 64 + web/src/debug/collector.ts | 162 + web/src/disclaimer.ts | 8 + web/src/env.d.ts | 43 + web/src/layouts/AuthenticatedShell.vue | 432 ++ web/src/layouts/UnauthenticatedShell.vue | 31 + web/src/main.ts | 148 + web/src/router/index.ts | 63 + web/src/services/cards.ts | 34 + web/src/services/dashboard.ts | 12 + web/src/services/devices.ts | 396 ++ web/src/services/http.ts | 57 + web/src/services/logs.ts | 19 + web/src/services/proxy.ts | 42 + web/src/services/sms.ts | 113 + web/src/services/system.ts | 260 + web/src/services/traffic.ts | 38 + web/src/services/upstream-proxy.ts | 75 + web/src/stores/auth.ts | 77 + web/src/stores/dashboard.ts | 58 + web/src/stores/devices.ts | 123 + web/src/stores/logs.ts | 44 + web/src/stores/proxy.ts | 71 + web/src/stores/settings.ts | 451 ++ web/src/stores/sms.ts | 67 + web/src/stores/upstream-proxy.ts | 99 + web/src/style.css | 231 + web/src/types/api.ts | 497 ++ web/src/types/domain.ts | 37 + web/src/types/view-model.ts | 31 + web/src/utils/clipboard.ts | 52 + web/src/utils/deviceBackend.ts | 6 + web/src/utils/deviceLifecycle.ts | 68 + web/src/utils/mcc-mnc.ts | 179 + web/src/utils/upstreamProxyAddress.ts | 12 + web/src/views/Dashboard.vue | 156 + web/src/views/Devices.vue | 1376 ++++ web/src/views/Login.vue | 123 + web/src/views/Logs.vue | 246 + web/src/views/Proxy.vue | 956 +++ web/src/views/Settings.vue | 885 +++ web/src/views/Sms.vue | 1220 ++++ web/tailwind.config.cjs | 28 + web/tests/deviceConfigTabAtPort.test.ts | 28 + web/tsconfig.json | 18 + web/vite.config.ts | 87 + 984 files changed, 255607 insertions(+) create mode 100644 .dockerignore create mode 100644 .github/workflows/binary-release.yml create mode 100644 .github/workflows/docker-build.yml create mode 100644 .github/workflows/docker-publish.yml create mode 100644 .github/workflows/web-ci.yml create mode 100644 .gitignore create mode 100644 DOCKERHUB.md create mode 100644 Dockerfile create mode 100644 Dockerfile.github create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 THIRD_PARTY_NOTICES.md create mode 100644 cmd/mbimprobe/main.go create mode 100644 cmd/vohive/main.go create mode 100644 config/config.example.yaml create mode 100644 docker-compose.yml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 go.work create mode 100644 internal/apduarbiter/arbiter.go create mode 100644 internal/apduarbiter/arbiter_test.go create mode 100644 internal/apduarbiter/simauth_ready.go create mode 100644 internal/api/auth_security_test.go create mode 100644 internal/api/card_policy.go create mode 100644 internal/api/card_policy_test.go create mode 100644 internal/api/device_e911.go create mode 100644 internal/api/device_e911_test.go create mode 100644 internal/api/device_mgmt.go create mode 100644 internal/api/device_mgmt_add_imei_test.go create mode 100644 internal/api/device_mgmt_at_test.go create mode 100644 internal/api/device_mgmt_backend_mode_test.go create mode 100644 internal/api/device_mgmt_cardpolicy_writethrough_test.go create mode 100644 internal/api/device_mgmt_discovery_test.go create mode 100644 internal/api/device_mgmt_flightmode_test.go create mode 100644 internal/api/device_mgmt_ipversion_test.go create mode 100644 internal/api/device_mgmt_lifecycle_test.go create mode 100644 internal/api/device_mgmt_overview_display_test.go create mode 100644 internal/api/device_mgmt_overview_stream_test.go create mode 100644 internal/api/device_mgmt_overview_test.go create mode 100644 internal/api/device_mgmt_phone_test.go create mode 100644 internal/api/device_mgmt_qmi_proxy_test.go create mode 100644 internal/api/device_mgmt_restart.go create mode 100644 internal/api/device_mgmt_restart_test.go create mode 100644 internal/api/device_mgmt_test_helpers_test.go create mode 100644 internal/api/device_mgmt_ussd_test.go create mode 100644 internal/api/device_operator_selection.go create mode 100644 internal/api/device_operator_selection_test.go create mode 100644 internal/api/device_policy_display.go create mode 100644 internal/api/device_policy_display_test.go create mode 100644 internal/api/device_traffic.go create mode 100644 internal/api/device_traffic_test.go create mode 100644 internal/api/docs_assets/swagger-ui/LICENSE create mode 100644 internal/api/docs_assets/swagger-ui/NOTICE create mode 100644 internal/api/docs_assets/swagger-ui/swagger-ui-bundle.js create mode 100644 internal/api/docs_assets/swagger-ui/swagger-ui-bundle.js.LICENSE.txt create mode 100644 internal/api/docs_assets/swagger-ui/swagger-ui-standalone-preset.js create mode 100644 internal/api/docs_assets/swagger-ui/swagger-ui-standalone-preset.js.LICENSE.txt create mode 100644 internal/api/docs_assets/swagger-ui/swagger-ui.css create mode 100644 internal/api/openapi.go create mode 100644 internal/api/openapi.vohive.yaml create mode 100644 internal/api/openapi_test.go create mode 100644 internal/api/path_params.go create mode 100644 internal/api/proxy.go create mode 100644 internal/api/proxy_test.go create mode 100644 internal/api/route_adapters.go create mode 100644 internal/api/server.go create mode 100644 internal/api/settings.go create mode 100644 internal/api/settings_bark.go create mode 100644 internal/api/settings_email.go create mode 100644 internal/api/settings_webhook.go create mode 100644 internal/api/sms_inbox_test.go create mode 100644 internal/api/system.go create mode 100644 internal/api/system_test.go create mode 100644 internal/api/traffic.go create mode 100644 internal/api/upstream_proxy.go create mode 100644 internal/api/upstream_proxy_country_rules_test.go create mode 100644 internal/api/websheet.go create mode 100644 internal/api/websheet_test.go create mode 100644 internal/backend/at_backend.go create mode 100644 internal/backend/at_operator_selection.go create mode 100644 internal/backend/backend.go create mode 100644 internal/backend/check.go create mode 100644 internal/backend/discovery.go create mode 100644 internal/backend/factory.go create mode 100644 internal/backend/info.go create mode 100644 internal/backend/mbim_backend.go create mode 100644 internal/backend/mbim_backend_aka.go create mode 100644 internal/backend/mbim_backend_capability.go create mode 100644 internal/backend/mbim_backend_identity.go create mode 100644 internal/backend/mbim_backend_simauth.go create mode 100644 internal/backend/mbim_backend_simfiles.go create mode 100644 internal/backend/mbim_backend_simfiles_test.go create mode 100644 internal/backend/mbim_backend_sms.go create mode 100644 internal/backend/mbim_backend_test.go create mode 100644 internal/backend/mbim_backend_ussd.go create mode 100644 internal/backend/mbim_backend_ussd_test.go create mode 100644 internal/backend/mbim_operator_selection.go create mode 100644 internal/backend/mbim_operator_selection_test.go create mode 100644 internal/backend/mbim_source.go create mode 100644 internal/backend/operator_selection.go create mode 100644 internal/backend/operator_selection_test.go create mode 100644 internal/backend/opmode.go create mode 100644 internal/backend/qmi_backend.go create mode 100644 internal/backend/qmi_backend_msisdn_test.go create mode 100644 internal/backend/qmi_backend_send_test.go create mode 100644 internal/backend/qmi_backend_shortcode_test.go create mode 100644 internal/backend/qmi_backend_ussd.go create mode 100644 internal/backend/qmi_operator_selection.go create mode 100644 internal/backend/qmi_signal_test.go create mode 100644 internal/backend/registration.go create mode 100644 internal/backend/simauth.go create mode 100644 internal/backend/sms.go create mode 100644 internal/backend/smsc.go create mode 100644 internal/backend/types.go create mode 100644 internal/backend/ussd.go create mode 100644 internal/cardpolicy/policy.go create mode 100644 internal/cardpolicy/policy_test.go create mode 100644 internal/config/config.go create mode 100644 internal/config/config_test.go create mode 100644 internal/config/esim_transport_test.go create mode 100644 internal/config/imei.go create mode 100644 internal/config/imei_test.go create mode 100644 internal/config/ipversion_test.go create mode 100644 internal/config/manager.go create mode 100644 internal/config/mbim_transport_test.go create mode 100644 internal/config/persist.go create mode 100644 internal/config/persist_devices.go create mode 100644 internal/config/persist_devices_imei_test.go create mode 100644 internal/config/persist_devices_slimming_test.go create mode 100644 internal/data/repo/db_repo.go create mode 100644 internal/data/repo/repo.go create mode 100644 internal/db/card_policy.go create mode 100644 internal/db/card_policy_canonical_migration.go create mode 100644 internal/db/card_policy_canonical_test.go create mode 100644 internal/db/card_policy_resolver.go create mode 100644 internal/db/card_policy_test.go create mode 100644 internal/db/check_test.go create mode 100644 internal/db/db.go create mode 100644 internal/db/db_ipv6_test.go create mode 100644 internal/db/iccid_rekey_migration.go create mode 100644 internal/db/iccid_rekey_migration_test.go create mode 100644 internal/db/pending_phone_e2e_test.go create mode 100644 internal/db/pending_phone_test.go create mode 100644 internal/db/phone_number_test.go create mode 100644 internal/db/phone_number_validation_test.go create mode 100644 internal/db/proxy_instance.go create mode 100644 internal/db/sms_delete_test.go create mode 100644 internal/db/sms_delivery.go create mode 100644 internal/db/sms_iccid_query_test.go create mode 100644 internal/db/sms_query.go create mode 100644 internal/db/sqlite_dialector.go create mode 100644 internal/db/traffic.go create mode 100644 internal/db/traffic_latest.go create mode 100644 internal/db/traffic_rollup.go create mode 100644 internal/db/traffic_test.go create mode 100644 internal/db/upstream_proxy.go create mode 100644 internal/db/upstream_proxy_test.go create mode 100644 internal/device/at_port_resolver.go create mode 100644 internal/device/at_port_resolver_test.go create mode 100644 internal/device/at_radio_snapshot.go create mode 100644 internal/device/at_radio_snapshot_test.go create mode 100644 internal/device/backend_init.go create mode 100644 internal/device/device_limit.go create mode 100644 internal/device/discovery_compat.go create mode 100644 internal/device/discovery_compat_test.go create mode 100644 internal/device/discovery_enrichment.go create mode 100644 internal/device/discovery_enrichment_test.go create mode 100644 internal/device/health_watchdog.go create mode 100644 internal/device/health_watchdog_test.go create mode 100644 internal/device/identity_resolver.go create mode 100644 internal/device/identity_resolver_test.go create mode 100644 internal/device/lifecycle.go create mode 100644 internal/device/lifecycle_test.go create mode 100644 internal/device/mbim_bootstrap_test.go create mode 100644 internal/device/mbim_discovery_test.go create mode 100644 internal/device/mbim_imei_probe.go create mode 100644 internal/device/mbim_imei_probe_test.go create mode 100644 internal/device/mbim_registration.go create mode 100644 internal/device/mbim_registration_test.go create mode 100644 internal/device/network_controller.go create mode 100644 internal/device/network_controller_test.go create mode 100644 internal/device/notifier.go create mode 100644 internal/device/notifier_nil_test.go create mode 100644 internal/device/operator_selection.go create mode 100644 internal/device/operator_selection_test.go create mode 100644 internal/device/phone_number_sync_test.go create mode 100644 internal/device/policy_projection.go create mode 100644 internal/device/policy_projection_test.go create mode 100644 internal/device/pool.go create mode 100644 internal/device/pool_apdu_cleanup.go create mode 100644 internal/device/pool_apdu_cleanup_test.go create mode 100644 internal/device/pool_at_radio_warmup.go create mode 100644 internal/device/pool_attachment_persist.go create mode 100644 internal/device/pool_attachment_persist_test.go create mode 100644 internal/device/pool_bootstrap.go create mode 100644 internal/device/pool_bootstrap_test.go create mode 100644 internal/device/pool_device_limit_test.go create mode 100644 internal/device/pool_esim_imei_test.go create mode 100644 internal/device/pool_esim_manager_test.go create mode 100644 internal/device/pool_esim_switch.go create mode 100644 internal/device/pool_esim_switch_restore_test.go create mode 100644 internal/device/pool_health_ip.go create mode 100644 internal/device/pool_health_ip_test.go create mode 100644 internal/device/pool_health_ip_v6_test.go create mode 100644 internal/device/pool_lifecycle_test.go create mode 100644 internal/device/pool_mbim_indications_test.go create mode 100644 internal/device/pool_mbim_recovery_test.go create mode 100644 internal/device/pool_migration_test.go create mode 100644 internal/device/pool_policy_sync_test.go create mode 100644 internal/device/pool_proxy_reconcile_test.go create mode 100644 internal/device/pool_qmi_mode_test.go create mode 100644 internal/device/pool_qmi_reconnect_test.go create mode 100644 internal/device/pool_qmi_sms_test.go create mode 100644 internal/device/pool_qmi_startup_network_test.go create mode 100644 internal/device/pool_reboot_recovery.go create mode 100644 internal/device/pool_reboot_recovery_test.go create mode 100644 internal/device/pool_rescan_characterization_test.go create mode 100644 internal/device/pool_rescan_collect_test.go create mode 100644 internal/device/pool_rescan_nonqmi_test.go create mode 100644 internal/device/pool_sms.go create mode 100644 internal/device/pool_sms_mbim.go create mode 100644 internal/device/pool_sms_mbim_test.go create mode 100644 internal/device/pool_smsc_test.go create mode 100644 internal/device/pool_state.go create mode 100644 internal/device/pool_uim_indication_test.go create mode 100644 internal/device/pool_vowifi_autostart.go create mode 100644 internal/device/pool_vowifi_controller_test.go create mode 100644 internal/device/pool_vowifi_country_proxy_test.go create mode 100644 internal/device/pool_vowifi_host.go create mode 100644 internal/device/pool_vowifi_identity_test.go create mode 100644 internal/device/pool_vowifi_lock_test.go create mode 100644 internal/device/pool_vowifi_policy_test.go create mode 100644 internal/device/pool_vowifi_reconcile.go create mode 100644 internal/device/pool_vowifi_reconcile_test.go create mode 100644 internal/device/pool_vowifi_runtime.go create mode 100644 internal/device/pool_vowifi_runtime_test.go create mode 100644 internal/device/pool_vowifi_voice_test.go create mode 100644 internal/device/pool_vowifi_wiring.go create mode 100644 internal/device/post_switch_convergence.go create mode 100644 internal/device/post_switch_convergence_test.go create mode 100644 internal/device/qmi_core_start.go create mode 100644 internal/device/qmi_core_start_test.go create mode 100644 internal/device/qmi_modem_adapter.go create mode 100644 internal/device/qmi_recovery_attachment.go create mode 100644 internal/device/qmi_recovery_attachment_test.go create mode 100644 internal/device/qmi_recovery_readiness.go create mode 100644 internal/device/qmi_recovery_readiness_test.go create mode 100644 internal/device/qmi_registration.go create mode 100644 internal/device/qmi_registration_test.go create mode 100644 internal/device/qmi_static_discovery.go create mode 100644 internal/device/qmi_static_discovery_test.go create mode 100644 internal/device/qmi_transport_error.go create mode 100644 internal/device/qmi_transport_error_test.go create mode 100644 internal/device/switch_reinit.go create mode 100644 internal/device/switch_reinit_test.go create mode 100644 internal/device/transport_recovery_controller.go create mode 100644 internal/device/transport_recovery_controller_test.go create mode 100644 internal/device/udev.go create mode 100644 internal/device/udev_test.go create mode 100644 internal/device/vowifi_delivery_store.go create mode 100644 internal/device/vowifi_dispatcher.go create mode 100644 internal/device/vowifi_eventhost_boundary_test.go create mode 100644 internal/device/vowifi_external_boundary_test.go create mode 100644 internal/device/vowifi_host_boundary_test.go create mode 100644 internal/device/vowifi_modem_adapter.go create mode 100644 internal/device/vowifi_plmn_format.go create mode 100644 internal/device/vowifi_plmn_format_test.go create mode 100644 internal/device/vowifi_runtime_store_test.go create mode 100644 internal/device/vowifi_sms_history_recorder.go create mode 100644 internal/device/vowifi_sms_history_recorder_test.go create mode 100644 internal/device/vowifi_start_errors.go create mode 100644 internal/device/vowifi_start_orchestrator.go create mode 100644 internal/device/vowifi_start_profile.go create mode 100644 internal/device/vowifi_state_api.go create mode 100644 internal/device/vowifi_teardown.go create mode 100644 internal/device/vowifi_voice_lifecycle_boundary_test.go create mode 100644 internal/device/worker_atport.go create mode 100644 internal/device/worker_atport_test.go create mode 100644 internal/e911/artifact_boundary_test.go create mode 100644 internal/e911/availability.go create mode 100644 internal/e911/availability_test.go create mode 100644 internal/e911/coordinator.go create mode 100644 internal/e911/coordinator_test.go create mode 100644 internal/e911/trace.go create mode 100644 internal/e911/trace_test.go create mode 100644 internal/esim/apdu_coordinator.go create mode 100644 internal/esim/apdu_coordinator_test.go create mode 100644 internal/esim/channel.go create mode 100644 internal/esim/download_error.go create mode 100644 internal/esim/errors.go create mode 100644 internal/esim/euicc_info.go create mode 100644 internal/esim/manager.go create mode 100644 internal/esim/manager_test.go create mode 100644 internal/esim/mbim_apdu_transport.go create mode 100644 internal/esim/mbim_apdu_transport_test.go create mode 100644 internal/esim/pki/accredited.json create mode 100644 internal/esim/pki/ci.json create mode 100644 internal/esim/pki/pki.go create mode 100644 internal/esim/qmi_channel.go create mode 100644 internal/esim/qmi_channel_log_test.go create mode 100644 internal/esim/qmi_channel_test.go create mode 100644 internal/esim/qmi_uim_transport.go create mode 100644 internal/global/version.go create mode 100644 internal/mbim/dataconn.go create mode 100644 internal/mbim/dataconn_test.go create mode 100644 internal/mbim/healthprobe.go create mode 100644 internal/mbim/healthprobe_test.go create mode 100644 internal/mbim/manager.go create mode 100644 internal/mbim/manager_arbiter_test.go create mode 100644 internal/mbim/manager_capability_test.go create mode 100644 internal/mbim/manager_ef_test.go create mode 100644 internal/mbim/manager_providers_test.go create mode 100644 internal/mbim/manager_registration_test.go create mode 100644 internal/mbim/manager_test.go create mode 100644 internal/mbim/manager_uicc_probe_test.go create mode 100644 internal/mbim/manager_ussd_test.go create mode 100644 internal/mbim/netcfg_adapter.go create mode 100644 internal/mbim/post_switch.go create mode 100644 internal/mbim/post_switch_test.go create mode 100644 internal/mbim/recovery.go create mode 100644 internal/mbim/recovery_test.go create mode 100644 internal/mbim/testsupport.go create mode 100644 internal/modem/at_parse.go create mode 100644 internal/modem/at_parse_test.go create mode 100644 internal/modem/commands.go create mode 100644 internal/modem/commands_apdu_test.go create mode 100644 internal/modem/imei_probe.go create mode 100644 internal/modem/manager.go create mode 100644 internal/modem/manager_execute_at_test.go create mode 100644 internal/modem/manager_force_release_test.go create mode 100644 internal/modem/manager_pure_backend_test.go create mode 100644 internal/modem/manager_sms_storage_test.go create mode 100644 internal/modem/operator_name.go create mode 100644 internal/modem/operator_name_test.go create mode 100644 internal/modem/operator_selection.go create mode 100644 internal/modem/operator_selection_test.go create mode 100644 internal/modem/phone_number_parse_test.go create mode 100644 internal/modem/serial_at.go create mode 100644 internal/modem/sim_metadata.go create mode 100644 internal/modem/sim_metadata_test.go create mode 100644 internal/modem/spn.go create mode 100644 internal/modem/spn_test.go create mode 100644 internal/modem/urc_format.go create mode 100644 internal/netprobe/netprobe.go create mode 100644 internal/netprobe/netprobe_test.go create mode 100644 internal/notify/bark.go create mode 100644 internal/notify/channel.go create mode 100644 internal/notify/commands.go create mode 100644 internal/notify/email.go create mode 100644 internal/notify/feishu.go create mode 100644 internal/notify/feishu_linux_arm.go create mode 100644 internal/notify/manager.go create mode 100644 internal/notify/manager_test.go create mode 100644 internal/notify/pushplus.go create mode 100644 internal/notify/qq.go create mode 100644 internal/notify/qq_test.go create mode 100644 internal/notify/telegram.go create mode 100644 internal/notify/telegram_test.go create mode 100644 internal/notify/webhook.go create mode 100644 internal/notify/webhook_test.go create mode 100644 internal/proxy/server/http_proxy.go create mode 100644 internal/proxy/server/manager.go create mode 100644 internal/proxy/server/server.go create mode 100644 internal/proxy/server/server_bind_test.go create mode 100644 internal/proxy/server/stats.go create mode 100644 internal/proxy/traffic/qmi_wds.go create mode 100644 internal/proxy/traffic/realtime.go create mode 100644 internal/proxy/traffic/realtime_test.go create mode 100644 internal/proxy/traffic/sampler.go create mode 100644 internal/proxy/traffic/sampler_test.go create mode 100644 internal/qmi/client_options.go create mode 100644 internal/qmi/client_options_test.go create mode 100644 internal/qmi/control_device_holders_linux.go create mode 100644 internal/qmi/manager.go create mode 100644 internal/qmi/manager_apdu_lease_test.go create mode 100644 internal/qmi/manager_events_test.go create mode 100644 internal/qmi/manager_existing_connection_test.go create mode 100644 internal/qmi/manager_ipfamily_test.go create mode 100644 internal/qmi/manager_privateip_test.go create mode 100644 internal/qmi/manager_publicip_test.go create mode 100644 internal/qmi/manager_recovery_exhausted_test.go create mode 100644 internal/qmi/manager_transport_test.go create mode 100644 internal/sim/aka_provider.go create mode 100644 internal/sim/aka_provider_test.go create mode 100644 internal/sim/apdu.go create mode 100644 internal/sim/diag.go create mode 100644 internal/sim/factory.go create mode 100644 internal/sim/factory_test.go create mode 100644 internal/sim/types.go create mode 100644 internal/simaid/aid.go create mode 100644 internal/simaid/apdu.go create mode 100644 internal/simaid/dir.go create mode 100644 internal/simaid/select.go create mode 100644 internal/simaid/simaid_test.go create mode 100644 internal/simaid/tlv.go create mode 100644 internal/smsnotify/policy.go create mode 100644 internal/smsnotify/policy_test.go create mode 100644 internal/updater/updater.go create mode 100644 internal/upstreamproxy/country_table.go create mode 100644 internal/upstreamproxy/country_table_test.go create mode 100644 internal/upstreamproxy/probe.go create mode 100644 internal/upstreamproxy/probe_test.go create mode 100644 internal/vowifihost/adapter.go create mode 100644 internal/vowifihost/controller.go create mode 100644 internal/vowifihost/controller_test.go create mode 100644 internal/vowifihost/lifecycle_api.go create mode 100644 internal/vowifihost/lifecycle_run.go create mode 100644 internal/vowifihost/manager.go create mode 100644 internal/vowifihost/manager_lifecycle_test.go create mode 100644 internal/vowifihost/reconcile.go create mode 100644 internal/vowifihost/reconcile_test.go create mode 100644 internal/vowifihost/recover_state.go create mode 100644 internal/vowifihost/recover_state_test.go create mode 100644 internal/vowifihost/runtime_access.go create mode 100644 internal/vowifihost/runtime_access_test.go create mode 100644 internal/vowifihost/runtime_sim_select_test.go create mode 100644 internal/vowifihost/runtime_start.go create mode 100644 internal/vowifihost/runtime_start_test.go create mode 100644 internal/vowifihost/start.go create mode 100644 internal/vowifihost/start_test.go create mode 100644 internal/vowifihost/state_pubsub.go create mode 100644 internal/vowifihost/state_pubsub_test.go create mode 100644 internal/vowifihost/store.go create mode 100644 internal/vowifihost/teardown.go create mode 100644 internal/vowifihost/teardown_test.go create mode 100644 internal/web/fs.go create mode 100644 internal/websheet/bridge.js create mode 100644 internal/websheet/websheet.go create mode 100644 internal/websheet/websheet_test.go create mode 100644 packaging/openwrt/vohive/files/config.yaml create mode 100644 packaging/openwrt/vohive/files/vohive.init create mode 100644 pkg/logger/log_broadcaster.go create mode 100644 pkg/logger/logger.go create mode 100644 pkg/logger/run_mode.go create mode 100644 pkg/logger/slog_adapter.go create mode 100644 pkg/mbim/auth.go create mode 100644 pkg/mbim/auth_test.go create mode 100644 pkg/mbim/basicconnect.go create mode 100644 pkg/mbim/basicconnect_test.go create mode 100644 pkg/mbim/capability.go create mode 100644 pkg/mbim/capability_test.go create mode 100644 pkg/mbim/connect.go create mode 100644 pkg/mbim/connect_indication_test.go create mode 100644 pkg/mbim/connect_test.go create mode 100644 pkg/mbim/databuffer.go create mode 100644 pkg/mbim/databuffer_test.go create mode 100644 pkg/mbim/device.go create mode 100644 pkg/mbim/device_test.go create mode 100644 pkg/mbim/deviceservices.go create mode 100644 pkg/mbim/deviceservices_test.go create mode 100644 pkg/mbim/fragment.go create mode 100644 pkg/mbim/fragment_test.go create mode 100644 pkg/mbim/ipconfig.go create mode 100644 pkg/mbim/ipconfig_test.go create mode 100644 pkg/mbim/message.go create mode 100644 pkg/mbim/message_test.go create mode 100644 pkg/mbim/packet.go create mode 100644 pkg/mbim/packet_test.go create mode 100644 pkg/mbim/protocol.go create mode 100644 pkg/mbim/protocol_test.go create mode 100644 pkg/mbim/providers.go create mode 100644 pkg/mbim/providers_test.go create mode 100644 pkg/mbim/radio.go create mode 100644 pkg/mbim/radio_test.go create mode 100644 pkg/mbim/register.go create mode 100644 pkg/mbim/register_test.go create mode 100644 pkg/mbim/reset.go create mode 100644 pkg/mbim/reset_test.go create mode 100644 pkg/mbim/signal.go create mode 100644 pkg/mbim/signal_test.go create mode 100644 pkg/mbim/slotinfo.go create mode 100644 pkg/mbim/slotinfo_test.go create mode 100644 pkg/mbim/sms.go create mode 100644 pkg/mbim/sms_test.go create mode 100644 pkg/mbim/snapshot.go create mode 100644 pkg/mbim/snapshot_test.go create mode 100644 pkg/mbim/subscribe.go create mode 100644 pkg/mbim/subscribe_test.go create mode 100644 pkg/mbim/subscriber.go create mode 100644 pkg/mbim/subscriber_test.go create mode 100644 pkg/mbim/testsupport.go create mode 100644 pkg/mbim/transport.go create mode 100644 pkg/mbim/transport_proxy.go create mode 100644 pkg/mbim/transport_test.go create mode 100644 pkg/mbim/uicc.go create mode 100644 pkg/mbim/uicc_fileaccess.go create mode 100644 pkg/mbim/uicc_fileaccess_test.go create mode 100644 pkg/mbim/uicc_qmi.go create mode 100644 pkg/mbim/uicc_qmi_power.go create mode 100644 pkg/mbim/uicc_qmi_power_test.go create mode 100644 pkg/mbim/uicc_qmi_read.go create mode 100644 pkg/mbim/uicc_qmi_read_test.go create mode 100644 pkg/mbim/uicc_test.go create mode 100644 pkg/mbim/ussd.go create mode 100644 pkg/mbim/ussd_test.go create mode 100644 pkg/mbim/version.go create mode 100644 pkg/mbim/version_test.go create mode 100644 pkg/smscodec/binary_classifier.go create mode 100644 pkg/smscodec/binary_classifier_test.go create mode 100644 pkg/smscodec/pdu.go create mode 100644 pkg/smscodec/pdu_encoding_test.go create mode 100644 pkg/smscodec/pdu_rp_test.go create mode 100644 pkg/smscodec/pdu_trim.go create mode 100644 pkg/smscodec/pdu_trim_test.go create mode 100644 pkg/smscodec/reassembler.go create mode 100644 pkg/smscodec/reassembler_test.go create mode 100644 pkg/smscodec/wbxml_omacp.go create mode 100644 pkg/smscodec/wbxml_omacp_test.go create mode 100644 pkg/smsutil/compat.go create mode 100644 pkg/smsutil/compat_test.go create mode 100644 third_party/netlink/.github/scripts/modprobe.sh create mode 100644 third_party/netlink/.github/workflows/main.yml create mode 100644 third_party/netlink/.gitignore create mode 100644 third_party/netlink/CHANGELOG.md create mode 100644 third_party/netlink/LICENSE create mode 100644 third_party/netlink/Makefile create mode 100644 third_party/netlink/README.md create mode 100644 third_party/netlink/addr.go create mode 100644 third_party/netlink/addr_linux.go create mode 100644 third_party/netlink/addr_test.go create mode 100644 third_party/netlink/bpf_linux.go create mode 100644 third_party/netlink/bridge_linux.go create mode 100644 third_party/netlink/bridge_linux_test.go create mode 100644 third_party/netlink/chain.go create mode 100644 third_party/netlink/chain_linux.go create mode 100644 third_party/netlink/chain_test.go create mode 100644 third_party/netlink/class.go create mode 100644 third_party/netlink/class_linux.go create mode 100644 third_party/netlink/class_test.go create mode 100644 third_party/netlink/cmd/ipset-test/main.go create mode 100644 third_party/netlink/conntrack_linux.go create mode 100644 third_party/netlink/conntrack_test.go create mode 100644 third_party/netlink/conntrack_unspecified.go create mode 100644 third_party/netlink/devlink.go create mode 100644 third_party/netlink/devlink_linux.go create mode 100644 third_party/netlink/devlink_test.go create mode 100644 third_party/netlink/devlink_unspecified.go create mode 100644 third_party/netlink/filter.go create mode 100644 third_party/netlink/filter_linux.go create mode 100644 third_party/netlink/filter_test.go create mode 100644 third_party/netlink/fou.go create mode 100644 third_party/netlink/fou_linux.go create mode 100644 third_party/netlink/fou_test.go create mode 100644 third_party/netlink/fou_unspecified.go create mode 100644 third_party/netlink/genetlink_linux.go create mode 100644 third_party/netlink/genetlink_unspecified.go create mode 100644 third_party/netlink/go.mod create mode 100644 third_party/netlink/go.sum create mode 100644 third_party/netlink/gtp_linux.go create mode 100644 third_party/netlink/gtp_test.go create mode 100644 third_party/netlink/handle_linux.go create mode 100644 third_party/netlink/handle_linux_test.go create mode 100644 third_party/netlink/handle_test.go create mode 100644 third_party/netlink/handle_unspecified.go create mode 100644 third_party/netlink/inet_diag.go create mode 100644 third_party/netlink/ioctl_linux.go create mode 100644 third_party/netlink/ipset_linux.go create mode 100644 third_party/netlink/ipset_linux_test.go create mode 100644 third_party/netlink/link.go create mode 100644 third_party/netlink/link_linux.go create mode 100644 third_party/netlink/link_test.go create mode 100644 third_party/netlink/link_tuntap_linux.go create mode 100644 third_party/netlink/neigh.go create mode 100644 third_party/netlink/neigh_linux.go create mode 100644 third_party/netlink/neigh_test.go create mode 100644 third_party/netlink/netlink.go create mode 100644 third_party/netlink/netlink_linux.go create mode 100644 third_party/netlink/netlink_test.go create mode 100644 third_party/netlink/netlink_unspecified.go create mode 100644 third_party/netlink/netns_linux.go create mode 100644 third_party/netlink/netns_test.go create mode 100644 third_party/netlink/netns_unspecified.go create mode 100644 third_party/netlink/nexthop.go create mode 100644 third_party/netlink/nexthop_linux.go create mode 100644 third_party/netlink/nexthop_test.go create mode 100644 third_party/netlink/nl/addr_linux.go create mode 100644 third_party/netlink/nl/addr_linux_test.go create mode 100644 third_party/netlink/nl/bridge_linux.go create mode 100644 third_party/netlink/nl/bridge_linux_test.go create mode 100644 third_party/netlink/nl/conntrack_linux.go create mode 100644 third_party/netlink/nl/devlink_linux.go create mode 100644 third_party/netlink/nl/genetlink_linux.go create mode 100644 third_party/netlink/nl/ip6tnl_linux.go create mode 100644 third_party/netlink/nl/ipset_linux.go create mode 100644 third_party/netlink/nl/link_linux.go create mode 100644 third_party/netlink/nl/link_linux_test.go create mode 100644 third_party/netlink/nl/lwt_linux.go create mode 100644 third_party/netlink/nl/mpls_linux.go create mode 100644 third_party/netlink/nl/nexthop_linux.go create mode 100644 third_party/netlink/nl/nl_linux.go create mode 100644 third_party/netlink/nl/nl_linux_test.go create mode 100644 third_party/netlink/nl/nl_unspecified.go create mode 100644 third_party/netlink/nl/parse_attr_linux.go create mode 100644 third_party/netlink/nl/rdma_link_linux.go create mode 100644 third_party/netlink/nl/route_linux.go create mode 100644 third_party/netlink/nl/route_linux_test.go create mode 100644 third_party/netlink/nl/seg6_linux.go create mode 100644 third_party/netlink/nl/seg6local_linux.go create mode 100644 third_party/netlink/nl/syscall.go create mode 100644 third_party/netlink/nl/tc_linux.go create mode 100644 third_party/netlink/nl/tc_linux_test.go create mode 100644 third_party/netlink/nl/vdpa_linux.go create mode 100644 third_party/netlink/nl/xfrm_linux.go create mode 100644 third_party/netlink/nl/xfrm_linux_test.go create mode 100644 third_party/netlink/nl/xfrm_monitor_linux.go create mode 100644 third_party/netlink/nl/xfrm_monitor_linux_test.go create mode 100644 third_party/netlink/nl/xfrm_policy_linux.go create mode 100644 third_party/netlink/nl/xfrm_policy_linux_test.go create mode 100644 third_party/netlink/nl/xfrm_state_linux.go create mode 100644 third_party/netlink/nl/xfrm_state_linux_test.go create mode 100644 third_party/netlink/order.go create mode 100644 third_party/netlink/proc_event_linux.go create mode 100644 third_party/netlink/proc_event_test.go create mode 100644 third_party/netlink/protinfo.go create mode 100644 third_party/netlink/protinfo_linux.go create mode 100644 third_party/netlink/protinfo_test.go create mode 100644 third_party/netlink/qdisc.go create mode 100644 third_party/netlink/qdisc_linux.go create mode 100644 third_party/netlink/qdisc_test.go create mode 100644 third_party/netlink/rdma_link_linux.go create mode 100644 third_party/netlink/rdma_link_test.go create mode 100644 third_party/netlink/route.go create mode 100644 third_party/netlink/route_linux.go create mode 100644 third_party/netlink/route_test.go create mode 100644 third_party/netlink/route_unspecified.go create mode 100644 third_party/netlink/rule.go create mode 100644 third_party/netlink/rule_linux.go create mode 100644 third_party/netlink/rule_nonlinux.go create mode 100644 third_party/netlink/rule_test.go create mode 100644 third_party/netlink/socket.go create mode 100644 third_party/netlink/socket_linux.go create mode 100644 third_party/netlink/socket_linux_test.go create mode 100644 third_party/netlink/socket_test.go create mode 100644 third_party/netlink/socket_unspecified.go create mode 100644 third_party/netlink/socket_xdp_linux.go create mode 100644 third_party/netlink/socket_xdp_linux_test.go create mode 100644 third_party/netlink/socket_xdp_unspecified.go create mode 100644 third_party/netlink/tcp.go create mode 100644 third_party/netlink/tcp_linux.go create mode 100644 third_party/netlink/tcp_linux_test.go create mode 100644 third_party/netlink/testdata/ipset_list_result create mode 100644 third_party/netlink/testdata/ipset_protocol_result create mode 100644 third_party/netlink/unix_diag.go create mode 100644 third_party/netlink/vdpa_linux.go create mode 100644 third_party/netlink/vdpa_linux_test.go create mode 100644 third_party/netlink/virtio.go create mode 100644 third_party/netlink/xdp_diag.go create mode 100644 third_party/netlink/xdp_linux.go create mode 100644 third_party/netlink/xfrm_linux.go create mode 100644 third_party/netlink/xfrm_monitor_linux.go create mode 100644 third_party/netlink/xfrm_monitor_linux_test.go create mode 100644 third_party/netlink/xfrm_policy_linux.go create mode 100644 third_party/netlink/xfrm_policy_linux_test.go create mode 100644 third_party/netlink/xfrm_state_linux.go create mode 100644 third_party/netlink/xfrm_state_linux_test.go create mode 100644 third_party/netlink/xfrm_unspecified.go create mode 100644 third_party/qqbot/LICENSE create mode 100644 third_party/qqbot/README.md create mode 100644 third_party/qqbot/app.go create mode 100644 third_party/qqbot/app_test.go create mode 100644 third_party/qqbot/go.mod create mode 100644 third_party/qqbot/go.sum create mode 100644 third_party/qqbot/handler.go create mode 100644 third_party/qqbot/internal/auth/source.go create mode 100644 third_party/qqbot/internal/auth/source_test.go create mode 100644 third_party/qqbot/internal/dispatch/engine.go create mode 100644 third_party/qqbot/internal/dispatch/engine_test.go create mode 100644 third_party/qqbot/internal/dispatch/store.go create mode 100644 third_party/qqbot/internal/rest/client.go create mode 100644 third_party/qqbot/internal/rest/client_test.go create mode 100644 third_party/qqbot/internal/stream/pump.go create mode 100644 third_party/qqbot/model.go create mode 100644 third_party/qqbot/settings.go create mode 100644 third_party/quectel-qmi-go/LICENSE create mode 100755 third_party/quectel-qmi-go/README.md create mode 100755 third_party/quectel-qmi-go/cmd/cm/main.go create mode 100755 third_party/quectel-qmi-go/cmd/dms-tool/main.go create mode 100755 third_party/quectel-qmi-go/cmd/info-tool/main.go create mode 100755 third_party/quectel-qmi-go/cmd/nas-tool/main.go create mode 100755 third_party/quectel-qmi-go/cmd/sms-tool/main.go create mode 100755 third_party/quectel-qmi-go/cmd/wda-tool/main.go create mode 100755 third_party/quectel-qmi-go/cmd/wds-tool/main.go create mode 100755 third_party/quectel-qmi-go/go.mod create mode 100755 third_party/quectel-qmi-go/go.sum create mode 100755 third_party/quectel-qmi-go/pkg/device/discovery.go create mode 100755 third_party/quectel-qmi-go/pkg/device/discovery_static_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/allocate_services_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/callbacks.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/callbacks_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/cleanup_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/core_ready_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/device.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/device_query.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/existing_data_cleanup_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/health_check_jitter_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/indication_log_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/logger.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/manager.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/nas_indication_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/pool.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/raw_sms_decode_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/raw_sms_event_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/recovery_exhausted_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/service_recovery.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/service_recovery_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/sms_send_encoding_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/sms_trim.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/sms_trim_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/smsc.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/smsc_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/snapshot.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/uim_apdu_context_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/uim_post_switch_reload_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/uim_provisioning.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/uim_provisioning_test.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/uim_readiness.go create mode 100644 third_party/quectel-qmi-go/pkg/manager/uim_readiness_test.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/uim_recovery.go create mode 100755 third_party/quectel-qmi-go/pkg/manager/voice_test.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/configurator.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/darwin.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/factory_darwin.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/factory_linux.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/factory_windows.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/linux.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/netcfg.go create mode 100755 third_party/quectel-qmi-go/pkg/netcfg/windows.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/client.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/client_indication_test.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/ctl.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/ctl_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/dms.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/dms_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/errors.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/errors_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/frame.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/ims.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/ims_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/imsa.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/imsdcm_compat_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/imsp.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/mapping_regression_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/nas.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/nas_test.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/proxy_client_test.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/proxy_transport_linux.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/proxy_transport_linux_test.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/proxy_transport_unsupported.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/test_helpers_test.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/transport.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/uim.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/uim_feature_test.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/uim_metadata_test.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/uim_spn_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/uim_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/voice.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/voice_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/wda.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/wds.go create mode 100644 third_party/quectel-qmi-go/pkg/qmi/wds_stop_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/wds_test.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/wms.go create mode 100755 third_party/quectel-qmi-go/pkg/qmi/wms_test.go create mode 100644 third_party/vowifi-go/.github/workflows/ci.yml create mode 100644 third_party/vowifi-go/AGENTS.md create mode 100644 third_party/vowifi-go/LICENSE create mode 100644 third_party/vowifi-go/Makefile create mode 100644 third_party/vowifi-go/README.md create mode 100644 third_party/vowifi-go/README.zh-CN.md create mode 100644 third_party/vowifi-go/docs/ARCHITECTURE.md create mode 100644 third_party/vowifi-go/docs/DEVELOPMENT.md create mode 100644 third_party/vowifi-go/docs/DISCLAIMER.md create mode 100644 third_party/vowifi-go/docs/DISCLAIMER.zh-CN.md create mode 100644 third_party/vowifi-go/docs/FEATURES.md create mode 100644 third_party/vowifi-go/engine/sim/sim.go create mode 100644 third_party/vowifi-go/engine/swu/eap_reauth.go create mode 100644 third_party/vowifi-go/engine/swu/eapaka/crypto.go create mode 100644 third_party/vowifi-go/engine/swu/eapaka/crypto_test.go create mode 100644 third_party/vowifi-go/engine/swu/eapaka/eapaka.go create mode 100644 third_party/vowifi-go/engine/swu/eapaka/eapaka_test.go create mode 100644 third_party/vowifi-go/engine/swu/esp/esp.go create mode 100644 third_party/vowifi-go/engine/swu/esp/esp_test.go create mode 100644 third_party/vowifi-go/engine/swu/ike_control.go create mode 100644 third_party/vowifi-go/engine/swu/ike_control_test.go create mode 100644 third_party/vowifi-go/engine/swu/ike_tunnel_manager.go create mode 100644 third_party/vowifi-go/engine/swu/ike_tunnel_manager_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/auth.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/auth_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/childsa.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/childsa_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/create_child.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/create_child_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/crypto.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/crypto_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/informational.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/informational_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/init.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/init_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/keys.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/payloads.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/payloads_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/sa.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/sa_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/session_payloads.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/session_payloads_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/sk.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/sk_test.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/types.go create mode 100644 third_party/vowifi-go/engine/swu/ikev2/types_test.go create mode 100644 third_party/vowifi-go/engine/swu/packet_pump.go create mode 100644 third_party/vowifi-go/engine/swu/packet_pump_test.go create mode 100644 third_party/vowifi-go/engine/swu/packet_session.go create mode 100644 third_party/vowifi-go/engine/swu/packet_session_test.go create mode 100644 third_party/vowifi-go/engine/swu/swu.go create mode 100644 third_party/vowifi-go/engine/swu/swu_test.go create mode 100644 third_party/vowifi-go/engine/swu/tun_linux.go create mode 100644 third_party/vowifi-go/engine/swu/tun_linux_test.go create mode 100644 third_party/vowifi-go/engine/swu/tun_routing.go create mode 100644 third_party/vowifi-go/engine/swu/tun_routing_test.go create mode 100644 third_party/vowifi-go/engine/swu/tun_tunnel_manager.go create mode 100644 third_party/vowifi-go/engine/swu/tun_tunnel_manager_test.go create mode 100644 third_party/vowifi-go/engine/swu/tun_unsupported.go create mode 100644 third_party/vowifi-go/engine/swu/udp_esp_transport.go create mode 100644 third_party/vowifi-go/engine/swu/udp_esp_transport_test.go create mode 100644 third_party/vowifi-go/engine/swu/xfrm.go create mode 100644 third_party/vowifi-go/engine/swu/xfrm_test.go create mode 100644 third_party/vowifi-go/go.mod create mode 100644 third_party/vowifi-go/go.sum create mode 100644 third_party/vowifi-go/runtimehost/carrier/carrier.go create mode 100644 third_party/vowifi-go/runtimehost/carrier/carrier_test.go create mode 100644 third_party/vowifi-go/runtimehost/e911/e911.go create mode 100644 third_party/vowifi-go/runtimehost/e911/e911_test.go create mode 100644 third_party/vowifi-go/runtimehost/eventhost/eventhost.go create mode 100644 third_party/vowifi-go/runtimehost/identity/identity.go create mode 100644 third_party/vowifi-go/runtimehost/identity/identity_test.go create mode 100644 third_party/vowifi-go/runtimehost/imsregistrar.go create mode 100644 third_party/vowifi-go/runtimehost/imsregistrar_test.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ims_inbound_sms.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ims_sms.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ims_sms_test.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ims_ussd.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ims_ussd_inbound.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ims_ussd_test.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/messaging.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/messaging_test.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/sms_pdu.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/sms_pdu_test.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ussd_xml.go create mode 100644 third_party/vowifi-go/runtimehost/messaging/ussd_xml_test.go create mode 100644 third_party/vowifi-go/runtimehost/simauth/aka.go create mode 100644 third_party/vowifi-go/runtimehost/simauth/apdu.go create mode 100644 third_party/vowifi-go/runtimehost/simauth/apdu_test.go create mode 100644 third_party/vowifi-go/runtimehost/simauth/tlv.go create mode 100644 third_party/vowifi-go/runtimehost/types.go create mode 100644 third_party/vowifi-go/runtimehost/types_test.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/dialog.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/security.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/sip_resolver.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/sip_resolver_test.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/voiceclient.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/voiceclient_test.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/wire_flow.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/wire_flow_test.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/wire_sip_transport.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/wire_transport.go create mode 100644 third_party/vowifi-go/runtimehost/voiceclient/wire_transport_test.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/ims_agent.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/ims_agent_test.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/ims_inbound_agent.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/ims_inbound_agent_test.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/ims_inbound_wire.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/ims_inbound_wire_test.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/ims_message.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/rtcp_feedback.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/rtp_relay.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/rtp_relay_test.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/sdp_rewrite.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/sdp_rewrite_test.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/srtp_media.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/srtp_media_test.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/voicehost.go create mode 100644 third_party/vowifi-go/runtimehost/voicehost/voicehost_test.go create mode 100755 third_party/vowifi-go/scripts/ci.sh create mode 100644 web/.gitignore create mode 100644 web/README.md create mode 100644 web/eslint.config.js create mode 100644 web/go.mod create mode 100644 web/index.html create mode 100644 web/package-lock.json create mode 100644 web/package.json create mode 100644 web/postcss.config.js create mode 100644 web/public/favicon.svg create mode 100644 web/public/vite.svg create mode 100644 web/src/App.vue create mode 100644 web/src/assets/vue.svg create mode 100644 web/src/auto-imports.d.ts create mode 100644 web/src/components.d.ts create mode 100644 web/src/components/CardPolicyPanel.vue create mode 100644 web/src/components/CarrierWebsheetDialog.vue create mode 100644 web/src/components/DebugPanel.vue create mode 100644 web/src/components/DeviceAddDialog.vue create mode 100644 web/src/components/DeviceAtTab.vue create mode 100644 web/src/components/DeviceCard.vue create mode 100644 web/src/components/DeviceConfigTab.vue create mode 100644 web/src/components/DeviceDetailHeader.vue create mode 100644 web/src/components/DeviceDetailLoading.vue create mode 100644 web/src/components/DeviceEsimTab.vue create mode 100644 web/src/components/DeviceListPanel.vue create mode 100644 web/src/components/DeviceOverviewTab.vue create mode 100644 web/src/components/DeviceUssdTab.vue create mode 100644 web/src/components/EmptyState.vue create mode 100644 web/src/components/ErrorBoundary.vue create mode 100644 web/src/components/ErrorState.vue create mode 100644 web/src/components/EsimCardPolicyInline.vue create mode 100644 web/src/components/FieldRow.vue create mode 100644 web/src/components/HelloWorld.vue create mode 100644 web/src/components/ListSkeleton.vue create mode 100644 web/src/components/LoadingScreen.vue create mode 100644 web/src/components/OperatorSelectionDialog.vue create mode 100644 web/src/components/PageHeader.vue create mode 100644 web/src/components/RefreshButton.vue create mode 100644 web/src/components/StatusLight.vue create mode 100644 web/src/components/SwitchDark.vue create mode 100644 web/src/components/TrafficAnalysisPanel.vue create mode 100644 web/src/components/deviceEsimNotifications.ts create mode 100644 web/src/components/deviceEsimOperationNotice.ts create mode 100644 web/src/components/deviceEsimOptimistic.ts create mode 100644 web/src/components/deviceEsimOverviewRefresh.ts create mode 100644 web/src/components/deviceOverviewActiveEsim.ts create mode 100644 web/src/components/statusLight.ts create mode 100644 web/src/composables/useCardPolicyToggles.ts create mode 100644 web/src/composables/useCardPolicyToggles.typecheck.ts create mode 100644 web/src/composables/useEventStream.ts create mode 100644 web/src/composables/usePollingScheduler.ts create mode 100644 web/src/composables/useSensitiveVisibility.ts create mode 100644 web/src/composables/useSensitiveVisibility.typecheck.ts create mode 100644 web/src/composables/useSmartPoll.ts create mode 100644 web/src/constants/atTemplates.ts create mode 100644 web/src/debug/collector.ts create mode 100644 web/src/disclaimer.ts create mode 100644 web/src/env.d.ts create mode 100644 web/src/layouts/AuthenticatedShell.vue create mode 100644 web/src/layouts/UnauthenticatedShell.vue create mode 100644 web/src/main.ts create mode 100644 web/src/router/index.ts create mode 100644 web/src/services/cards.ts create mode 100644 web/src/services/dashboard.ts create mode 100644 web/src/services/devices.ts create mode 100644 web/src/services/http.ts create mode 100644 web/src/services/logs.ts create mode 100644 web/src/services/proxy.ts create mode 100644 web/src/services/sms.ts create mode 100644 web/src/services/system.ts create mode 100644 web/src/services/traffic.ts create mode 100644 web/src/services/upstream-proxy.ts create mode 100644 web/src/stores/auth.ts create mode 100644 web/src/stores/dashboard.ts create mode 100644 web/src/stores/devices.ts create mode 100644 web/src/stores/logs.ts create mode 100644 web/src/stores/proxy.ts create mode 100644 web/src/stores/settings.ts create mode 100644 web/src/stores/sms.ts create mode 100644 web/src/stores/upstream-proxy.ts create mode 100644 web/src/style.css create mode 100644 web/src/types/api.ts create mode 100644 web/src/types/domain.ts create mode 100644 web/src/types/view-model.ts create mode 100644 web/src/utils/clipboard.ts create mode 100644 web/src/utils/deviceBackend.ts create mode 100644 web/src/utils/deviceLifecycle.ts create mode 100644 web/src/utils/mcc-mnc.ts create mode 100644 web/src/utils/upstreamProxyAddress.ts create mode 100644 web/src/views/Dashboard.vue create mode 100644 web/src/views/Devices.vue create mode 100644 web/src/views/Login.vue create mode 100644 web/src/views/Logs.vue create mode 100644 web/src/views/Proxy.vue create mode 100644 web/src/views/Settings.vue create mode 100644 web/src/views/Sms.vue create mode 100644 web/tailwind.config.cjs create mode 100644 web/tests/deviceConfigTabAtPort.test.ts create mode 100644 web/tsconfig.json create mode 100644 web/vite.config.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..fa7f2c64 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,21 @@ +.git +.github +.gitignore +go.work + +**/*.log +**/*.db +**/*.sqlite +**/*.sqlite3 + +logs +data +tmp +dist + +web/node_modules +web/dist + +internal/web/dist + +**/.DS_Store diff --git a/.github/workflows/binary-release.yml b/.github/workflows/binary-release.yml new file mode 100644 index 00000000..09058d18 --- /dev/null +++ b/.github/workflows/binary-release.yml @@ -0,0 +1,181 @@ +name: Build Release Binaries + +on: + push: + tags: + - 'v*' + workflow_dispatch: + inputs: + version: + description: 'Version string used when manually triggered' + required: false + default: 'dev' + enable_upx: + description: 'Enable UPX compression (true/false)' + required: false + default: 'false' + +permissions: + contents: write + +concurrency: + group: binary-release-${{ github.ref }} + cancel-in-progress: false + +jobs: + frontend: + name: Build frontend assets + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + cache-dependency-path: web/package-lock.json + + - name: Build frontend assets + shell: bash + run: | + npm ci --prefix web + npm run build --prefix web + + - name: Upload frontend dist + uses: actions/upload-artifact@v4 + with: + name: web-dist + path: web/dist + if-no-files-found: error + retention-days: 1 + + build: + name: Build ${{ matrix.artifact_arch }} + runs-on: ubuntu-latest + needs: frontend + strategy: + fail-fast: false + matrix: + include: + - goarch: amd64 + goarm: '' + artifact_arch: amd64 + - goarch: arm64 + goarm: '' + artifact_arch: arm64 + - goarch: arm + goarm: '7' + artifact_arch: armv7 + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + + - name: Prepare build vars + id: vars + shell: bash + run: | + if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then + VERSION="${GITHUB_REF_NAME}" + else + VERSION="${{ github.event.inputs.version || 'dev' }}" + fi + BUILDTIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" + ENABLE_UPX_RAW="${{ github.event.inputs.enable_upx || 'false' }}" + case "${ENABLE_UPX_RAW}" in + true|1|yes|on) ENABLE_UPX=1 ;; + *) ENABLE_UPX=0 ;; + esac + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + echo "buildtime=${BUILDTIME}" >> "${GITHUB_OUTPUT}" + echo "enable_upx=${ENABLE_UPX}" >> "${GITHUB_OUTPUT}" + + - name: Download frontend dist + uses: actions/download-artifact@v4 + with: + name: web-dist + path: web/dist + + - name: Sync frontend dist for embed + shell: bash + run: | + rm -rf internal/web/dist + mkdir -p internal/web + cp -R web/dist internal/web/dist + + - name: Build binary + shell: bash + run: | + mkdir -p dist + GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=${{ matrix.goarch }} GOARM=${{ matrix.goarm }} \ + go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" \ + -ldflags "-s -w -X 'github.com/iniwex5/vohive/internal/global.Version=${{ steps.vars.outputs.version }}' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=${{ steps.vars.outputs.buildtime }}'" \ + -o dist/vo-hive ./cmd/vohive + + - name: Install UPX + if: ${{ steps.vars.outputs.enable_upx == '1' }} + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y upx-ucl || sudo apt-get install -y upx + + - name: Compress with UPX + if: ${{ steps.vars.outputs.enable_upx == '1' }} + shell: bash + run: | + upx --best --lzma dist/vo-hive || upx -9 dist/vo-hive + + - name: Package artifact + shell: bash + run: | + OUT="vohive_${{ steps.vars.outputs.version }}_linux_${{ matrix.artifact_arch }}" + mkdir -p out + cp dist/vo-hive "out/${OUT}" + sha256sum "out/${OUT}" > "out/${OUT}.sha256" + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: binaries-${{ matrix.artifact_arch }} + path: out/* + retention-days: 3 + + release: + name: Publish release assets + runs-on: ubuntu-latest + needs: build + if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v') + steps: + - name: Prepare release vars + id: release_vars + shell: bash + run: | + if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then + RELEASE_VERSION="${GITHUB_REF_NAME}" + else + RELEASE_VERSION="${{ github.event.inputs.version || 'dev' }}" + fi + echo "release_version=${RELEASE_VERSION}" >> "${GITHUB_OUTPUT}" + + - name: Download all artifacts + uses: actions/download-artifact@v4 + with: + pattern: binaries-* + merge-multiple: true + path: dist + + - name: Publish to this GitHub Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.release_vars.outputs.release_version }} + files: dist/* + fail_on_unmatched_files: true + overwrite_files: true diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml new file mode 100644 index 00000000..8c0680af --- /dev/null +++ b/.github/workflows/docker-build.yml @@ -0,0 +1,74 @@ +name: docker-build + +on: + workflow_dispatch: + inputs: + platforms: + description: build platforms + required: false + default: linux/amd64,linux/arm64 + push: + description: push image + required: false + default: "false" + enable_upx: + description: enable UPX compression (true/false) + required: false + default: "false" + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v4 + + - uses: docker/setup-qemu-action@v3 + if: ${{ contains(inputs.platforms, 'arm') || contains(inputs.platforms, 'ppc') || contains(inputs.platforms, 's390') || contains(inputs.platforms, 'riscv') }} + with: + platforms: all + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + if: ${{ inputs.push == 'true' }} + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Prepare build args + id: vars + shell: bash + run: | + VERSION="dev-${GITHUB_SHA::7}" + BUILDTIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" + REVISION="${GITHUB_SHA}" + ENABLE_UPX_RAW="${{ inputs.enable_upx }}" + case "${ENABLE_UPX_RAW}" in + false|0|no|off) ENABLE_UPX=0 ;; + *) ENABLE_UPX=1 ;; + esac + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + echo "buildtime=${BUILDTIME}" >> "${GITHUB_OUTPUT}" + echo "revision=${REVISION}" >> "${GITHUB_OUTPUT}" + echo "enable_upx=${ENABLE_UPX}" >> "${GITHUB_OUTPUT}" + + - uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile.github + platforms: ${{ inputs.platforms }} + push: ${{ inputs.push == 'true' }} + tags: ghcr.io/${{ github.repository }}/vohive:dev + provenance: false + sbom: false + cache-from: type=gha + cache-to: type=gha,mode=max + build-args: | + VERSION=${{ steps.vars.outputs.version }} + BUILDTIME=${{ steps.vars.outputs.buildtime }} + REVISION=${{ steps.vars.outputs.revision }} + ENABLE_UPX=${{ steps.vars.outputs.enable_upx }} diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml new file mode 100644 index 00000000..6f57f0ff --- /dev/null +++ b/.github/workflows/docker-publish.yml @@ -0,0 +1,88 @@ +name: Build and Push Docker Image + +on: + push: + tags: + - 'v*' + workflow_dispatch: + inputs: + enable_upx: + description: enable UPX compression (true/false) + required: false + default: "false" + +env: + DOCKER_IMAGE: skyhotspur/vohive + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to DockerHub + if: github.event_name != 'pull_request' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Extract metadata (tags, labels) + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.DOCKER_IMAGE }} + tags: | + # 语义化精确版本标签 (例如 v1.0.0 会被转换为 1.0.0) + type=semver,pattern={{version}},enable=${{ startsWith(github.ref, 'refs/tags/v') }} + # 手动触发时只推 sha 标签,避免覆盖 latest + type=sha,prefix=sha-,format=short,enable=${{ github.event_name == 'workflow_dispatch' }} + + - name: Prepare build args + id: vars + shell: bash + run: | + if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then + VERSION="${GITHUB_REF_NAME}" + else + VERSION="sha-${GITHUB_SHA::7}" + fi + BUILDTIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" + REVISION="${GITHUB_SHA}" + if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then + ENABLE_UPX_RAW="${{ github.event.inputs.enable_upx }}" + else + ENABLE_UPX_RAW="false" + fi + case "${ENABLE_UPX_RAW}" in + false|0|no|off) ENABLE_UPX=0 ;; + *) ENABLE_UPX=1 ;; + esac + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + echo "buildtime=${BUILDTIME}" >> "${GITHUB_OUTPUT}" + echo "revision=${REVISION}" >> "${GITHUB_OUTPUT}" + echo "enable_upx=${ENABLE_UPX}" >> "${GITHUB_OUTPUT}" + + - name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: ./Dockerfile.github + platforms: linux/amd64,linux/arm64 + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + build-args: | + VERSION=${{ steps.vars.outputs.version }} + BUILDTIME=${{ steps.vars.outputs.buildtime }} + REVISION=${{ steps.vars.outputs.revision }} + ENABLE_UPX=${{ steps.vars.outputs.enable_upx }} diff --git a/.github/workflows/web-ci.yml b/.github/workflows/web-ci.yml new file mode 100644 index 00000000..dc36503e --- /dev/null +++ b/.github/workflows/web-ci.yml @@ -0,0 +1,40 @@ +name: Web CI + +on: + pull_request: + paths: + - 'web/**' + - '.github/workflows/web-ci.yml' + push: + branches: + - main + paths: + - 'web/**' + - '.github/workflows/web-ci.yml' + workflow_dispatch: + +jobs: + web-check: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + cache-dependency-path: web/package-lock.json + + - name: Install dependencies + run: npm ci --prefix web + + - name: Lint + run: npm run lint --prefix web + + - name: Typecheck + run: npm run typecheck --prefix web + + - name: Build + run: npm run build --prefix web diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..cdc47f1d --- /dev/null +++ b/.gitignore @@ -0,0 +1,65 @@ +# 构建产物 +/vo-hive +/mbimprobe +*.exe +*.dll +*.so +*.dylib + +# 数据和日志目录 +/data/ +/logs/ +*.db +*.db-journal +*.log + +# 前端构建产物 (由 npm run build 生成) +/web/dist/ +/web/node_modules/ +/web-reader/dist/ +/web-reader/node_modules/ +/internal/web/dist/ +/dist/* +/raspberry-backups/ + +# IDE 和编辑器 +.idea/ +.vscode/ +.agent/ +.shared/ +*.swp +*.swo +*~ + +# 系统文件 +.DS_Store +Thumbs.db + +# 配置文件 (包含敏感信息) +/config/config.yaml +/config/*.yaml +!config/config.example.yaml + +# 测试覆盖率 +coverage.out +*.cover +*.coverprofile + +# 临时文件 +*.tmp +*.temp +.cache/ +/server +/reader +vohive.code-workspace +PushNotification.pdf +Quectel_LTE_Standard_UAC_应用指导_V1.0.pdf + +# macOS AppleDouble metadata +**/._* +.superpowers/* +.codex +.worktrees/ +Quectel_EC2xEG2xEG9xEM05_Series_AT_Commands_Manual_V2.2.pdf +Quectel_EC2xEG2xEG9xEM05_Series_QCFG_AT_Commands_Manual_V1.6.pdf +410sim自动激活脚本/* diff --git a/DOCKERHUB.md b/DOCKERHUB.md new file mode 100644 index 00000000..70e70275 --- /dev/null +++ b/DOCKERHUB.md @@ -0,0 +1,90 @@ +# VoHive Docker Hub 镜像 + +镜像地址:`skyhotspur/vohive` + +支持架构: + +- `linux/amd64` +- `linux/arm64` + +## 快速启动 + +```bash +mkdir -p vohive/{config,data,logs} +cd vohive +``` + +创建 `config/config.yaml`: + +```yaml +server: + port: 7575 + debug: false + +web: + username: admin + password: admin + +devices: [] + +proxy: + instances: [] + +vowifi: + enabled: false +``` + +创建 `docker-compose.yml`: + +```yaml +services: + vohive: + image: skyhotspur/vohive:${VOHIVE_TAG:-1.5.5} + container_name: vohive + restart: unless-stopped + network_mode: host + privileged: true + volumes: + - ./config:/app/config + - ./data:/app/data + - ./logs:/app/logs + - /dev:/dev + environment: + TZ: Asia/Shanghai + CONFIG_PATH: /app/config/config.yaml +``` + +启动: + +```bash +docker compose up -d +``` + +Web 入口:`http://YOUR_IP:7575` + +默认账号:`admin` / `admin` + +首次登录后请立即修改密码。 + +## 更新镜像 + +```bash +docker pull "skyhotspur/vohive:${VOHIVE_TAG:-1.5.5}" +docker compose up -d +``` + +应用内二进制热更新在这个源码整合构建中已禁用。Docker 部署请通过拉取新镜像升级。 + +## 配置说明 + +| 路径 | 说明 | +| --- | --- | +| `/app/config` | 配置文件目录 | +| `/app/data` | SQLite 数据与运行数据 | +| `/app/logs` | 日志目录 | + +容器默认时区为 `Asia/Shanghai`。Compose 文件也显式设置了同一时区,方便在不同运行方式下保持一致。 + +## 许可证提示 + +本仓库是源码整合树,不是单一 MIT 许可项目。根项目来自 PolyForm Noncommercial 1.0.0,`third_party/vowifi-go` 为 AGPL-3.0,其它第三方源码按各自许可证授权。发布公开二进制或 Docker 镜像前,请先确认组合分发的许可证义务。 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..3e14b0e5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,101 @@ +# GitHub Actions 多架构构建专用 Dockerfile + +# 构建阶段 1: 前端构建 (Frontend) +# 使用 --platform=$BUILDPLATFORM 强制在构建机本地架构(通常是amd64)运行 +# 避免在 arm64 构建时使用 QEMU 模拟,大幅提升速度且产物跨平台通用 +FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder +ARG BUILDPLATFORM +WORKDIR /app/web +COPY web/package*.json ./ +# 挂载 npm 缓存,加速依赖安装 +RUN --mount=type=cache,target=/root/.npm,id=npm-${BUILDPLATFORM},sharing=locked \ + npm ci +COPY web/ . +RUN npm run build + +# 构建阶段 2: 后端构建 (Backend) +FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine AS backend-builder +ARG BUILDPLATFORM +ARG VERSION=unknown +ARG BUILDTIME=unknown +ARG REVISION=unknown +ARG ENABLE_UPX=0 +WORKDIR /app + +ENV PATH="/usr/local/go/bin:${PATH}" +# 使用镜像内置的已修复 Go 工具链,避免构建时隐式下载工具链 +ENV GOTOOLCHAIN=local +ENV GOWORK=off + +# 安装构建依赖 +RUN apk add --no-cache git + +# 复制 go mod 文件 +COPY go.mod go.sum ./ +COPY third_party ./third_party + +# 挂载 Go 模块缓存,加速依赖下载 +ARG TARGETOS +ARG TARGETARCH +RUN --mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \ + go mod download + +# 复制源代码 +COPY . . + +# 复制构建好的前端资源到 internal/web/dist 以便嵌入 +COPY --from=frontend-builder /app/web/dist ./internal/web/dist/ + +# 验证前端资源已复制 +RUN ls -la internal/web/dist/ && echo "Frontend assets copied successfully" + +# 整理依赖并编译二进制 +# 挂载 Go 构建缓存和模块缓存,加速重复构建 +RUN --mount=type=cache,target=/root/.cache/go-build,id=gobuild-${TARGETOS}-${TARGETARCH},sharing=locked \ + --mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \ + go mod tidy && \ + BUILD_TIME="${BUILDTIME}" && \ + if [ -z "${BUILD_TIME}" ] || [ "${BUILD_TIME}" = "unknown" ]; then \ + BUILD_TIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"; \ + fi && \ + CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \ + go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" -ldflags "-s -w -X 'github.com/iniwex5/vohive/internal/global.Version=${VERSION}' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=${BUILD_TIME}'" -o vo-hive ./cmd/vohive && \ + if [ "${ENABLE_UPX}" = "1" ] || [ "${ENABLE_UPX}" = "true" ]; then \ + echo "UPX enabled, compressing binary..."; \ + (apk add --no-cache upx >/dev/null 2>&1 || apk add --no-cache upx-ucl >/dev/null 2>&1 || true); \ + if command -v upx >/dev/null 2>&1; then \ + upx --best --lzma /app/vo-hive; \ + else \ + echo "UPX package not available, skip compression."; \ + fi; \ + else \ + echo "UPX disabled."; \ + fi && \ + ls -lh /app/vo-hive + +# 运行阶段 (Runtime) +FROM alpine:latest +ARG REVISION=unknown +WORKDIR /app +LABEL org.opencontainers.image.revision=${REVISION} + +# 运行时依赖 +# - ca-certificates / tzdata: 基础 HTTPS 与时区支持 +RUN apk add --no-cache ca-certificates tzdata + +# 复制二进制文件 +COPY --from=backend-builder /app/vo-hive . + +# 创建配置和数据目录 +RUN mkdir -p config data logs + +# 暴露端口 +EXPOSE 7575 + +# 默认配置路径环境变量 +ENV CONFIG_PATH=/app/config/config.yaml +ENV TZ=Asia/Shanghai + +# 入口点 +ENTRYPOINT ["./vo-hive"] +CMD ["-c", "/app/config/config.yaml"] diff --git a/Dockerfile.github b/Dockerfile.github new file mode 100644 index 00000000..3e14b0e5 --- /dev/null +++ b/Dockerfile.github @@ -0,0 +1,101 @@ +# GitHub Actions 多架构构建专用 Dockerfile + +# 构建阶段 1: 前端构建 (Frontend) +# 使用 --platform=$BUILDPLATFORM 强制在构建机本地架构(通常是amd64)运行 +# 避免在 arm64 构建时使用 QEMU 模拟,大幅提升速度且产物跨平台通用 +FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder +ARG BUILDPLATFORM +WORKDIR /app/web +COPY web/package*.json ./ +# 挂载 npm 缓存,加速依赖安装 +RUN --mount=type=cache,target=/root/.npm,id=npm-${BUILDPLATFORM},sharing=locked \ + npm ci +COPY web/ . +RUN npm run build + +# 构建阶段 2: 后端构建 (Backend) +FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine AS backend-builder +ARG BUILDPLATFORM +ARG VERSION=unknown +ARG BUILDTIME=unknown +ARG REVISION=unknown +ARG ENABLE_UPX=0 +WORKDIR /app + +ENV PATH="/usr/local/go/bin:${PATH}" +# 使用镜像内置的已修复 Go 工具链,避免构建时隐式下载工具链 +ENV GOTOOLCHAIN=local +ENV GOWORK=off + +# 安装构建依赖 +RUN apk add --no-cache git + +# 复制 go mod 文件 +COPY go.mod go.sum ./ +COPY third_party ./third_party + +# 挂载 Go 模块缓存,加速依赖下载 +ARG TARGETOS +ARG TARGETARCH +RUN --mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \ + go mod download + +# 复制源代码 +COPY . . + +# 复制构建好的前端资源到 internal/web/dist 以便嵌入 +COPY --from=frontend-builder /app/web/dist ./internal/web/dist/ + +# 验证前端资源已复制 +RUN ls -la internal/web/dist/ && echo "Frontend assets copied successfully" + +# 整理依赖并编译二进制 +# 挂载 Go 构建缓存和模块缓存,加速重复构建 +RUN --mount=type=cache,target=/root/.cache/go-build,id=gobuild-${TARGETOS}-${TARGETARCH},sharing=locked \ + --mount=type=cache,target=/go/pkg/mod,id=gomod-${TARGETOS}-${TARGETARCH},sharing=locked \ + go mod tidy && \ + BUILD_TIME="${BUILDTIME}" && \ + if [ -z "${BUILD_TIME}" ] || [ "${BUILD_TIME}" = "unknown" ]; then \ + BUILD_TIME="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"; \ + fi && \ + CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \ + go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" -ldflags "-s -w -X 'github.com/iniwex5/vohive/internal/global.Version=${VERSION}' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=${BUILD_TIME}'" -o vo-hive ./cmd/vohive && \ + if [ "${ENABLE_UPX}" = "1" ] || [ "${ENABLE_UPX}" = "true" ]; then \ + echo "UPX enabled, compressing binary..."; \ + (apk add --no-cache upx >/dev/null 2>&1 || apk add --no-cache upx-ucl >/dev/null 2>&1 || true); \ + if command -v upx >/dev/null 2>&1; then \ + upx --best --lzma /app/vo-hive; \ + else \ + echo "UPX package not available, skip compression."; \ + fi; \ + else \ + echo "UPX disabled."; \ + fi && \ + ls -lh /app/vo-hive + +# 运行阶段 (Runtime) +FROM alpine:latest +ARG REVISION=unknown +WORKDIR /app +LABEL org.opencontainers.image.revision=${REVISION} + +# 运行时依赖 +# - ca-certificates / tzdata: 基础 HTTPS 与时区支持 +RUN apk add --no-cache ca-certificates tzdata + +# 复制二进制文件 +COPY --from=backend-builder /app/vo-hive . + +# 创建配置和数据目录 +RUN mkdir -p config data logs + +# 暴露端口 +EXPOSE 7575 + +# 默认配置路径环境变量 +ENV CONFIG_PATH=/app/config/config.yaml +ENV TZ=Asia/Shanghai + +# 入口点 +ENTRYPOINT ["./vo-hive"] +CMD ["-c", "/app/config/config.yaml"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..9526d79d --- /dev/null +++ b/LICENSE @@ -0,0 +1,137 @@ +# PolyForm Noncommercial License 1.0.0 + + + +## Acceptance + +In order to get any license under these terms, you must agree +to them as both strict obligations and conditions to all +your licenses. + +## Copyright License + +The licensor grants you a copyright license for the +software to do everything you might do with the software +that would otherwise infringe the licensor's copyright +in it for any permitted purpose. However, you may +only distribute the software according to [Distribution +License](#distribution-license) and make changes or new works +based on the software according to [Changes and New Works +License](#changes-and-new-works-license). + +## Distribution License + +The licensor grants you an additional copyright license +to distribute copies of the software. Your license +to distribute covers distributing the software with +changes and new works permitted by [Changes and New Works +License](#changes-and-new-works-license). + +## Notices + +You must ensure that anyone who gets a copy of any part of +the software from you also gets a copy of these terms or the +URL for them above, as well as copies of any plain-text lines +beginning with `Required Notice:` that the licensor provided +with the software. For example: + +> Required Notice: Copyright iniwex5 (https://github.com/iniwex5/vohive) + +## Changes and New Works License + +The licensor grants you an additional copyright license to +make changes and new works based on the software for any +permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that +covers patent claims the licensor can license, or becomes able +to license, that you would infringe by using the software. + +## Noncommercial Purposes + +Any noncommercial purpose is a permitted purpose. + +## Personal Uses + +Personal use for research, experiment, and testing for +the benefit of public knowledge, personal study, private +entertainment, hobby projects, amateur pursuits, or religious +observance, without any anticipated commercial application, +is use for a permitted purpose. + +## Noncommercial Organizations + +Use by any charitable organization, educational institution, +public research organization, public safety or health +organization, environmental protection organization, or +government institution is use for a permitted purpose +regardless of the source of funding or obligations resulting +from the funding. + +## Fair Use + +You may have "fair use" rights for the software under the +law. These terms do not limit them. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of +your licenses to anyone else, or prevent the licensor from +granting licenses to anyone else. These terms do not imply +any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or +contributes to infringement of any patent, your patent license +for the software granted under these terms ends immediately. If +your company makes such a claim, your patent license ends +immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have +violated any of these terms, or done anything with the software +not covered by your licenses, your licenses can nonetheless +continue if you come into full compliance with these terms, +and take practical steps to correct past violations, within +32 days of receiving notice. Otherwise, all your licenses +end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without +any warranty or condition, and the licensor will not be liable +to you for any damages arising out of these terms or the use +or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these +terms, and the **software** is the software the licensor makes +available under these terms. + +**You** refers to the individual or entity agreeing to these +terms. + +**Your company** is any legal entity, sole proprietorship, +or other kind of organization that you work for, plus all +organizations that have control over, are under the control of, +or are under common control with that organization. **Control** +means ownership of substantially all the assets of an entity, +or the power to direct its management and policies by vote, +contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the +software under these terms. + +**Use** means anything you do with the software requiring one +of your licenses. + +**Trademark** means trademarks, service marks, and similar rights. + +--- + +Required Notice: Copyright iniwex5 (https://github.com/iniwex5/vohive) diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..c7d26de3 --- /dev/null +++ b/Makefile @@ -0,0 +1,55 @@ +BINARY_NAME ?= vohive +GO_TAGS ?= with_utls nomsgpack +GOOS ?= linux +CGO_ENABLED ?= 0 +VERSION ?= $(shell git describe --tags --always 2>/dev/null || echo "unknown") +VERSION_TAG = $(if $(filter v%,$(VERSION)),$(VERSION),v$(VERSION)) +BUILD_TIME ?= $(shell date "+%Y-%m-%d %H:%M:%S") +DIST_DIR ?= dist +MAIN_PACKAGE ?= ./cmd/vohive + +LDFLAGS = -s -w -X 'github.com/iniwex5/vohive/internal/global.Version=$(VERSION)' -X 'github.com/iniwex5/vohive/internal/global.BuildTime=$(BUILD_TIME)' +GO_BUILD = go build -trimpath -buildvcs=false -tags "$(GO_TAGS)" -ldflags "$(LDFLAGS)" + +AMD64_OUT = $(DIST_DIR)/$(BINARY_NAME)_$(VERSION_TAG)_linux_amd64 +ARM64_OUT = $(DIST_DIR)/$(BINARY_NAME)_$(VERSION_TAG)_linux_arm64 +ARMV7_OUT = $(DIST_DIR)/$(BINARY_NAME)_$(VERSION_TAG)_linux_armv7 +UPX ?= $(shell command -v upx || command -v upx-ucl) +UPX_FLAGS ?= --best --lzma + +.PHONY: all build build-amd64 build-arm64 build-armv7 build-all frontend-dist clean + +all: build-all + +build: build-amd64 + +build-all: build-amd64 build-arm64 build-armv7 + +frontend-dist: + npm ci --prefix web + npm run build --prefix web + rm -rf internal/web/dist + mkdir -p internal/web + cp -R web/dist internal/web/dist + +build-amd64: frontend-dist + @test -n "$(UPX)" || { echo "错误: 需要安装 upx"; exit 1; } + mkdir -p $(DIST_DIR) + CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=amd64 $(GO_BUILD) -o $(AMD64_OUT) $(MAIN_PACKAGE) + $(UPX) $(UPX_FLAGS) $(AMD64_OUT) + +build-arm64: frontend-dist + @test -n "$(UPX)" || { echo "错误: 需要安装 upx"; exit 1; } + mkdir -p $(DIST_DIR) + CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=arm64 $(GO_BUILD) -o $(ARM64_OUT) $(MAIN_PACKAGE) + $(UPX) $(UPX_FLAGS) $(ARM64_OUT) + +build-armv7: frontend-dist + @test -n "$(UPX)" || { echo "错误: 需要安装 upx"; exit 1; } + mkdir -p $(DIST_DIR) + CGO_ENABLED=$(CGO_ENABLED) GOOS=$(GOOS) GOARCH=arm GOARM=7 $(GO_BUILD) -o $(ARMV7_OUT) $(MAIN_PACKAGE) + $(UPX) $(UPX_FLAGS) $(ARMV7_OUT) + +clean: + go clean + rm -rf $(DIST_DIR) diff --git a/README.md b/README.md new file mode 100644 index 00000000..27221d6b --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# VoHive + +> Windloom source integration tree: this repository vendors the visible +> project-level VoHive source dependencies under `third_party/` and builds +> without the unavailable upstream `github.com/iniwex5/vowifi-go` repository. +> See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for source origins, +> license notes, and build-chain details. + +## Local source build + +```bash +npm ci --prefix web +npm run build --prefix web +rm -rf internal/web/dist +mkdir -p internal/web +cp -R web/dist internal/web/dist + +GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ + go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" \ + -o dist/vohive-open_linux_amd64 ./cmd/vohive + +GOWORK=off CGO_ENABLED=0 GOOS=linux GOARCH=arm64 \ + go build -trimpath -buildvcs=false -tags "with_utls nomsgpack" \ + -o dist/vohive-open_linux_arm64 ./cmd/vohive +``` + +## Docker + +```bash +mkdir -p vohive/{config,data,logs} +cp config/config.example.yaml vohive/config/config.yaml +cd vohive +``` + +Use the compose file from this repository, or create one with: + +```yaml +services: + vohive: + image: skyhotspur/vohive:${VOHIVE_TAG:-1.5.5} + container_name: vohive + restart: unless-stopped + network_mode: host + privileged: true + volumes: + - ./config:/app/config + - ./data:/app/data + - ./logs:/app/logs + - /dev:/dev + environment: + TZ: Asia/Shanghai + CONFIG_PATH: /app/config/config.yaml +``` + +Default login: `admin` / `admin`. Change the password after first login. Set +`VOHIVE_TAG` before running Compose when you want a specific image tag. + +[![License: PolyForm Noncommercial 1.0.0](https://img.shields.io/badge/License-PolyForm--Noncommercial--1.0.0-blue.svg)](https://polyformproject.org/licenses/noncommercial/1.0.0) +[![Go](https://img.shields.io/badge/Go-1.26%2B-00ADD8?logo=go)](go.mod) +[![Vue 3](https://img.shields.io/badge/Vue-3-42b883?logo=vue.js)](web/package.json) + +> 面向高通 4G/LTE/5G 模组(Quectel EC20/EC25/EC21/EG25/EM20 等)的综合管理与代理服务平台。 + +VoHive 把模组热插拔管理、SOCKS5/HTTP 代理编排、短信收发、VoWiFi/IMS 通话、eSIM 全生命周期管理整合到一个服务里,并提供一套现代化的响应式 Web 管理后台。 + +## 核心特性 + +| 模块 | 说明 | +| --- | --- | +| 多模组并发管理 | USB 热插拔自动发现(ttyUSB 等)、多设备实时状态监控 | +| 轻量级代理引擎 | 内建 SOCKS5 / HTTP 代理内核,支持多实例并发;基于 `SO_BINDTODEVICE` 按设备网卡严格绑定出站流量 | +| 通信与短信中心 | 统一界面/API 处理 AT 短信收发、会话与联系人管理、USSD 交互,短信落库可查 | +| eSIM 管理 | 通过 AT 指令通道直接管理 eSIM 芯片,支持 Profile 下载、启用/停用、重命名、删除 | +| 全渠道通知 | 重要短信及系统告警可推送至 Telegram、Email、PushPlus、Bark、飞书(Lark/Feishu)、QQ 等 | +| 多架构构建 | 原生支持 amd64 / arm64 / arm7 跨平台编译,路由器到边缘节点均可部署 | + +## 典型应用场景 + +- **私有 IP 代理池**:单主机挂载多张物理 SIM 卡或多张 eSIM,每张网卡对应独立的 SOCKS5/HTTP 实例,组建自己的移动网络代理。 +- **统一接码/验证码中心**:Web 界面或 API 并行收发多卡短信,并通过 Webhook/Bot 实时推送到个人终端。 +- **VoWiFi 零信号通信**:地下室、弱覆盖场景下,借助宽带网络隧道建立 IMS 连接,保证业务不掉线。 + +## 架构与技术栈 + +- **Backend**:Go 1.26+(Gin、GORM、Viper、euicc-go) +- **Frontend**:Vue 3 + Vite + TailwindCSS + Element Plus +- **Database**:SQLite(`vohive.db`) +- **CI/CD**:GitHub Actions 自动化多架构 Docker 镜像构建与发布 + + +## 免责声明 + +- **用途定位**:本项目主要面向个人学习、技术研究与功能测试场景,不建议直接用于生产环境或关键业务系统;由此产生的部署及使用风险由使用者自行承担。 +- **非官方项目**:VoHive 为第三方独立开发的开源软件,与 Quectel(高通模组厂商)、高通公司及其他任何模组/芯片厂商均无官方关联、授权或合作关系,亦不对模组硬件本身的功能、质量或安全性负责。 +- **合规使用**:使用本项目搭建的服务时,请自行确保符合所在地区的法律法规及电信运营商的服务条款,不得用于任何违法违规用途。因违规使用造成的一切法律责任由使用者自行承担,与本项目作者及贡献者无关。 +- **无担保**:本软件按"现状"提供,不附带任何明示或暗示的担保,包括但不限于适销性、特定用途适用性及不侵权担保。因使用或无法使用本软件(含数据丢失、设备异常、业务中断等)造成的任何直接或间接损失,作者及贡献者不承担任何责任。 + +## License + +本源码整合树不是单一许可项目。根项目基于 [PolyForm Noncommercial License 1.0.0](LICENSE),`third_party/vowifi-go` 使用 AGPL-3.0,`third_party/quectel-qmi-go`、`third_party/netlink`、`third_party/qqbot` 等组件按各自许可证授权。发布公开二进制或 Docker 镜像前,请先确认组合分发的许可证义务;详情见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..047970c0 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,48 @@ +# Third-party source notices + +This repository is a source-complete integration tree for local builds of VoHive. +It keeps the visible project-level source dependencies in `third_party/` so the +build no longer depends on the unavailable `github.com/iniwex5/vowifi-go` +repository or on release-only VoHive binaries. + +## Included source trees + +| Path | Upstream | Commit checked | License | +| --- | --- | --- | --- | +| `.` | `https://github.com/giszh86/vohive` | `f240894e763cf7f0cf74c88562bb9b55f0d573b1` | PolyForm Noncommercial 1.0.0 | +| `third_party/netlink` | `https://github.com/iniwex5/netlink` | module cache `v1.3.3` | MIT | +| `third_party/qqbot` | `https://github.com/iniwex5/qqbot` | module cache `v1.0.1` | MIT | +| `third_party/quectel-qmi-go` | `https://github.com/iniwex5/quectel-qmi-go` | `aaada14395c19ee4c8b4b15a373f41bd2ed14cf0` (`v0.6.0`) | MIT | +| `third_party/vowifi-go` | `https://github.com/boa-z/vowifi-go` | `23459976796fb43b024c479b19b6edf8baf379d4` | AGPL-3.0 | + +The original `github.com/iniwex5/vowifi-go v1.1.2` module was not publicly +accessible at the time this integration tree was assembled. The replacement +under `third_party/vowifi-go` is an independent open implementation that uses +the same module path for compatibility. + +## Build notes + +The root `go.mod` uses local `replace` directives: + +```go +replace ( + github.com/iniwex5/netlink => ./third_party/netlink + github.com/iniwex5/qqbot => ./third_party/qqbot + github.com/iniwex5/quectel-qmi-go => ./third_party/quectel-qmi-go + github.com/iniwex5/vowifi-go => ./third_party/vowifi-go +) +``` + +In-app binary self-updates are disabled for this integration tree. Release +binaries and Docker images should be updated through repository releases or +container image rollout. + +UPX compression is disabled by default in `Dockerfile.github` to keep produced +binaries easier to inspect. + +## License compatibility note + +The root project license and the included AGPL-3.0 VoWiFi implementation carry +different obligations. This file documents the source origins; it does not grant +additional rights or resolve license compatibility for public combined binary or +container distribution. diff --git a/cmd/mbimprobe/main.go b/cmd/mbimprobe/main.go new file mode 100644 index 00000000..aa6aed24 --- /dev/null +++ b/cmd/mbimprobe/main.go @@ -0,0 +1,306 @@ +// Command mbimprobe is a throwaway real-device harness. NOT part of the build. +package main + +import ( + "context" + "crypto/rand" + "fmt" + "os" + "time" + "encoding/hex" + + dev "github.com/iniwex5/vohive/internal/device" + mbimcore "github.com/iniwex5/vohive/internal/mbim" +) + +func main() { + mode := "probe" + if len(os.Args) > 1 { + mode = os.Args[1] + } + if mode == "scan" { + runScan() + return + } + if mode == "uicc" { + runUICC() + return + } + if mode == "auth" { + runAuth() + return + } + if mode == "simauth" { + runSimAuth() + return + } + runProbe() +} + +// runSimAuth 验证"逻辑通道 + APDU"链路:用已知能开的 ISD-R 完整 AID 开出通道, +// 然后在通道上发真 APDU 选 USIM(部分 AID),确认 APDU 传输可用 + USIM 可选中。 +// 两点成立 → 逻辑通道 AKA 可行(复用现有 APDU AUTHENTICATE 逻辑)。 +// runSimAuth 验证智能选卡与 MBIM 逻辑通道 AKA。 +// 直接获取 QMI 暴露的长 AID,打开逻辑通道并尝试发送 0x88 AUTHENTICATE 指令。 +func runSimAuth() { + node := "/dev/cdc-wdm2" + if len(os.Args) > 2 { + node = os.Args[2] + } + octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second) + defer ocancel() + m := mbimcore.New(node, "auto") + if err := m.Open(octx); err != nil { + fmt.Println("Open 失败:", err) + os.Exit(1) + } + defer m.Close() + fmt.Println("== 测试智能选卡与逻辑通道 APDU (MBIM AKA) ==") + + aidStr, source, err := m.ResolveLogicalChannelAID("usim", "") + if err != nil { + fmt.Println("智能选卡提取 USIM 失败:", err) + return + } + fmt.Printf("成功提取 USIM 长 AID: %s (Source: %s)\n", aidStr, source) + + aid, _ := hex.DecodeString(aidStr) + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + defer cancel() + + ch, err := m.OpenChannel(ctx, aid) + if err != nil { + fmt.Printf("OpenChannel(USIM) 失败: %v\n", err) + return + } + fmt.Printf("OpenChannel(USIM) OK channel=%d\n", ch) + defer m.CloseChannel(ctx, ch) + + // 伪造全 0 的 RAND 和 AUTN 发送 AKA + randBytes := make([]byte, 16) + autnBytes := make([]byte, 16) + // CLA(含通道号), INS(0x88), P1(0x00), P2(0x81), Lc(0x22), Data... + cla := byte(ch) & 0x03 + apdu := []byte{cla, 0x88, 0x00, 0x81, 0x22, 0x10} + apdu = append(apdu, randBytes...) + apdu = append(apdu, 0x10) + apdu = append(apdu, autnBytes...) + + fmt.Printf("发送 3G AKA 鉴权 APDU: %X\n", apdu) + resp, err := m.TransmitAPDU(ctx, ch, apdu) + if err != nil { + fmt.Println("TransmitAPDU(AKA) 失败:", err) + return + } + fmt.Printf("TransmitAPDU(AKA) 响应: %X\n", resp) + if len(resp) >= 2 && resp[len(resp)-2] == 0x98 && resp[len(resp)-1] == 0x62 { + fmt.Println("验证成功:收到 9862(MAC Failure)!底层逻辑通道鉴权完全打通。") + } else if len(resp) >= 2 && resp[len(resp)-2] == 0x61 { + fmt.Println("验证成功:收到 61xx!有响应数据。底层逻辑通道鉴权完全打通。") + } else { + fmt.Println("收到其他响应,可能是通道状态或指令参数不支持。") + } +} + +// runAuth 判别这颗模组的 MBIM AUTH 服务是真可用还是 stub。 +// - AUTH_SIM(2G GSM):无 AUTN/MAC,功能正常的子系统对任意 RAND 都返回 SRES/Kc; +// 报错 → 整个 AUTH 服务是 stub。 +// - AUTH_AKA(随机 RAND/AUTN):预期 status=0x23(35,INCORRECT_AUTN),作基线对照。 +func runAuth() { + node := "/dev/cdc-wdm2" + if len(os.Args) > 2 { + node = os.Args[2] + } + octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second) + defer ocancel() + m := mbimcore.New(node, "auto") + if err := m.Open(octx); err != nil { + fmt.Println("Open 失败:", err) + os.Exit(1) + } + defer m.Close() + fmt.Println("== MBIM Open 成功,测试 AUTH 服务可用性 ==") + + r16 := func() []byte { + b := make([]byte, 16) + _, _ = rand.Read(b) + return b + } + + ctx1, c1 := context.WithTimeout(context.Background(), 8*time.Second) + sres, kc, err := m.AuthSIM(ctx1, r16()) + c1() + if err != nil { + fmt.Printf("AUTH_SIM(2G): 报错 -> %v\n", err) + fmt.Println(" 判定: AUTH 服务大概率是 stub(连无 MAC 校验的 GSM 鉴权都失败)") + } else { + fmt.Printf("AUTH_SIM(2G): OK SRES=0x%08x Kc=0x%016x\n", sres, kc) + fmt.Println(" 判定: AUTH 子系统是工作的 → AKA 的 status=35 不是 stub,需查应用上下文(USIM/ISIM)") + } + + ctx2, c2 := context.WithTimeout(context.Background(), 8*time.Second) + _, _, _, _, akaErr := m.CalculateAKA(ctx2, r16(), r16()) + c2() + if akaErr != nil { + fmt.Printf("AUTH_AKA(随机): %v (基线:随机 AUTN 必然 MAC 失败,预期 0x23/35)\n", akaErr) + } else { + fmt.Println("AUTH_AKA(随机): 竟然成功? 异常,随机 AUTN 不应通过 MAC") + } +} + +func runScan() { + // 复现 API handleDeviceMgmtDiscovered 的发现路径:QMI+fallback 合并。 + fmt.Println("== DiscoverCompatibleModemsFromQMI(nil) [= /devices/discovered 路径] ==") + list, err := dev.DiscoverCompatibleModemsFromQMI(nil) + if err != nil { + fmt.Println("发现错误:", err) + return + } + if len(list) == 0 { + fmt.Println("(未发现兼容 modem)") + return + } + for i, m := range list { + fmt.Printf("[%d] mode=%s transport=%s vid:pid=%04x:%04x driver=%s\n", + i, m.Mode, m.TransportType, m.VendorID, m.ProductID, m.DriverName) + fmt.Printf(" control=%s net=%s usb=%s netcap=%v IMEI=%s AT=%v\n", + m.ControlPath, m.NetInterface, m.USBPath, m.NetworkCapable, m.IMEI, m.ATPorts) + if m.Mode == "mbim" { + enriched, imei := dev.EnrichDiscoveredCompatibleModem(m, dev.CompatibleModemEnrichOptions{ + EnableATProbe: true, + ATProbeTimeout: 900 * time.Millisecond, + }) + fmt.Printf(" [enrich] AT口=%s IMEI=%q (enrichment 未崩溃)\n", enriched.ATPort, imei) + } + } +} + +func runUICC() { + node := "/dev/cdc-wdm2" + if len(os.Args) > 2 { + node = os.Args[2] + } + octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second) + defer ocancel() + m := mbimcore.New(node, "auto") + if err := m.Open(octx); err != nil { + fmt.Println("Open 失败:", err) + os.Exit(1) + } + defer m.Close() + fmt.Println("== MBIM Open 成功(走 mbim-proxy,不与现有进程抢占设备),测试 UICC 逻辑通道 ==") + + // 尝试直接通过 QMI over MBIM 隧道获取长 AID 列表 + fmt.Println("== 尝试通过原生 QMI over MBIM 隧道获取所有应用信息 ==") + qmiCtx, qmiCancel := context.WithTimeout(context.Background(), 5*time.Second) + apps, qmiErr := m.QMIUIMApplicationList(qmiCtx) + qmiCancel() + if qmiErr != nil { + fmt.Printf("QMIUIMApplicationList 失败: %v\n", qmiErr) + } else { + appTypeNames := map[uint8]string{1: "SIM(2G)", 2: "USIM(3G/4G/5G)", 3: "RUIM", 4: "CSIM", 5: "ISIM"} + for i, app := range apps { + name := appTypeNames[app.Type] + if name == "" { + name = fmt.Sprintf("Unknown(%d)", app.Type) + } + fmt.Printf(" 发现应用[%d]: 类型=%-14s AID=%X\n", i, name, app.AID) + } + } + fmt.Println("==================================================") + + // ISD-R AID (eSIM) 和 USIM 选 MF 的最小尝试 + cases := []struct { + name string + aid []byte + }{ + {"ISD-R(eSIM)", []byte{0xA0, 0x00, 0x00, 0x05, 0x59, 0x10, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0x89, 0x00, 0x00, 0x01, 0x00}}, + {"USIM Partial(7)", []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02}}, + {"USIM Fake(16)", []byte{0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, + {"空AID(基础通道)", nil}, + } + for _, c := range cases { + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + ch, err := m.OpenChannel(ctx, c.aid) + if err != nil { + fmt.Printf("%-16s OpenChannel 失败: %v\n", c.name, err) + cancel() + continue + } + fmt.Printf("%-16s OpenChannel OK channel=%d\n", c.name, ch) + _ = m.CloseChannel(ctx, ch) + cancel() + } +} + +func runProbe() { + node := "/dev/cdc-wdm2" + if len(os.Args) > 2 { + node = os.Args[2] + } + octx, ocancel := context.WithTimeout(context.Background(), 10*time.Second) + defer ocancel() + m := mbimcore.New(node, "direct") + if err := m.Open(octx); err != nil { + fmt.Println("Open 失败:", err) + os.Exit(1) + } + defer m.Close() + fmt.Println("== MBIM Open 成功 ==") + + step := func(name string, fn func(context.Context) string) { + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + done := make(chan string, 1) + go func() { done <- fn(ctx) }() + select { + case s := <-done: + fmt.Printf("%-14s %s\n", name+":", s) + case <-ctx.Done(): + fmt.Printf("%-14s 超时/无响应\n", name+":") + } + } + + step("DeviceCaps", func(ctx context.Context) string { + c, err := m.DeviceCaps(ctx) + if err != nil { + return "ERR " + err.Error() + } + return fmt.Sprintf("IMEI=%s FW=%s", c.DeviceID, c.FirmwareInfo) + }) + step("Subscriber", func(ctx context.Context) string { + s, err := m.SubscriberReady(ctx) + if err != nil { + return "ERR " + err.Error() + } + return fmt.Sprintf("ready=%d IMSI=%s ICCID=%s", s.ReadyState, s.IMSI, s.ICCID) + }) + step("Register", func(ctx context.Context) string { + r, err := m.RegisterState(ctx) + if err != nil { + return "ERR " + err.Error() + } + return fmt.Sprintf("state=%d provider=%q MCC=%s MNC=%s", r.RegisterState, r.ProviderName, r.MCC, r.MNC) + }) + step("Signal", func(ctx context.Context) string { + s, err := m.SignalState(ctx) + if err != nil { + return "ERR " + err.Error() + } + return fmt.Sprintf("unknown=%v rssi=%d dBm=%d", s.Unknown, s.RSSI, s.DBM) + }) + step("Packet", func(ctx context.Context) string { + p, err := m.PacketService(ctx) + if err != nil { + return "ERR " + err.Error() + } + return fmt.Sprintf("state=%d", p.State) + }) + step("Radio", func(ctx context.Context) string { + r, err := m.RadioState(ctx) + if err != nil { + return "ERR " + err.Error() + } + return fmt.Sprintf("hw=%d sw=%d", r.Hardware, r.Software) + }) +} diff --git a/cmd/vohive/main.go b/cmd/vohive/main.go new file mode 100644 index 00000000..b0d3caeb --- /dev/null +++ b/cmd/vohive/main.go @@ -0,0 +1,277 @@ +package main + +import ( + "context" + "errors" + "flag" + "log" + "log/slog" + "net/http" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + "github.com/iniwex5/vohive/internal/api" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/db" + "github.com/iniwex5/vohive/internal/device" + "github.com/iniwex5/vohive/internal/notify" + proxyserver "github.com/iniwex5/vohive/internal/proxy/server" + "github.com/iniwex5/vohive/internal/proxy/traffic" + "github.com/iniwex5/vohive/internal/upstreamproxy" + "github.com/iniwex5/vowifi-go/runtimehost/carrier" + "github.com/iniwex5/vowifi-go/runtimehost/voicehost" + + "github.com/iniwex5/vohive/internal/web" + "github.com/iniwex5/vohive/pkg/logger" +) + +func main() { + // Parse flags + var configPath string + var backendOnly bool + flag.StringVar(&configPath, "c", "config/config.yaml", "config file path") + flag.BoolVar(&backendOnly, "backend-only", false, "run as backend-only (disable embedded web UI)") + flag.Parse() + + // 1. 加载配置 + if err := config.InitGlobalManager(configPath); err != nil { + log.Fatalf("初始化配置管理器失败: %v", err) + } + cfg := config.GetConfig() + + // 2. 初始化日志 + logger.Setup(logger.LogConfig{ + Debug: cfg.Server.Debug, + Filename: "logs/app.log", + }) + // 将内置 slog 重定向到已就绪的系统日志框架 + slog.SetDefault(slog.New(logger.NewSlogHandler(logger.ZapLogger()))) + logger.Info("VoHive 模组管理器启动中...") + + go func() { + disclaimer := ` +====================================================================== +【VoHive 免责与使用声明】 +1. 本软件仅供个人技术测试与研究交流,严禁任何商业用途。 +2. 严禁将本软件用于任何非法或违规场景。 +3. 本软件涉及底层通信操作,因测试产生的硬件、资费或网络风险由用户自行承担。 +4. 作者不对使用本软件造成的任何直接或间接损失负责。 +======================================================================` + logger.Warn(disclaimer) + ticker := time.NewTicker(24 * time.Hour) + defer ticker.Stop() + for range ticker.C { + logger.Warn(disclaimer) + } + }() + + loadResult, err := carrier.LoadCarrierOverrides("") + if err != nil { + carrier.ClearCarrierOverrides() + logger.Warn("加载 carrier_overrides 失败,回退内置运营商配置", + "path", loadResult.Path, + "err", err) + } else if loadResult.Missing { + //logger.Info("carrier_overrides 文件不存在,使用内置运营商配置", "path", loadResult.Path) + } else { + logger.Info("carrier_overrides 已加载", "path", loadResult.Path, "entries", loadResult.Count) + } + + // 3. 初始化数据库 + dbPath := "data/vohive.db" + if err := db.Init(dbPath); err != nil { + log.Fatalf("初始化数据库失败: %v", err) + } + dbResolvedPath := dbPath + if absPath, err := filepath.Abs(dbPath); err == nil { + dbResolvedPath = absPath + } + logger.Info("数据库已初始化", "path", dbPath, "resolved_path", dbResolvedPath) + countryResult := upstreamproxy.InitCountryTable(context.Background(), upstreamproxy.CountryTableOptions{ + CachePath: upstreamproxy.DefaultCountryTableCachePath, + }) + if countryResult.Err != nil { + logger.Warn("MCC/MNC 国家表不可用,VoWiFi 国家代理规则将按未知国家直连", + "path", countryResult.CachePath, + "source_url", countryResult.SourceURL, + "source", countryResult.Source, + "err", countryResult.Err) + } else { + logger.Info("MCC/MNC 国家表已加载", + "path", countryResult.CachePath, + "source", countryResult.Source, + "rows", countryResult.RowCount, + "countries", countryResult.Countries) + } + go func() { + need, err := db.NeedBackfillSMSContacts() + if err != nil { + logger.Error("短信联系人回填检查失败", "err", err) + return + } + if !need { + return + } + logger.Info("开始短信联系人回填") + if err := db.BackfillSMSPeerAndContacts(1000); err != nil { + logger.Error("短信联系人回填失败", "err", err) + return + } + logger.Info("短信联系人回填完成") + }() + + // 4. 初始化设备池 + + pool := device.NewPool(cfg) + + pool.SetPolicyResolver(db.CardPolicyResolver{}) + + // 6. 初始化代理实例管理器 + proxyMgr := proxyserver.NewManager() + logger.Info("代理实例管理器已初始化") + + // 7. 初始化语音网关 + // voiceGW 始终创建,用于管理 VoWiFi Agent(SimulateCall 等)。 + var notifyMgr *notify.Manager + voiceGW := voicehost.NewGateway() + pool.SetVoiceGateway(voiceGW) + + if err := voiceGW.Start(context.Background()); err != nil { + logger.Error("语音网关启动失败", "err", err) + } else { + logger.Info("语音网关已启动") + + // 通知管理器初始化 + var err error + notifyMgr, err = notify.NewManager(cfg, pool) + if err != nil { + logger.Warn("通知管理器初始化异常", "err", err) + } else { + pool.SetNotifier(notifyMgr) + voiceGW.SetNotifier(notifyMgr) + } + + } + + // 5. 启动工作器 (代理, 短信, 健康检查) + _ = pool.StartAll() + + trafficSampler := traffic.New(traffic.Options{Pool: pool, Mgr: proxyMgr}) + trafficSampler.Start() + realtimeTraffic := traffic.NewRealtimeManager(traffic.RealtimeOptions{Pool: pool}) + + // 7. 启动 API 服务器 + // 准备静态文件系统 + var staticFS http.FileSystem + if backendOnly { + logger.Info("启用纯后端模式(未挂载前端静态资源)") + } else { + distFS, err := web.GetFS() + if err != nil { + log.Fatalf("无法加载嵌入的 Web 文件: %v", err) + } + staticFS = http.FS(distFS) + } + + // 通知管理器如果在上方未初始化,在这里兜底(防止 VoiceGW 未配置/启动的场景) + if notifyMgr == nil { + var err error + notifyMgr, err = notify.NewManager(cfg, pool) + if err != nil { + logger.Warn("通知管理器初始化异常", "err", err) + } else { + pool.SetNotifier(notifyMgr) + if voiceGW != nil { + voiceGW.SetNotifier(notifyMgr) + } + } + } + + apiServer := api.New(cfg, pool, staticFS, proxyMgr, voiceGW, notifyMgr, configPath) + apiServer.SetRealtimeTraffic(realtimeTraffic) + + syncProxyConfigs := func(reason, deviceID string) { + if err := apiServer.SyncProxyConfigs(); err != nil { + logger.Warn("同步代理配置失败", "reason", reason, "device_id", deviceID, "err", err) + return + } + logger.Debug("代理配置已同步", "reason", reason, "device_id", deviceID) + } + pool.OnDataConnected(func(deviceID string) { + syncProxyConfigs("qmi_data_connected", deviceID) + }) + + // 启动后同步代理配置到实例管理器 + go func() { + time.Sleep(500 * time.Millisecond) // 等待 API 服务器初始化 + syncProxyConfigs("startup", "") + }() + + apiErrCh := make(chan error, 1) + go func() { + if err := apiServer.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) { + apiErrCh <- err + } + }() + + logger.Info("所有服务已启动") + + quit := make(chan os.Signal, 2) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(quit) + + // 8. 等待关闭信号 + var sig os.Signal + select { + case sig = <-quit: + logger.Info("收到关闭信号", "signal", sig.String()) + case err := <-apiErrCh: + logger.Error("API 服务器失败", "err", err) + } + logger.Info("正在优雅关闭所有服务...") + + // 9. 优雅关闭 + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutdownCancel() + + done := make(chan struct{}) + go func() { + if err := apiServer.Shutdown(shutdownCtx); err != nil { + logger.Error("关闭 API 服务器时出错", "err", err) + } + + if notifyMgr != nil { + notifyMgr.Close() + } + + trafficSampler.Stop() + + if err := proxyMgr.Shutdown(shutdownCtx); err != nil { + logger.Error("关闭代理实例时出错", "err", err) + } + + // 关闭语音网关 + if voiceGW != nil { + if err := voiceGW.Stop(); err != nil { + logger.Error("关闭语音网关时出错", "err", err) + } + } + + if err := pool.Shutdown(); err != nil { + logger.Error("关闭工作器池时出错", "err", err) + } + close(done) + }() + + select { + case <-done: + case <-quit: + case <-time.After(12 * time.Second): + logger.Warn("关闭超时,强制退出") + } + + logger.Info("再见!") +} diff --git a/config/config.example.yaml b/config/config.example.yaml new file mode 100644 index 00000000..8cc62928 --- /dev/null +++ b/config/config.example.yaml @@ -0,0 +1,18 @@ +server: + debug: false + port: 7575 + +web: + username: admin + password: admin + +devices: [] + +proxy: + instances: [] + +vowifi: + enabled: false + +webhook: + enabled: false diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..588c6598 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,15 @@ +services: + vohive: + image: skyhotspur/vohive:${VOHIVE_TAG:-1.5.5} + container_name: vohive + restart: unless-stopped + network_mode: host + privileged: true + volumes: + - ./config:/app/config + - ./data:/app/data + - ./logs:/app/logs + - /dev:/dev + environment: + TZ: Asia/Shanghai + CONFIG_PATH: /app/config/config.yaml diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..a77e1c13 --- /dev/null +++ b/go.mod @@ -0,0 +1,108 @@ +module github.com/iniwex5/vohive + +go 1.26.4 + +replace ( + github.com/iniwex5/netlink => ./third_party/netlink + github.com/iniwex5/qqbot => ./third_party/qqbot + github.com/iniwex5/quectel-qmi-go => ./third_party/quectel-qmi-go + github.com/iniwex5/vowifi-go => ./third_party/vowifi-go +) + +require ( + github.com/damonto/euicc-go v1.1.3-0.20260628013808-8d873a2dfc98 + github.com/gin-gonic/gin v1.11.0 + github.com/glebarez/sqlite v1.11.0 + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/iniwex5/netlink v1.3.3 + github.com/iniwex5/qqbot v1.0.1 + github.com/iniwex5/quectel-qmi-go v0.6.0 + github.com/iniwex5/vowifi-go v1.1.2 + github.com/larksuite/oapi-sdk-go/v3 v3.5.3 + github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible + github.com/miekg/dns v1.1.67 + github.com/spf13/viper v1.21.0 + github.com/stretchr/testify v1.11.1 + github.com/things-go/go-socks5 v0.1.1 + github.com/warthog618/sms v0.3.0 + go.bug.st/serial v1.6.4 + go.uber.org/zap v1.27.1 + go.yaml.in/yaml/v3 v3.0.4 + golang.org/x/crypto v0.49.0 + golang.org/x/sync v0.20.0 + golang.org/x/sys v0.46.0 + gopkg.in/yaml.v3 v3.0.1 + gorm.io/gorm v1.30.5 +) + +require ( + github.com/bytedance/sonic v1.14.0 // indirect + github.com/bytedance/sonic/loader v0.3.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/creack/goselect v0.1.2 // indirect + github.com/damonto/uicc-go v0.0.0-20260622025011-5cf36d6c8626 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/emiago/sipgo v1.4.0 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.8 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/glebarez/go-sqlite v1.21.2 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.27.0 // indirect + github.com/go-viper/mapstructure/v2 v2.4.0 // indirect + github.com/gobwas/httphead v0.1.0 // indirect + github.com/gobwas/pool v0.2.1 // indirect + github.com/gobwas/ws v1.4.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/goccy/go-yaml v1.18.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/websocket v1.5.3 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/jonboulle/clockwork v0.5.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/lestrrat-go/strftime v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/pion/logging v0.2.4 // indirect + github.com/pion/randutil v0.1.0 // indirect + github.com/pion/rtcp v1.2.16 // indirect + github.com/pion/rtp v1.10.2 // indirect + github.com/pion/srtp/v3 v3.0.12 // indirect + github.com/pion/transport/v4 v4.0.2 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.57.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect + github.com/sagikazarmark/locafero v0.11.0 // indirect + github.com/sirupsen/logrus v1.9.4 // indirect + github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect + github.com/spf13/afero v1.15.0 // indirect + github.com/spf13/cast v1.10.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.0 // indirect + github.com/vishvananda/netns v0.0.5 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/arch v0.20.0 // indirect + golang.org/x/mod v0.34.0 // indirect + golang.org/x/net v0.52.0 // indirect + golang.org/x/text v0.36.0 // indirect + golang.org/x/tools v0.43.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect + modernc.org/libc v1.22.5 // indirect + modernc.org/mathutil v1.5.0 // indirect + modernc.org/memory v1.5.0 // indirect + modernc.org/sqlite v1.23.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..c22c6b58 --- /dev/null +++ b/go.sum @@ -0,0 +1,249 @@ +github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= +github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= +github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= +github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0= +github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY= +github.com/damonto/euicc-go v1.1.3-0.20260628013808-8d873a2dfc98 h1:n2VA/WOWZCYjcd90zAuH+PlZpDjiEeXfIO1rMbIEsfM= +github.com/damonto/euicc-go v1.1.3-0.20260628013808-8d873a2dfc98/go.mod h1:L2YqXCb1ESnL1ZlqkQ7t/bVrcqrgt1hCwdzWrVzgYN0= +github.com/damonto/uicc-go v0.0.0-20260622025011-5cf36d6c8626 h1:jcUx6ygMhU27ca9qn0qX3rZCa1956YYJcn/1NUhX8XQ= +github.com/damonto/uicc-go v0.0.0-20260622025011-5cf36d6c8626/go.mod h1:4il4tcO0GJ2Bn8827RWDiMxNOnQpEApy3pwKliaR9uc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/emiago/sipgo v1.4.0 h1:IRiwIUu4H97gC+vq2zsm3iWe/j08LPExFZRe3kfY0f0= +github.com/emiago/sipgo v1.4.0/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= +github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk= +github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls= +github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= +github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= +github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= +github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4= +github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= +github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= +github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= +github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a h1:fEBsGL/sjAuJrgah5XqmmYsTLzJp/TO9Lhy39gkverk= +github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= +github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/larksuite/oapi-sdk-go/v3 v3.5.3 h1:xvf8Dv29kBXC5/DNDCLhHkAFW8l/0LlQJimO5Zn+JUk= +github.com/larksuite/oapi-sdk-go/v3 v3.5.3/go.mod h1:ZEplY+kwuIrj/nqw5uSCINNATcH3KdxSN7y+UxYY5fI= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8= +github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= +github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4= +github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA= +github.com/lestrrat-go/strftime v1.2.0 h1:8fAUYOeaJKCuLzNvUWBAo8t6I6hkFfodDTndEzJIun0= +github.com/lestrrat-go/strftime v1.2.0/go.mod h1:GtsIA/7ddIGJjEdfadUafEb1sbutvlvpMdPCMglykYo= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/miekg/dns v1.1.67 h1:kg0EHj0G4bfT5/oOys6HhZw4vmMlnoZ+gDu8tJ/AlI0= +github.com/miekg/dns v1.1.67/go.mod h1:fujopn7TB3Pu3JM69XaawiU0wqjpL9/8xGop5UrTPps= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8= +github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so= +github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= +github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= +github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo= +github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo= +github.com/pion/rtp v1.10.2 h1:l+f6tTDcAH6xwepaAoW791ddhuYsJlqRATOzirO04Mo= +github.com/pion/rtp v1.10.2/go.mod h1:Au8fc6cEByy8RLTwKTQTEeQqDB/SJDxwL4mZuxYA5Pk= +github.com/pion/srtp/v3 v3.0.12 h1:U7V17bckl7sI4mb3sepiojByDuBY0wNCqQE+6IlQBbc= +github.com/pion/srtp/v3 v3.0.12/go.mod h1:EeZOi/sd6glM1EXapg051gdNWO9yWT1YSsgQ4SlJkns= +github.com/pion/transport/v4 v4.0.2 h1:ifYlPqNwsy6aKQ9y8yzxXlHae5431ZrH2avkD/Rn6Tk= +github.com/pion/transport/v4 v4.0.2/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.57.0 h1:AsSSrrMs4qI/hLrKlTH/TGQeTMY0ib1pAOX7vA3AdqE= +github.com/quic-go/quic-go v0.57.0/go.mod h1:ly4QBAjHA2VhdnxhojRsCUOeJwKYg+taDlos92xb1+s= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= +github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/things-go/go-socks5 v0.1.1 h1:48hy9cHEXPKeG91G/g4n8zW4uynzPUQy/FkcrJ7r5AY= +github.com/things-go/go-socks5 v0.1.1/go.mod h1:1YBHVYG7Oli5ae+Pwkp630cPAwY1pjUPmohO1n0Emg0= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA= +github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY= +github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM= +github.com/warthog618/sms v0.3.0 h1:LYAb5ngmu2qjNExgji3B7xi2tIZ9+DsuE9pC5xs4wwc= +github.com/warthog618/sms v0.3.0/go.mod h1:+bYZGeBxu003sxD5xhzsrIPBAjPBzTABsRTwSpd7ld4= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A= +go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= +go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= +golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= +golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg= +golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s= +golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/gorm v1.30.5 h1:dvEfYwxL+i+xgCNSGGBT1lDjCzfELK8fHZxL3Ee9X0s= +gorm.io/gorm v1.30.5/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE= +modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE= +modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= +modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM= +modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk= diff --git a/go.work b/go.work new file mode 100644 index 00000000..aed9a8b5 --- /dev/null +++ b/go.work @@ -0,0 +1,9 @@ +go 1.26.4 + +use ( + . + ./third_party/netlink + ./third_party/qqbot + ./third_party/quectel-qmi-go + ./third_party/vowifi-go +) diff --git a/internal/apduarbiter/arbiter.go b/internal/apduarbiter/arbiter.go new file mode 100644 index 00000000..bae6940a --- /dev/null +++ b/internal/apduarbiter/arbiter.go @@ -0,0 +1,940 @@ +package apduarbiter + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/iniwex5/vohive/pkg/logger" +) + +var ErrAPDUBusy = errors.New("apdu busy") + +type LeaseType string + +const ( + LeaseTypeSession LeaseType = "session" + LeaseTypeOneShot LeaseType = "oneshot" + LeaseTypeTransport LeaseType = "transport" + LeaseTypeBarrier LeaseType = "barrier" +) + +type TransportScope string + +const ( + TransportScopeExclusive TransportScope = "exclusive" + TransportScopeQMIChannel TransportScope = "qmi_channel" +) + +type APDUClass string + +const ( + APDUClassEUICCWrite APDUClass = "EUICCWrite" + APDUClassEUICCRead APDUClass = "EUICCRead" + APDUClassUSIMAKA APDUClass = "USIMAKA" + APDUClassSMSC APDUClass = "SMSC" + APDUClassSwitchBarrier APDUClass = "SwitchBarrier" + APDUClassRecovery APDUClass = "Recovery" +) + +const transportPriorityAging = 500 * time.Millisecond + +type Options struct { + // MaxLeaseHold 是单条 APDU transport lease 的无进展 watchdog 超时。 + // 持有方应在长耗时单条 APDU 前后调用 Touch;logical channel 生命周期不应再持有该 lease。 + MaxLeaseHold time.Duration + // MaxSessions 是 legacy 兼容字段,仅服务旧 AcquireSession 接口。 + // 新生产路径应使用 AcquireTransport,默认单设备同一时刻只允许一个 active transport APDU。 + MaxSessions int + // MaxQMITransports 限制 QMI logical-channel transport 并发数量。 + // 只有显式使用 TransportScopeQMIChannel 的 QMI channel APDU 会使用该并发窗口。 + MaxQMITransports int +} + +type Request struct { + Owner string + Mode string + Class APDUClass + Channel int + Scope TransportScope +} + +type BarrierPolicy struct { + BlockedClasses []APDUClass +} + +type Stats struct { + WaitRequests uint64 + Acquires uint64 + WaitTimeouts uint64 + ForcedReleases uint64 + CurrentQueue int + ActiveSessions int + ActiveOneshot bool + ActiveTransport bool + ActiveTransports int + ActiveBarriers int + CurrentQueueType string +} + +type SnapshotEntry struct { + ID uint64 + Owner string + Mode string + Class APDUClass + Channel int + Scope TransportScope + LeaseType LeaseType + WaitMS int64 + HoldMS int64 +} + +type Snapshot struct { + Active []SnapshotEntry + Queue []SnapshotEntry +} + +type waitKind string + +const ( + waitKindLease waitKind = "lease" + waitKindBarrier waitKind = "barrier" +) + +type waitTicket struct { + id uint64 + owner string + mode string + class APDUClass + channel int + scope TransportScope + leaseType LeaseType + kind waitKind + blocked map[APDUClass]bool + enqueued time.Time +} + +type activeLease struct { + waitTicket + acquiredAt time.Time + expiresAt time.Time + timer *time.Timer +} + +type activeBarrier struct { + waitTicket + acquiredAt time.Time +} + +type Arbiter struct { + // 64 位 atomic 变量必须放在头部 + seq uint64 + + deviceID string + opts Options + + mu sync.Mutex + queue []waitTicket + activeSessions []*activeLease + activeOneshot *activeLease + activeTransports []*activeLease + activeBarriers []*activeBarrier + simAuthReady simAuthReadyState + notifyC chan struct{} + + waitRequests atomic.Uint64 + acquires atomic.Uint64 + waitTimeouts atomic.Uint64 + forcedReleases atomic.Uint64 +} + +type Lease struct { + arbiter *Arbiter + id uint64 + owner string + mode string + class APDUClass + channel int + scope TransportScope + leaseType LeaseType + once sync.Once +} + +type Barrier struct { + arbiter *Arbiter + id uint64 + owner string + mode string + class APDUClass + once sync.Once +} + +func New(deviceID string, opts Options) *Arbiter { + if opts.MaxLeaseHold <= 0 { + opts.MaxLeaseHold = 2 * time.Minute + } + if opts.MaxSessions <= 0 { + opts.MaxSessions = 1 + } + if opts.MaxQMITransports <= 0 { + opts.MaxQMITransports = 1 + } + return &Arbiter{ + deviceID: strings.TrimSpace(deviceID), + opts: opts, + notifyC: make(chan struct{}), + } +} + +func (a *Arbiter) AcquireTransport(ctx context.Context, req Request) (*Lease, error) { + return a.acquire(ctx, normalizeRequest(req, LeaseTypeTransport), LeaseTypeTransport) +} + +func (a *Arbiter) BeginBarrier(ctx context.Context, req Request, policy BarrierPolicy) (*Barrier, error) { + if ctx == nil { + ctx = context.Background() + } + req.Owner = normalizeOwner(req.Owner) + req.Mode = normalizeMode(req.Mode) + if req.Class == "" { + req.Class = APDUClassSwitchBarrier + } + blocked := make(map[APDUClass]bool) + for _, class := range policy.BlockedClasses { + class = normalizeClass(class, LeaseTypeOneShot) + if class != "" { + blocked[class] = true + } + } + if len(blocked) == 0 { + blocked[APDUClassUSIMAKA] = true + blocked[APDUClassSMSC] = true + } + + ticket := waitTicket{ + id: atomic.AddUint64(&a.seq, 1), + owner: req.Owner, + mode: req.Mode, + class: req.Class, + channel: req.Channel, + scope: TransportScopeExclusive, + leaseType: LeaseTypeBarrier, + kind: waitKindBarrier, + blocked: blocked, + enqueued: time.Now(), + } + + a.mu.Lock() + a.queue = append(a.queue, ticket) + a.waitRequests.Add(1) + a.logEvent(ticket, "barrier_wait", len(a.queue), 0, 0, "") + a.signalLocked() + + for { + if a.canAcquireBarrierLocked(ticket) { + a.removeTicketLocked(ticket.id) + a.activeBarriers = append(a.activeBarriers, &activeBarrier{ + waitTicket: ticket, + acquiredAt: time.Now(), + }) + a.acquires.Add(1) + waitMs := time.Since(ticket.enqueued).Milliseconds() + a.logEvent(ticket, "barrier_enter", len(a.queue), waitMs, 0, "") + a.signalLocked() + a.mu.Unlock() + return &Barrier{ + arbiter: a, + id: ticket.id, + owner: ticket.owner, + mode: ticket.mode, + class: ticket.class, + }, nil + } + + waitC := a.notifyC + a.mu.Unlock() + select { + case <-ctx.Done(): + a.mu.Lock() + if a.removeTicketLocked(ticket.id) { + a.waitTimeouts.Add(1) + a.logEvent(ticket, "timeout", len(a.queue), time.Since(ticket.enqueued).Milliseconds(), 0, ctx.Err().Error()) + a.signalLocked() + } + a.mu.Unlock() + return nil, fmt.Errorf("%w: barrier owner=%s mode=%s class=%s: %v", ErrAPDUBusy, ticket.owner, ticket.mode, ticket.class, ctx.Err()) + case <-waitC: + a.mu.Lock() + } + } +} + +func (a *Arbiter) AcquireSession(ctx context.Context, owner, mode string) (*Lease, error) { + return a.acquire(ctx, Request{Owner: owner, Mode: mode}, LeaseTypeSession) +} + +func (a *Arbiter) AcquireOneShot(ctx context.Context, owner, mode string) (*Lease, error) { + return a.acquire(ctx, Request{Owner: owner, Mode: mode}, LeaseTypeOneShot) +} + +func (a *Arbiter) WaitIdle(ctx context.Context) error { + if ctx == nil { + ctx = context.Background() + } + for { + a.mu.Lock() + idle := a.isIdleLocked() + waitC := a.notifyC + a.mu.Unlock() + if idle { + return nil + } + select { + case <-ctx.Done(): + return fmt.Errorf("%w: wait idle: %v", ErrAPDUBusy, ctx.Err()) + case <-waitC: + } + } +} + +func (a *Arbiter) IsIdle() bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.isIdleLocked() +} + +func (a *Arbiter) Stats() Stats { + a.mu.Lock() + defer a.mu.Unlock() + queueType := "" + if len(a.queue) > 0 { + queueType = string(a.queue[0].kind) + } + return Stats{ + WaitRequests: a.waitRequests.Load(), + Acquires: a.acquires.Load(), + WaitTimeouts: a.waitTimeouts.Load(), + ForcedReleases: a.forcedReleases.Load(), + CurrentQueue: len(a.queue), + ActiveSessions: len(a.activeSessions), + ActiveOneshot: a.activeOneshot != nil, + ActiveTransport: len(a.activeTransports) > 0, + ActiveTransports: len(a.activeTransports), + ActiveBarriers: len(a.activeBarriers), + CurrentQueueType: queueType, + } +} + +func (a *Arbiter) Snapshot() Snapshot { + a.mu.Lock() + defer a.mu.Unlock() + + now := time.Now() + active := make([]SnapshotEntry, 0, len(a.activeSessions)+len(a.activeTransports)+len(a.activeBarriers)+1) + for _, session := range a.activeSessions { + active = append(active, snapshotActiveLease(session, now)) + } + if a.activeOneshot != nil { + active = append(active, snapshotActiveLease(a.activeOneshot, now)) + } + for _, transport := range a.activeTransports { + active = append(active, snapshotActiveLease(transport, now)) + } + for _, barrier := range a.activeBarriers { + active = append(active, SnapshotEntry{ + ID: barrier.id, + Owner: barrier.owner, + Mode: barrier.mode, + Class: barrier.class, + Channel: barrier.channel, + Scope: barrier.scope, + LeaseType: LeaseTypeBarrier, + HoldMS: now.Sub(barrier.acquiredAt).Milliseconds(), + }) + } + queue := make([]SnapshotEntry, 0, len(a.queue)) + for _, ticket := range a.queue { + queue = append(queue, SnapshotEntry{ + ID: ticket.id, + Owner: ticket.owner, + Mode: ticket.mode, + Class: ticket.class, + Channel: ticket.channel, + Scope: ticket.scope, + LeaseType: ticket.leaseType, + WaitMS: now.Sub(ticket.enqueued).Milliseconds(), + }) + } + return Snapshot{Active: active, Queue: queue} +} + +func (l *Lease) Touch() bool { + if l == nil || l.arbiter == nil { + return false + } + return l.arbiter.touch(l.id, l.leaseType) +} + +func (l *Lease) Active() bool { + if l == nil || l.arbiter == nil { + return false + } + return l.arbiter.isActive(l.id, l.leaseType) +} + +func (l *Lease) Release() { + if l == nil || l.arbiter == nil { + return + } + l.once.Do(func() { + l.arbiter.release(l.id, l.leaseType, "release") + }) +} + +func (b *Barrier) Release() { + if b == nil || b.arbiter == nil { + return + } + b.once.Do(func() { + b.arbiter.releaseBarrier(b.id) + }) +} + +func (a *Arbiter) acquire(ctx context.Context, req Request, leaseType LeaseType) (*Lease, error) { + if ctx == nil { + ctx = context.Background() + } + req = normalizeRequest(req, leaseType) + ticket := waitTicket{ + id: atomic.AddUint64(&a.seq, 1), + owner: req.Owner, + mode: req.Mode, + class: req.Class, + channel: req.Channel, + scope: req.Scope, + leaseType: leaseType, + kind: waitKindLease, + enqueued: time.Now(), + } + + a.mu.Lock() + a.queue = append(a.queue, ticket) + a.waitRequests.Add(1) + a.logEvent(ticket, "wait", len(a.queue), 0, 0, "") + a.signalLocked() + + for { + if a.canAcquireLeaseLocked(ticket) { + a.removeTicketLocked(ticket.id) + active := &activeLease{ + waitTicket: ticket, + acquiredAt: time.Now(), + } + if a.opts.MaxLeaseHold > 0 { + active.expiresAt = active.acquiredAt.Add(a.opts.MaxLeaseHold) + leaseID := ticket.id + lType := leaseType + active.timer = time.AfterFunc(a.opts.MaxLeaseHold, func() { + a.releaseExpired(leaseID, lType) + }) + } + a.addActiveLocked(active) + a.acquires.Add(1) + waitMs := time.Since(ticket.enqueued).Milliseconds() + a.logEvent(ticket, "acquire", len(a.queue), waitMs, 0, "") + a.signalLocked() + a.mu.Unlock() + return &Lease{ + arbiter: a, + id: ticket.id, + owner: ticket.owner, + mode: ticket.mode, + class: ticket.class, + channel: ticket.channel, + scope: ticket.scope, + leaseType: leaseType, + }, nil + } + + waitC := a.notifyC + a.mu.Unlock() + select { + case <-ctx.Done(): + a.mu.Lock() + if a.removeTicketLocked(ticket.id) { + a.waitTimeouts.Add(1) + a.logEvent(ticket, "timeout", len(a.queue), time.Since(ticket.enqueued).Milliseconds(), 0, ctx.Err().Error()) + a.signalLocked() + } + a.mu.Unlock() + return nil, fmt.Errorf("%w: owner=%s mode=%s class=%s channel=%d: %v", ErrAPDUBusy, ticket.owner, ticket.mode, ticket.class, ticket.channel, ctx.Err()) + case <-waitC: + a.mu.Lock() + } + } +} + +func (a *Arbiter) canAcquireLeaseLocked(ticket waitTicket) bool { + if ticket.kind != waitKindLease { + return false + } + if a.isBlockedByActiveBarrierLocked(ticket.class) { + return false + } + if a.hasPendingBarrierAheadLocked(ticket) { + return false + } + + switch ticket.leaseType { + case LeaseTypeSession: + return a.queueHeadIsLocked(ticket.id) && a.activeOneshot == nil && !a.hasActiveTransportLocked() && len(a.activeSessions) < a.opts.MaxSessions + case LeaseTypeOneShot: + return a.queueHeadIsLocked(ticket.id) && len(a.activeSessions) == 0 && a.activeOneshot == nil && !a.hasActiveTransportLocked() + case LeaseTypeTransport: + if len(a.activeSessions) > 0 || a.activeOneshot != nil { + return false + } + return a.selectedTransportLocked() == ticket.id + default: + return false + } +} + +func (a *Arbiter) canAcquireBarrierLocked(ticket waitTicket) bool { + if ticket.kind != waitKindBarrier { + return false + } + if a.hasActiveTransportLocked() || len(a.activeSessions) > 0 || a.activeOneshot != nil { + return false + } + return a.selectedBarrierLocked() == ticket.id +} + +func (a *Arbiter) selectedBarrierLocked() uint64 { + for _, ticket := range a.queue { + if ticket.kind == waitKindBarrier { + return ticket.id + } + } + return 0 +} + +func (a *Arbiter) selectedTransportLocked() uint64 { + var oldestEligible *waitTicket + var oldestAgedNonAKA *waitTicket + var oldestAKA *waitTicket + now := time.Now() + for i := range a.queue { + ticket := &a.queue[i] + if ticket.kind == waitKindBarrier { + break + } + if ticket.leaseType != LeaseTypeTransport { + break + } + if a.isBlockedByActiveBarrierLocked(ticket.class) { + continue + } + if !a.canAcquireTransportNowLocked(*ticket) { + if a.transportWaitGatesQueueLocked(*ticket) { + break + } + continue + } + if oldestEligible == nil { + oldestEligible = ticket + } + if ticket.class == APDUClassUSIMAKA { + if oldestAKA == nil { + oldestAKA = ticket + } + continue + } + if oldestAgedNonAKA == nil && now.Sub(ticket.enqueued) >= transportPriorityAging { + oldestAgedNonAKA = ticket + } + } + switch { + case oldestAgedNonAKA != nil: + return oldestAgedNonAKA.id + case oldestAKA != nil: + return oldestAKA.id + case oldestEligible != nil: + return oldestEligible.id + default: + return 0 + } +} + +func (a *Arbiter) canAcquireTransportNowLocked(ticket waitTicket) bool { + if ticket.leaseType != LeaseTypeTransport { + return false + } + if ticket.scope != TransportScopeQMIChannel { + return !a.hasActiveTransportLocked() + } + if a.hasActiveExclusiveTransportLocked() { + return false + } + if a.activeQMITransportCountLocked() >= a.opts.MaxQMITransports { + return false + } + return !a.hasActiveTransportOnChannelLocked(ticket.channel) +} + +func (a *Arbiter) transportWaitGatesQueueLocked(ticket waitTicket) bool { + if ticket.leaseType != LeaseTypeTransport { + return true + } + if ticket.scope != TransportScopeQMIChannel { + return true + } + if a.hasActiveExclusiveTransportLocked() || a.activeQMITransportCountLocked() >= a.opts.MaxQMITransports { + return true + } + return false +} + +func (a *Arbiter) hasPendingBarrierAheadLocked(ticket waitTicket) bool { + for _, queued := range a.queue { + if queued.id == ticket.id { + return false + } + if queued.kind != waitKindBarrier { + continue + } + if queued.blocked[ticket.class] { + return true + } + } + return false +} + +func (a *Arbiter) isBlockedByActiveBarrierLocked(class APDUClass) bool { + for _, barrier := range a.activeBarriers { + if barrier.blocked[class] { + return true + } + } + return false +} + +func (a *Arbiter) queueHeadIsLocked(ticketID uint64) bool { + return len(a.queue) > 0 && a.queue[0].id == ticketID +} + +func (a *Arbiter) addActiveLocked(active *activeLease) { + switch active.leaseType { + case LeaseTypeSession: + a.activeSessions = append(a.activeSessions, active) + case LeaseTypeOneShot: + a.activeOneshot = active + case LeaseTypeTransport: + a.activeTransports = append(a.activeTransports, active) + } +} + +func (a *Arbiter) touch(leaseID uint64, leaseType LeaseType) bool { + if a.opts.MaxLeaseHold <= 0 { + return a.isActive(leaseID, leaseType) + } + + a.mu.Lock() + defer a.mu.Unlock() + + active := a.findActiveLocked(leaseID, leaseType) + if active == nil { + return false + } + active.expiresAt = time.Now().Add(a.opts.MaxLeaseHold) + if active.timer == nil { + lType := leaseType + active.timer = time.AfterFunc(a.opts.MaxLeaseHold, func() { + a.releaseExpired(leaseID, lType) + }) + return true + } + active.timer.Reset(a.opts.MaxLeaseHold) + return true +} + +func (a *Arbiter) release(leaseID uint64, leaseType LeaseType, reason string) { + a.mu.Lock() + defer a.mu.Unlock() + + released := a.removeActiveLocked(leaseID, leaseType) + if released == nil { + return + } + if released.timer != nil { + released.timer.Stop() + } + holdMs := time.Since(released.acquiredAt).Milliseconds() + phase := "release" + if reason == "force-timeout" { + phase = "force-release" + a.forcedReleases.Add(1) + } + a.logEvent(released.waitTicket, phase, len(a.queue), 0, holdMs, reason) + a.signalLocked() +} + +func (a *Arbiter) releaseBarrier(barrierID uint64) { + a.mu.Lock() + defer a.mu.Unlock() + + for i, barrier := range a.activeBarriers { + if barrier.id != barrierID { + continue + } + a.activeBarriers = append(a.activeBarriers[:i], a.activeBarriers[i+1:]...) + holdMs := time.Since(barrier.acquiredAt).Milliseconds() + a.logEvent(barrier.waitTicket, "barrier_leave", len(a.queue), 0, holdMs, "") + a.signalLocked() + return + } +} + +func (a *Arbiter) releaseExpired(leaseID uint64, leaseType LeaseType) { + a.mu.Lock() + defer a.mu.Unlock() + + active := a.findActiveLocked(leaseID, leaseType) + if active == nil { + return + } + if !active.expiresAt.IsZero() { + if remaining := time.Until(active.expiresAt); remaining > 0 { + if active.timer != nil { + active.timer.Reset(remaining) + } + return + } + } + + released := a.removeActiveLocked(leaseID, leaseType) + if released == nil { + return + } + if released.timer != nil { + released.timer.Stop() + } + a.forcedReleases.Add(1) + holdMs := time.Since(released.acquiredAt).Milliseconds() + a.logEvent(released.waitTicket, "force-release", len(a.queue), 0, holdMs, "force-timeout") + a.signalLocked() +} + +func (a *Arbiter) isActive(leaseID uint64, leaseType LeaseType) bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.findActiveLocked(leaseID, leaseType) != nil +} + +func (a *Arbiter) findActiveLocked(leaseID uint64, leaseType LeaseType) *activeLease { + switch leaseType { + case LeaseTypeSession: + for _, s := range a.activeSessions { + if s.id == leaseID { + return s + } + } + case LeaseTypeOneShot: + if a.activeOneshot != nil && a.activeOneshot.id == leaseID { + return a.activeOneshot + } + case LeaseTypeTransport: + for _, t := range a.activeTransports { + if t.id == leaseID { + return t + } + } + } + return nil +} + +func (a *Arbiter) removeActiveLocked(leaseID uint64, leaseType LeaseType) *activeLease { + switch leaseType { + case LeaseTypeSession: + for i, s := range a.activeSessions { + if s.id == leaseID { + a.activeSessions = append(a.activeSessions[:i], a.activeSessions[i+1:]...) + return s + } + } + case LeaseTypeOneShot: + if a.activeOneshot != nil && a.activeOneshot.id == leaseID { + released := a.activeOneshot + a.activeOneshot = nil + return released + } + case LeaseTypeTransport: + for i, t := range a.activeTransports { + if t.id == leaseID { + a.activeTransports = append(a.activeTransports[:i], a.activeTransports[i+1:]...) + return t + } + } + } + return nil +} + +func (a *Arbiter) removeTicketLocked(ticketID uint64) bool { + for i := range a.queue { + if a.queue[i].id != ticketID { + continue + } + a.queue = append(a.queue[:i], a.queue[i+1:]...) + return true + } + return false +} + +func (a *Arbiter) isIdleLocked() bool { + return a.activeOneshot == nil && + len(a.activeTransports) == 0 && + len(a.activeSessions) == 0 && + len(a.activeBarriers) == 0 && + len(a.queue) == 0 +} + +func (a *Arbiter) hasActiveTransportLocked() bool { + return len(a.activeTransports) > 0 +} + +func (a *Arbiter) hasActiveExclusiveTransportLocked() bool { + for _, transport := range a.activeTransports { + if transport.scope != TransportScopeQMIChannel { + return true + } + } + return false +} + +func (a *Arbiter) activeQMITransportCountLocked() int { + count := 0 + for _, transport := range a.activeTransports { + if transport.scope == TransportScopeQMIChannel { + count++ + } + } + return count +} + +func (a *Arbiter) hasActiveTransportOnChannelLocked(channel int) bool { + for _, transport := range a.activeTransports { + if transport.scope == TransportScopeQMIChannel && transport.channel == channel { + return true + } + } + return false +} + +func (a *Arbiter) signalLocked() { + close(a.notifyC) + a.notifyC = make(chan struct{}) +} + +func shouldLogEvent(phase string, queueLen int, waitMs int64, holdMs int64) bool { + if phase == "timeout" || phase == "force-release" || strings.HasPrefix(phase, "barrier_") { + return true + } + if waitMs > 0 || holdMs >= 500 || queueLen > 1 { + return true + } + return false +} + +func (a *Arbiter) logEvent(ticket waitTicket, phase string, queueLen int, waitMs int64, holdMs int64, reason string) { + if !shouldLogEvent(phase, queueLen, waitMs, holdMs) { + return + } + + fields := []any{ + "device", a.deviceID, + "owner", ticket.owner, + "mode", ticket.mode, + "class", string(ticket.class), + "channel", ticket.channel, + "scope", string(ticket.scope), + "lease_type", string(ticket.leaseType), + "phase", phase, + "queue_len", queueLen, + "wait_ms", waitMs, + "hold_ms", holdMs, + } + if reason != "" { + fields = append(fields, "reason", reason) + } + switch phase { + case "timeout", "force-release": + logger.Warn("APDU 仲裁事件", fields...) + default: + logger.Debug("APDU 仲裁事件", fields...) + } +} + +func snapshotActiveLease(active *activeLease, now time.Time) SnapshotEntry { + return SnapshotEntry{ + ID: active.id, + Owner: active.owner, + Mode: active.mode, + Class: active.class, + Channel: active.channel, + Scope: active.scope, + LeaseType: active.leaseType, + HoldMS: now.Sub(active.acquiredAt).Milliseconds(), + } +} + +func normalizeRequest(req Request, leaseType LeaseType) Request { + req.Owner = normalizeOwner(req.Owner) + req.Mode = normalizeMode(req.Mode) + req.Class = normalizeClass(req.Class, leaseType) + req.Scope = normalizeTransportScope(req.Scope, req.Mode, req.Channel, leaseType) + return req +} + +func normalizeTransportScope(scope TransportScope, mode string, channel int, leaseType LeaseType) TransportScope { + if leaseType != LeaseTypeTransport { + return TransportScopeExclusive + } + if scope == TransportScopeQMIChannel && mode == "QMI" && channel > 0 { + return TransportScopeQMIChannel + } + return TransportScopeExclusive +} + +func normalizeClass(class APDUClass, leaseType LeaseType) APDUClass { + if class != "" { + return class + } + switch leaseType { + case LeaseTypeTransport: + return APDUClassEUICCWrite + case LeaseTypeOneShot: + return APDUClassUSIMAKA + default: + return APDUClassEUICCWrite + } +} + +func normalizeOwner(owner string) string { + owner = strings.TrimSpace(owner) + if owner == "" { + return "unknown" + } + return owner +} + +func normalizeMode(mode string) string { + mode = strings.ToUpper(strings.TrimSpace(mode)) + if mode == "" { + return "UNKNOWN" + } + return mode +} diff --git a/internal/apduarbiter/arbiter_test.go b/internal/apduarbiter/arbiter_test.go new file mode 100644 index 00000000..c45d6668 --- /dev/null +++ b/internal/apduarbiter/arbiter_test.go @@ -0,0 +1,781 @@ +package apduarbiter + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestArbiterFIFO(t *testing.T) { + arb := New("dev-1", Options{}) + + first, err := arb.AcquireSession(context.Background(), "first", "AT") + if err != nil { + t.Fatalf("AcquireSession(first) failed: %v", err) + } + defer first.Release() + + order := make(chan string, 2) + var wg sync.WaitGroup + wg.Add(2) + + go func() { + defer wg.Done() + lease, acquireErr := arb.AcquireSession(context.Background(), "second", "AT") + if acquireErr != nil { + t.Errorf("AcquireSession(second) failed: %v", acquireErr) + return + } + order <- "second" + lease.Release() + }() + + time.Sleep(20 * time.Millisecond) + + go func() { + defer wg.Done() + lease, acquireErr := arb.AcquireSession(context.Background(), "third", "AT") + if acquireErr != nil { + t.Errorf("AcquireSession(third) failed: %v", acquireErr) + return + } + order <- "third" + lease.Release() + }() + + time.Sleep(80 * time.Millisecond) + first.Release() + wg.Wait() + close(order) + + got := make([]string, 0, 2) + for entry := range order { + got = append(got, entry) + } + if len(got) != 2 { + t.Fatalf("unexpected order length: %d", len(got)) + } + if got[0] != "second" || got[1] != "third" { + t.Fatalf("unexpected FIFO order: %v", got) + } +} + +func TestArbiterTimeout(t *testing.T) { + arb := New("dev-1", Options{}) + + lease, err := arb.AcquireSession(context.Background(), "holder", "QMI") + if err != nil { + t.Fatalf("AcquireSession(holder) failed: %v", err) + } + defer lease.Release() + + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + _, err = arb.AcquireSession(ctx, "waiter", "QMI") + if err == nil { + t.Fatal("expected timeout error, got nil") + } + if !errors.Is(err, ErrAPDUBusy) { + t.Fatalf("expected ErrAPDUBusy, got %v", err) + } +} + +func TestArbiterWaitIdle(t *testing.T) { + arb := New("dev-1", Options{}) + lease, err := arb.AcquireSession(context.Background(), "holder", "AT") + if err != nil { + t.Fatalf("AcquireSession(holder) failed: %v", err) + } + + done := make(chan struct{}) + go func() { + defer close(done) + time.Sleep(60 * time.Millisecond) + lease.Release() + }() + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err := arb.WaitIdle(ctx); err != nil { + t.Fatalf("WaitIdle failed: %v", err) + } + <-done +} + +func TestTransportUSIMAKAAcquiresBetweenEUICCTransports(t *testing.T) { + arb := New("dev-1", Options{}) + first, err := arb.AcquireTransport(context.Background(), Request{ + Owner: "download", + Mode: "QMI", + Class: APDUClassEUICCWrite, + }) + if err != nil { + t.Fatalf("AcquireTransport(first) error=%v", err) + } + + order := make(chan string, 2) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + go func() { + lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "download-next", Mode: "QMI", Class: APDUClassEUICCWrite}) + if acquireErr != nil { + t.Errorf("AcquireTransport(euicc) error=%v", acquireErr) + return + } + order <- "euicc" + lease.Release() + }() + time.Sleep(20 * time.Millisecond) + go func() { + lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "vowifi_aka", Mode: "QMI", Class: APDUClassUSIMAKA}) + if acquireErr != nil { + t.Errorf("AcquireTransport(aka) error=%v", acquireErr) + return + } + order <- "aka" + lease.Release() + }() + + time.Sleep(40 * time.Millisecond) + first.Release() + select { + case got := <-order: + if got != "aka" { + t.Fatalf("first acquired transport=%q want aka", got) + } + case <-time.After(time.Second): + t.Fatal("timed out waiting for first transport") + } + select { + case got := <-order: + if got != "euicc" { + t.Fatalf("second acquired transport=%q want euicc", got) + } + case <-time.After(time.Second): + t.Fatal("timed out waiting for second transport") + } +} + +func TestTransportPriorityAgingPreventsEUICCStarvation(t *testing.T) { + arb := New("dev-1", Options{}) + first, err := arb.AcquireTransport(context.Background(), Request{ + Owner: "holder", + Mode: "QMI", + Class: APDUClassEUICCWrite, + }) + if err != nil { + t.Fatalf("AcquireTransport(first) error=%v", err) + } + + order := make(chan string, 2) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + go func() { + lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "aged-euicc", Mode: "QMI", Class: APDUClassEUICCWrite}) + if acquireErr != nil { + t.Errorf("AcquireTransport(euicc) error=%v", acquireErr) + return + } + order <- "euicc" + lease.Release() + }() + time.Sleep(transportPriorityAging + 80*time.Millisecond) + go func() { + lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "vowifi_aka", Mode: "QMI", Class: APDUClassUSIMAKA}) + if acquireErr != nil { + t.Errorf("AcquireTransport(aka) error=%v", acquireErr) + return + } + order <- "aka" + lease.Release() + }() + + time.Sleep(40 * time.Millisecond) + first.Release() + select { + case got := <-order: + if got != "euicc" { + t.Fatalf("first acquired transport=%q want euicc", got) + } + case <-time.After(time.Second): + t.Fatal("timed out waiting for first transport") + } +} + +func TestQMIChannelTransportsAcquireConcurrentlyAcrossChannels(t *testing.T) { + arb := New("dev-1", Options{MaxQMITransports: 3}) + first, err := arb.AcquireTransport(context.Background(), Request{ + Owner: "profile-a", + Mode: "QMI", + Class: APDUClassEUICCWrite, + Channel: 2, + Scope: TransportScopeQMIChannel, + }) + if err != nil { + t.Fatalf("AcquireTransport(first) error=%v", err) + } + defer first.Release() + + ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel() + second, err := arb.AcquireTransport(ctx, Request{ + Owner: "profile-b", + Mode: "QMI", + Class: APDUClassEUICCWrite, + Channel: 3, + Scope: TransportScopeQMIChannel, + }) + if err != nil { + t.Fatalf("AcquireTransport(second different channel) error=%v", err) + } + defer second.Release() + + if stats := arb.Stats(); stats.ActiveTransports != 2 { + t.Fatalf("ActiveTransports=%d want 2: %+v", stats.ActiveTransports, stats) + } +} + +func TestQMIChannelTransportSerializesSameChannel(t *testing.T) { + arb := New("dev-1", Options{MaxQMITransports: 3}) + first, err := arb.AcquireTransport(context.Background(), Request{ + Owner: "profile-a", + Mode: "QMI", + Class: APDUClassEUICCWrite, + Channel: 2, + Scope: TransportScopeQMIChannel, + }) + if err != nil { + t.Fatalf("AcquireTransport(first) error=%v", err) + } + defer first.Release() + + acquired := make(chan struct{}) + done := make(chan struct{}) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + go func() { + defer close(done) + lease, acquireErr := arb.AcquireTransport(ctx, Request{ + Owner: "profile-a-next", + Mode: "QMI", + Class: APDUClassEUICCWrite, + Channel: 2, + Scope: TransportScopeQMIChannel, + }) + if acquireErr != nil { + t.Errorf("AcquireTransport(waiter) error=%v", acquireErr) + return + } + close(acquired) + lease.Release() + }() + + select { + case <-acquired: + t.Fatal("same-channel QMI transport acquired while channel was active") + case <-time.After(80 * time.Millisecond): + } + + first.Release() + select { + case <-acquired: + case <-time.After(time.Second): + t.Fatal("same-channel QMI transport did not acquire after release") + } + <-done +} + +func TestExclusiveTransportWaitsForActiveQMIChannelTransport(t *testing.T) { + arb := New("dev-1", Options{MaxQMITransports: 3}) + first, err := arb.AcquireTransport(context.Background(), Request{ + Owner: "profile-a", + Mode: "QMI", + Class: APDUClassEUICCWrite, + Channel: 2, + Scope: TransportScopeQMIChannel, + }) + if err != nil { + t.Fatalf("AcquireTransport(first) error=%v", err) + } + defer first.Release() + + acquired := make(chan struct{}) + done := make(chan struct{}) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + go func() { + defer close(done) + lease, acquireErr := arb.AcquireTransport(ctx, Request{ + Owner: "qmi_channel_close", + Mode: "QMI", + Class: APDUClassRecovery, + Channel: 2, + }) + if acquireErr != nil { + t.Errorf("AcquireTransport(exclusive) error=%v", acquireErr) + return + } + close(acquired) + lease.Release() + }() + + select { + case <-acquired: + t.Fatal("exclusive transport acquired while QMI channel transport was active") + case <-time.After(80 * time.Millisecond): + } + + first.Release() + select { + case <-acquired: + case <-time.After(time.Second): + t.Fatal("exclusive transport did not acquire after active QMI transport release") + } + <-done +} + +func TestQueuedExclusiveTransportGatesLaterQMIChannelTransport(t *testing.T) { + arb := New("dev-1", Options{MaxQMITransports: 3}) + first, err := arb.AcquireTransport(context.Background(), Request{ + Owner: "profile-a", + Mode: "QMI", + Class: APDUClassEUICCWrite, + Channel: 2, + Scope: TransportScopeQMIChannel, + }) + if err != nil { + t.Fatalf("AcquireTransport(first) error=%v", err) + } + defer first.Release() + + exclusiveAcquired := make(chan struct{}) + releaseExclusive := make(chan struct{}) + exclusiveDone := make(chan struct{}) + qmiAcquired := make(chan struct{}) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + go func() { + defer close(exclusiveDone) + lease, acquireErr := arb.AcquireTransport(ctx, Request{ + Owner: "qmi_channel_close", + Mode: "QMI", + Class: APDUClassRecovery, + Channel: 2, + }) + if acquireErr != nil { + t.Errorf("AcquireTransport(exclusive) error=%v", acquireErr) + return + } + close(exclusiveAcquired) + <-releaseExclusive + lease.Release() + }() + + time.Sleep(20 * time.Millisecond) + go func() { + lease, acquireErr := arb.AcquireTransport(ctx, Request{ + Owner: "profile-b", + Mode: "QMI", + Class: APDUClassEUICCWrite, + Channel: 3, + Scope: TransportScopeQMIChannel, + }) + if acquireErr != nil { + return + } + close(qmiAcquired) + lease.Release() + }() + + select { + case <-qmiAcquired: + t.Fatal("later QMI channel transport passed queued exclusive transport") + case <-time.After(80 * time.Millisecond): + } + + first.Release() + select { + case <-exclusiveAcquired: + case <-time.After(time.Second): + t.Fatal("exclusive transport did not acquire after active QMI transport release") + } + select { + case <-qmiAcquired: + t.Fatal("later QMI channel transport acquired while exclusive transport was active") + case <-time.After(80 * time.Millisecond): + } + close(releaseExclusive) + <-exclusiveDone + select { + case <-qmiAcquired: + case <-time.After(time.Second): + t.Fatal("later QMI channel transport did not acquire after exclusive transport release") + } +} + +func TestSwitchBarrierBlocksUSIMAKAAndAllowsEUICC(t *testing.T) { + arb := New("dev-1", Options{}) + first, err := arb.AcquireTransport(context.Background(), Request{Owner: "holder", Mode: "QMI", Class: APDUClassEUICCWrite}) + if err != nil { + t.Fatalf("AcquireTransport(first) error=%v", err) + } + + barrierCh := make(chan *Barrier, 1) + errCh := make(chan error, 1) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + go func() { + barrier, beginErr := arb.BeginBarrier(ctx, Request{Owner: "switch", Mode: "QMI", Class: APDUClassSwitchBarrier}, BarrierPolicy{}) + if beginErr != nil { + errCh <- beginErr + return + } + barrierCh <- barrier + }() + + waitForQueuedClass(t, arb, APDUClassSwitchBarrier, LeaseTypeBarrier) + + akaAcquired := make(chan struct{}) + go func() { + lease, acquireErr := arb.AcquireTransport(ctx, Request{Owner: "vowifi_aka", Mode: "QMI", Class: APDUClassUSIMAKA}) + if acquireErr != nil { + return + } + close(akaAcquired) + lease.Release() + }() + + first.Release() + var barrier *Barrier + select { + case barrier = <-barrierCh: + case err := <-errCh: + t.Fatalf("BeginBarrier() error=%v", err) + case <-time.After(time.Second): + t.Fatal("timed out waiting for barrier") + } + defer barrier.Release() + + select { + case <-akaAcquired: + t.Fatal("USIMAKA acquired while switch barrier was active") + default: + } + + euicc, err := arb.AcquireTransport(ctx, Request{Owner: "switch-apdu", Mode: "QMI", Class: APDUClassEUICCWrite}) + if err != nil { + t.Fatalf("EUICC transport under barrier error=%v", err) + } + euicc.Release() + select { + case <-akaAcquired: + t.Fatal("USIMAKA acquired after unrelated EUICC transport while barrier active") + default: + } + + barrier.Release() + select { + case <-akaAcquired: + case <-time.After(time.Second): + t.Fatal("USIMAKA did not acquire after barrier release") + } +} + +func waitForQueuedClass(t *testing.T, arb *Arbiter, class APDUClass, leaseType LeaseType) { + t.Helper() + deadline := time.Now().Add(time.Second) + for { + for _, entry := range arb.Snapshot().Queue { + if entry.Class == class && entry.LeaseType == leaseType { + return + } + } + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for queued class=%s lease_type=%s", class, leaseType) + } + time.Sleep(time.Millisecond) + } +} + +func TestSnapshotReportsTransportAndBarrier(t *testing.T) { + arb := New("dev-1", Options{}) + barrier, err := arb.BeginBarrier(context.Background(), Request{Owner: "switch", Mode: "QMI", Class: APDUClassSwitchBarrier}, BarrierPolicy{}) + if err != nil { + t.Fatalf("BeginBarrier() error=%v", err) + } + defer barrier.Release() + + lease, err := arb.AcquireTransport(context.Background(), Request{Owner: "switch-apdu", Mode: "QMI", Class: APDUClassEUICCWrite, Channel: 2}) + if err != nil { + t.Fatalf("AcquireTransport() error=%v", err) + } + defer lease.Release() + + snap := arb.Snapshot() + if len(snap.Active) != 2 { + t.Fatalf("active entries=%d want 2: %+v", len(snap.Active), snap.Active) + } +} + +func TestLeaseTouchExtendsSessionWatchdog(t *testing.T) { + arb := New("dev-1", Options{MaxLeaseHold: 40 * time.Millisecond}) + + lease, err := arb.AcquireSession(context.Background(), "holder", "QMI") + if err != nil { + t.Fatalf("AcquireSession(holder) failed: %v", err) + } + defer lease.Release() + + acquired := make(chan struct{}) + done := make(chan struct{}) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + go func() { + defer close(done) + waiter, acquireErr := arb.AcquireOneShot(ctx, "waiter", "AT") + if acquireErr != nil { + return + } + close(acquired) + waiter.Release() + }() + + deadline := time.After(130 * time.Millisecond) + ticker := time.NewTicker(15 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-ticker.C: + lease.Touch() + case <-deadline: + goto touchedEnough + } + } + +touchedEnough: + select { + case <-acquired: + t.Fatal("oneshot acquired while session lease was being touched") + default: + } + stats := arb.Stats() + if stats.ForcedReleases != 0 { + t.Fatalf("ForcedReleases=%d want 0", stats.ForcedReleases) + } + if stats.ActiveSessions != 1 || stats.ActiveOneshot { + t.Fatalf("unexpected stats after touch: %+v", stats) + } + + lease.Release() + select { + case <-acquired: + case <-time.After(150 * time.Millisecond): + t.Fatal("oneshot did not acquire after session release") + } + <-done +} + +func TestLeaseTouchExtendsOneShotWatchdog(t *testing.T) { + arb := New("dev-1", Options{MaxLeaseHold: 40 * time.Millisecond}) + + lease, err := arb.AcquireOneShot(context.Background(), "holder", "AT") + if err != nil { + t.Fatalf("AcquireOneShot(holder) failed: %v", err) + } + defer lease.Release() + + deadline := time.After(130 * time.Millisecond) + ticker := time.NewTicker(15 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-ticker.C: + lease.Touch() + case <-deadline: + stats := arb.Stats() + if stats.ForcedReleases != 0 { + t.Fatalf("ForcedReleases=%d want 0", stats.ForcedReleases) + } + if !stats.ActiveOneshot || stats.ActiveSessions != 0 { + t.Fatalf("unexpected stats after touch: %+v", stats) + } + return + } + } +} + +func TestLeaseWatchdogForceReleasesWithoutTouch(t *testing.T) { + tests := []struct { + name string + acquire func(*Arbiter) (*Lease, error) + }{ + { + name: "session", + acquire: func(arb *Arbiter) (*Lease, error) { + return arb.AcquireSession(context.Background(), "holder", "QMI") + }, + }, + { + name: "oneshot", + acquire: func(arb *Arbiter) (*Lease, error) { + return arb.AcquireOneShot(context.Background(), "holder", "AT") + }, + }, + { + name: "transport", + acquire: func(arb *Arbiter) (*Lease, error) { + return arb.AcquireTransport(context.Background(), Request{Owner: "holder", Mode: "QMI", Class: APDUClassEUICCWrite}) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + arb := New("dev-1", Options{MaxLeaseHold: 30 * time.Millisecond}) + lease, err := tt.acquire(arb) + if err != nil { + t.Fatalf("acquire failed: %v", err) + } + defer lease.Release() + + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + if err := arb.WaitIdle(ctx); err != nil { + t.Fatalf("WaitIdle() error=%v", err) + } + stats := arb.Stats() + if stats.ForcedReleases != 1 { + t.Fatalf("ForcedReleases=%d want 1", stats.ForcedReleases) + } + if stats.ActiveSessions != 0 || stats.ActiveOneshot || stats.ActiveTransport { + t.Fatalf("unexpected active lease stats: %+v", stats) + } + if lease.Active() { + t.Fatal("lease.Active()=true after watchdog force release, want false") + } + if lease.Touch() { + t.Fatal("lease.Touch()=true after watchdog force release, want false") + } + }) + } +} + +func TestShouldLogEvent(t *testing.T) { + tests := []struct { + name string + phase string + queueLen int + waitMs int64 + holdMs int64 + want bool + }{ + {name: "suppress zero wait acquire", phase: "acquire", queueLen: 0, waitMs: 0, holdMs: 0, want: false}, + {name: "suppress short release", phase: "release", queueLen: 0, waitMs: 0, holdMs: 27, want: false}, + {name: "log waited event", phase: "acquire", queueLen: 0, waitMs: 1, holdMs: 0, want: true}, + {name: "suppress ordinary qmi release", phase: "release", queueLen: 0, waitMs: 0, holdMs: 95, want: false}, + {name: "log long hold release", phase: "release", queueLen: 0, waitMs: 0, holdMs: 500, want: true}, + {name: "log deeper queue", phase: "wait", queueLen: 2, waitMs: 0, holdMs: 0, want: true}, + {name: "always log timeout", phase: "timeout", queueLen: 0, waitMs: 0, holdMs: 0, want: true}, + {name: "always log force release", phase: "force-release", queueLen: 0, waitMs: 0, holdMs: 0, want: true}, + {name: "boundary suppress single queued wait", phase: "wait", queueLen: 1, waitMs: 0, holdMs: 0, want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := shouldLogEvent(tt.phase, tt.queueLen, tt.waitMs, tt.holdMs) + if got != tt.want { + t.Fatalf("shouldLogEvent(%q, %d, %d, %d) = %v, want %v", tt.phase, tt.queueLen, tt.waitMs, tt.holdMs, got, tt.want) + } + }) + } +} + +func TestSIMAuthReadyGateCoalescesConcurrentProbes(t *testing.T) { + arb := New("dev-1", Options{}) + started := make(chan struct{}, 1) + release := make(chan struct{}) + errs := make(chan error, 2) + var probes atomic.Int32 + + probe := func(ctx context.Context) error { + probes.Add(1) + select { + case started <- struct{}{}: + default: + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-release: + return nil + } + } + + for i := 0; i < 2; i++ { + go func() { + errs <- arb.WaitSIMAuthReady(context.Background(), probe) + }() + } + + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("SIMAuth probe did not start") + } + time.Sleep(20 * time.Millisecond) + close(release) + + for i := 0; i < 2; i++ { + select { + case err := <-errs: + if err != nil { + t.Fatalf("WaitSIMAuthReady() error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("WaitSIMAuthReady() did not return") + } + } + if got := probes.Load(); got != 1 { + t.Fatalf("probe count=%d want 1", got) + } + + if err := arb.WaitSIMAuthReady(context.Background(), func(context.Context) error { + probes.Add(1) + return nil + }); err != nil { + t.Fatalf("cached WaitSIMAuthReady() error=%v", err) + } + if got := probes.Load(); got != 1 { + t.Fatalf("probe count after cached wait=%d want 1", got) + } +} + +func TestSIMAuthReadyGateInvalidationForcesNewProbe(t *testing.T) { + arb := New("dev-1", Options{}) + var probes atomic.Int32 + probe := func(context.Context) error { + probes.Add(1) + return nil + } + + if err := arb.WaitSIMAuthReady(context.Background(), probe); err != nil { + t.Fatalf("first WaitSIMAuthReady() error=%v", err) + } + if err := arb.WaitSIMAuthReady(context.Background(), probe); err != nil { + t.Fatalf("cached WaitSIMAuthReady() error=%v", err) + } + if got := probes.Load(); got != 1 { + t.Fatalf("probe count before invalidate=%d want 1", got) + } + + arb.InvalidateSIMAuthReady("switch") + if err := arb.WaitSIMAuthReady(context.Background(), probe); err != nil { + t.Fatalf("post-invalidate WaitSIMAuthReady() error=%v", err) + } + if got := probes.Load(); got != 2 { + t.Fatalf("probe count after invalidate=%d want 2", got) + } +} diff --git a/internal/apduarbiter/simauth_ready.go b/internal/apduarbiter/simauth_ready.go new file mode 100644 index 00000000..74fc9731 --- /dev/null +++ b/internal/apduarbiter/simauth_ready.go @@ -0,0 +1,115 @@ +package apduarbiter + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/iniwex5/vohive/pkg/logger" +) + +var ErrSIMAuthNotReady = errors.New("simauth not ready") + +type SIMAuthReadyProbe func(context.Context) error + +type simAuthReadyState struct { + generation uint64 + ready bool + probing bool + waitC chan struct{} + lastErr error + reason string +} + +func (a *Arbiter) InvalidateSIMAuthReady(reason string) { + if a == nil { + return + } + reason = strings.TrimSpace(reason) + if reason == "" { + reason = "unknown" + } + + a.mu.Lock() + a.simAuthReady.generation++ + a.simAuthReady.ready = false + a.simAuthReady.lastErr = nil + a.simAuthReady.reason = reason + generation := a.simAuthReady.generation + probing := a.simAuthReady.probing + a.mu.Unlock() + + logger.Debug("SIMAuth readiness invalidated", + "device", a.deviceID, + "reason", reason, + "generation", generation, + "probing", probing) +} + +func (a *Arbiter) WaitSIMAuthReady(ctx context.Context, probe SIMAuthReadyProbe) error { + if a == nil { + return fmt.Errorf("%w: arbiter nil", ErrSIMAuthNotReady) + } + if probe == nil { + return fmt.Errorf("%w: probe nil", ErrSIMAuthNotReady) + } + if ctx == nil { + ctx = context.Background() + } + + for { + if err := ctx.Err(); err != nil { + return fmt.Errorf("%w: %v", ErrSIMAuthNotReady, err) + } + + a.mu.Lock() + if a.simAuthReady.ready { + a.mu.Unlock() + return nil + } + if a.simAuthReady.probing { + waitC := a.simAuthReady.waitC + if waitC == nil { + waitC = make(chan struct{}) + a.simAuthReady.waitC = waitC + } + a.mu.Unlock() + select { + case <-ctx.Done(): + return fmt.Errorf("%w: %v", ErrSIMAuthNotReady, ctx.Err()) + case <-waitC: + continue + } + } + + generation := a.simAuthReady.generation + waitC := make(chan struct{}) + a.simAuthReady.probing = true + a.simAuthReady.waitC = waitC + a.mu.Unlock() + + err := probe(ctx) + + a.mu.Lock() + stale := a.simAuthReady.generation != generation + if !stale { + a.simAuthReady.ready = err == nil + a.simAuthReady.lastErr = err + } + if a.simAuthReady.waitC == waitC { + close(waitC) + a.simAuthReady.waitC = nil + } + a.simAuthReady.probing = false + a.mu.Unlock() + + if err != nil { + return fmt.Errorf("%w: %v", ErrSIMAuthNotReady, err) + } + if stale { + continue + } + return nil + } +} diff --git a/internal/api/auth_security_test.go b/internal/api/auth_security_test.go new file mode 100644 index 00000000..385830d6 --- /dev/null +++ b/internal/api/auth_security_test.go @@ -0,0 +1,64 @@ +package api + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/config" +) + +// 登录限流必须按真实客户端 IP 计数,而不是按客户端可随意伪造的 +// X-Forwarded-For 头计数,否则暴力破解限流形同虚设。 +func TestLoginRateLimitIgnoresSpoofedForwardedFor(t *testing.T) { + gin.SetMode(gin.TestMode) + s := &Server{ + auth: config.WebConfig{Username: "admin", Password: "correct-horse-battery-staple"}, + loginAttempts: make(map[string]loginAttempt), + } + r := s.newRouter() + + body := `{"username":"admin","password":"wrong"}` + + for i := 0; i < 10; i++ { + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Forwarded-For", fmt.Sprintf("10.0.0.%d", i)) // 每次伪造不同的来源 IP + req.RemoteAddr = "192.0.2.1:54321" // 真实连接对端始终相同 + r.ServeHTTP(w, req) + + if w.Code != http.StatusUnauthorized { + t.Fatalf("attempt %d: code=%d want 401, body=%s", i, w.Code, w.Body.String()) + } + } + + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Forwarded-For", "10.0.0.99") // 第 11 次,依然是新的伪造 IP + req.RemoteAddr = "192.0.2.1:54321" + r.ServeHTTP(w, req) + + if w.Code != http.StatusTooManyRequests { + t.Fatalf("11th attempt: code=%d want 429 —— 限流应按真实 RemoteAddr 计数,不应被伪造的 X-Forwarded-For 绕过, body=%s", w.Code, w.Body.String()) + } +} + +func TestCheckPasswordPlaintextFallbackStillMatchesCorrectly(t *testing.T) { + if !checkPassword("plain-secret", "plain-secret") { + t.Fatal("相同的明文密码应当匹配") + } + if checkPassword("plain-secret", "wrong-secret") { + t.Fatal("不同明文密码不应匹配") + } + if checkPassword("plain-secret", "plain-secre") { + t.Fatal("长度不同的明文密码不应匹配") + } + if checkPassword("plain-secret", "") { + t.Fatal("空密码不应匹配非空存储密码") + } +} diff --git a/internal/api/card_policy.go b/internal/api/card_policy.go new file mode 100644 index 00000000..cedd36ad --- /dev/null +++ b/internal/api/card_policy.go @@ -0,0 +1,106 @@ +package api + +import ( + "errors" + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/db" +) + +// patchCardPolicyForDevice 解析设备当前 ICCID,对 card_policies 行执行原地修改并落库。 +// mutate 在 resolve 后的副本上改字段(source 会被强制为 "user")。 +// applied=false 且 err=nil 表示设备当前无 ICCID(离线/未识别),跳过落库。 +func (s *Server) patchCardPolicyForDevice(deviceID string, mutate func(*db.CardPolicy)) (iccid string, applied bool, err error) { + worker := s.pool.GetWorker(deviceID) + if worker == nil { + return "", false, fmt.Errorf("设备未找到") + } + iccid = worker.CurrentICCID() + if iccid == "" { + return "", false, nil + } + p, err := db.ResolveCardPolicy(iccid) + if err != nil { + return iccid, false, fmt.Errorf("获取卡策略失败: %w", err) + } + mutate(&p) + p.Source = "user" + db.NormalizeCardPolicy(&p) + if err := db.UpsertCardPolicy(p); err != nil { + return iccid, false, fmt.Errorf("保存卡策略失败: %w", err) + } + return iccid, true, nil +} + +func (s *Server) handleGetCardPolicy(c *gin.Context) { + iccid := c.Param("iccid") + pol, err := db.GetCardPolicy(iccid) + if errors.Is(err, db.ErrCardPolicyNotFound) { + // 未建档则返回默认模板(不落库,读端点保持只读语义) + c.JSON(http.StatusOK, db.DefaultCardPolicy(iccid)) + return + } + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, pol) +} + +func (s *Server) handleListCardPolicies(c *gin.Context) { + var out []db.CardPolicy + if db.DB != nil { + if err := db.DB.Order("updated_at desc").Find(&out).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + c.JSON(http.StatusOK, gin.H{"policies": out}) +} + +func (s *Server) handlePutCardPolicy(c *gin.Context) { + iccid := c.Param("iccid") + var req struct { + NetworkEnabled *bool `json:"network_enabled"` + VoWiFiEnabled *bool `json:"vowifi_enabled"` + AirplaneEnabled *bool `json:"airplane_enabled"` + IPVersion string `json:"ip_version"` + APN string `json:"apn"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // 查出当前策略(查不到则用默认值) + pol, err := db.GetCardPolicy(iccid) + if err != nil { + pol = db.DefaultCardPolicy(iccid) + } + + if req.NetworkEnabled != nil { + pol.NetworkEnabled = *req.NetworkEnabled + } + if req.VoWiFiEnabled != nil { + pol.VoWiFiEnabled = *req.VoWiFiEnabled + } + if req.AirplaneEnabled != nil { + pol.AirplaneEnabled = *req.AirplaneEnabled + } + if req.IPVersion != "" { + pol.IPVersion = req.IPVersion + } + if req.APN != "" { + pol.APN = req.APN + } + pol.Source = "user" + + if err := db.UpsertCardPolicy(pol); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, pol) +} diff --git a/internal/api/card_policy_test.go b/internal/api/card_policy_test.go new file mode 100644 index 00000000..e3a42c61 --- /dev/null +++ b/internal/api/card_policy_test.go @@ -0,0 +1,274 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "reflect" + "strings" + "testing" + "unsafe" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/db" + "github.com/iniwex5/vohive/internal/device" +) + +// injectWorker 通过 unsafe 反射将 worker 注入到 pool 的内部 workers map, +// 用于无需完整启动流程的测试场景。 +func injectWorker(p *device.Pool, w *device.Worker) { + pv := reflect.ValueOf(p).Elem().FieldByName("workers") + m := reflect.NewAt(pv.Type(), unsafe.Pointer(pv.UnsafeAddr())).Elem() + m.SetMapIndex(reflect.ValueOf(w.ID), reflect.ValueOf(w)) +} + +func openTestDB(t *testing.T) { + t.Helper() + if err := db.Init(filepath.Join(t.TempDir(), "test.db")); err != nil { + t.Fatalf("Init() error=%v", err) + } + t.Cleanup(func() { + if db.DB != nil { + if sqlDB, err := db.DB.DB(); err == nil && sqlDB != nil { + _ = sqlDB.Close() + } + } + }) +} + +func TestGetCardPolicyEndpoint(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + _ = db.UpsertCardPolicy(db.CardPolicy{ICCID: "8986004", NetworkEnabled: true, IPVersion: "v4", Source: "user"}) + + s := &Server{} + r := gin.Default() + r.GET("/api/cards/:iccid/policy", s.handleGetCardPolicy) + + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/cards/8986004/policy", nil) + r.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + var got db.CardPolicy + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if !got.NetworkEnabled { + t.Fatalf("payload 错: %+v", got) + } +} + +func TestPutCardPolicyEndpoint(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + s := &Server{ + pool: device.NewPool(&config.Config{}), + } + r := gin.Default() + r.PUT("/api/cards/:iccid/policy", s.handlePutCardPolicy) + + body := `{"network_enabled":true,"vowifi_enabled":true,"ip_version":"v4v6","apn":"ims"}` + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPut, "/api/cards/8986005/policy", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + got, _ := db.GetCardPolicy("8986005") + if !got.NetworkEnabled || !got.VoWiFiEnabled || got.IPVersion != "v4v6" || got.APN != "ims" { + t.Fatalf("未成功更新: %+v", got) + } +} + +// TestPatchCardPolicyForDevice 验证 patchCardPolicyForDevice helper 正确解析 ICCID 并落库。 +func TestPatchCardPolicyForDevice(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "wwan-patch"} + setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986patch001") + injectWorker(p, w) + + s := &Server{pool: p} + iccid, applied, err := s.patchCardPolicyForDevice("wwan-patch", func(pol *db.CardPolicy) { + pol.NetworkEnabled = true + pol.IPVersion = "v4v6" + pol.APN = "ims" + }) + + if err != nil { + t.Fatalf("error=%v", err) + } + if !applied { + t.Fatalf("expected applied=true") + } + if iccid != "8986patch001" { + t.Fatalf("iccid=%q", iccid) + } + got, err := db.GetCardPolicy("8986patch001") + if err != nil { + t.Fatal(err) + } + if !got.NetworkEnabled || got.IPVersion != "v4v6" || got.APN != "ims" { + t.Fatalf("card policy mismatch: %+v", got) + } + if got.Source != "user" { + t.Fatalf("source=%q want user", got.Source) + } +} + +// TestPatchCardPolicyForDeviceNoICCID 验证设备无 ICCID 时 applied=false 且不报错。 +func TestPatchCardPolicyForDeviceNoICCID(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "wwan-nocard"} + // 不设置 ICCID,模拟无卡状态 + injectWorker(p, w) + + s := &Server{pool: p} + iccid, applied, err := s.patchCardPolicyForDevice("wwan-nocard", func(pol *db.CardPolicy) { + pol.NetworkEnabled = true + }) + + if err != nil { + t.Fatalf("error=%v", err) + } + if applied { + t.Fatalf("expected applied=false when no ICCID") + } + if iccid != "" { + t.Fatalf("iccid=%q want empty", iccid) + } +} + +// TestPatchCardPolicyVoWiFiKeepsAirplaneIntent 验证开 VoWiFi 不再强制 airplane=true: +// airplane 反映用户的纯飞行意图,独立于 vowifi。 +func TestPatchCardPolicyVoWiFiKeepsAirplaneIntent(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "wwan-vowifi"} + setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986vowifi01") + injectWorker(p, w) + + s := &Server{pool: p} + // 从在线开 VoWiFi(飞行意图为 false):airplane 应保持 false,不被强制为 true。 + _, _, err := s.patchCardPolicyForDevice("wwan-vowifi", vowifiEnablePolicyMutation) + if err != nil { + t.Fatalf("error=%v", err) + } + got, _ := db.GetCardPolicy("8986vowifi01") + if !got.VoWiFiEnabled || got.AirplaneEnabled { + t.Fatalf("开 VoWiFi 不应强制 airplane=true: vowifi=%v airplane=%v", got.VoWiFiEnabled, got.AirplaneEnabled) + } +} + +// TestVoWiFiToggleCyclePreservesAirplaneIntent 复现并锁定 bug 修复: +// 先开飞行 → 开 VoWiFi → 关 VoWiFi,应回退到飞行(airplane 意图被保留)。 +func TestVoWiFiToggleCyclePreservesAirplaneIntent(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "wwan-cycle"} + setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986cycle001") + injectWorker(p, w) + s := &Server{pool: p} + + // 1) 用户先开飞行 + if _, _, err := s.patchCardPolicyForDevice("wwan-cycle", func(pol *db.CardPolicy) { + pol.AirplaneEnabled = true + pol.VoWiFiEnabled = false + pol.NetworkEnabled = false + }); err != nil { + t.Fatalf("开飞行 error=%v", err) + } + + // 2) 开 VoWiFi(落库副作用:只置 vowifi) + if _, _, err := s.patchCardPolicyForDevice("wwan-cycle", vowifiEnablePolicyMutation); err != nil { + t.Fatalf("开 vowifi error=%v", err) + } + mid, _ := db.GetCardPolicy("8986cycle001") + if !mid.VoWiFiEnabled || !mid.AirplaneEnabled { + t.Fatalf("开 VoWiFi 期间飞行意图应保留: %+v", mid) + } + + // 3) 关 VoWiFi(落库副作用:只清 vowifi),应回退到飞行 + if _, _, err := s.patchCardPolicyForDevice("wwan-cycle", vowifiDisablePolicyMutation); err != nil { + t.Fatalf("关 vowifi error=%v", err) + } + got, _ := db.GetCardPolicy("8986cycle001") + if got.VoWiFiEnabled || !got.AirplaneEnabled { + t.Fatalf("关 VoWiFi 后应回退到飞行模式: vowifi=%v airplane=%v", got.VoWiFiEnabled, got.AirplaneEnabled) + } +} + +// TestPatchCardPolicyAirplaneMutualExclusion 验证“开飞行模式”落库时与 network/vowifi 互斥 +// (等价于 handleDeviceMgmtSetFlightMode 开飞行时的落库副作用)。 +func TestPatchCardPolicyAirplaneMutualExclusion(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + + // 预置:network 开着、vowifi 开着 + _ = db.UpsertCardPolicy(db.CardPolicy{ICCID: "8986air001", NetworkEnabled: true, VoWiFiEnabled: true, Source: "user"}) + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "wwan-air"} + setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, "8986air001") + injectWorker(p, w) + + s := &Server{pool: p} + // 开飞行:airplane=on,且互斥关 network/vowifi + _, applied, err := s.patchCardPolicyForDevice("wwan-air", func(pol *db.CardPolicy) { + pol.AirplaneEnabled = true + pol.VoWiFiEnabled = false + pol.NetworkEnabled = false + }) + if err != nil || !applied { + t.Fatalf("applied=%v err=%v", applied, err) + } + + got, _ := db.GetCardPolicy("8986air001") + if !got.AirplaneEnabled || got.NetworkEnabled || got.VoWiFiEnabled { + t.Fatalf("开飞行应互斥关 network/vowifi: %+v", got) + } +} + +func TestPutCardPolicyAirplaneField(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + // 预置一行 network=true,验证只 PUT airplane 时 network 不被指针语义覆盖 + _ = db.UpsertCardPolicy(db.CardPolicy{ICCID: "8986air777", NetworkEnabled: true, IPVersion: "v4", Source: "user"}) + + s := &Server{pool: device.NewPool(&config.Config{})} + r := gin.Default() + r.PUT("/api/cards/:iccid/policy", s.handlePutCardPolicy) + + body := `{"airplane_enabled":true}` + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPut, "/api/cards/8986air777/policy", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + got, _ := db.GetCardPolicy("8986air777") + if !got.AirplaneEnabled { + t.Fatalf("airplane 未写入: %+v", got) + } + if !got.NetworkEnabled { + t.Fatalf("未传的 network 被错误覆盖: %+v", got) + } +} diff --git a/internal/api/device_e911.go b/internal/api/device_e911.go new file mode 100644 index 00000000..5fd3eb37 --- /dev/null +++ b/internal/api/device_e911.go @@ -0,0 +1,54 @@ +package api + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/e911" +) + +func e911ErrorStatus(err error) int { + switch { + case errors.Is(err, e911.ErrNotSupported), errors.Is(err, e911.ErrProviderUnavailable): + return http.StatusBadRequest + case errors.Is(err, e911.ErrIdentityUnavailable): + return http.StatusConflict + case errors.Is(err, e911.ErrChallengeIncomplete): + return http.StatusNotImplemented + case errors.Is(err, e911.ErrCarrierWebsheetAbsent): + return http.StatusBadGateway + default: + return http.StatusInternalServerError + } +} + +func e911ErrorCode(err error) string { + switch { + case errors.Is(err, e911.ErrNotSupported): + return "e911_not_supported" + case errors.Is(err, e911.ErrIdentityUnavailable): + return "e911_identity_unavailable" + case errors.Is(err, e911.ErrProviderUnavailable): + return "e911_provider_unavailable" + case errors.Is(err, e911.ErrChallengeIncomplete): + return "e911_challenge_not_implemented" + case errors.Is(err, e911.ErrCarrierWebsheetAbsent): + return "e911_websheet_unavailable" + default: + return "e911_start_failed" + } +} + +func (s *Server) handleDeviceE911Websheet(c *gin.Context) { + coord := &e911.Coordinator{ + Pool: s.pool, + Websheets: s.websheets, + } + info, err := coord.StartWebsheet(c.Request.Context(), deviceIDParam(c)) + if err != nil { + c.JSON(e911ErrorStatus(err), gin.H{"status": "error", "code": e911ErrorCode(err), "message": err.Error()}) + return + } + c.JSON(http.StatusCreated, info) +} diff --git a/internal/api/device_e911_test.go b/internal/api/device_e911_test.go new file mode 100644 index 00000000..76d6faf3 --- /dev/null +++ b/internal/api/device_e911_test.go @@ -0,0 +1,28 @@ +package api + +import ( + "errors" + "net/http" + "testing" + + "github.com/iniwex5/vohive/internal/e911" +) + +func TestE911ErrorStatus(t *testing.T) { + tests := []struct { + err error + want int + }{ + {err: e911.ErrNotSupported, want: http.StatusBadRequest}, + {err: e911.ErrProviderUnavailable, want: http.StatusBadRequest}, + {err: e911.ErrIdentityUnavailable, want: http.StatusConflict}, + {err: e911.ErrChallengeIncomplete, want: http.StatusNotImplemented}, + {err: e911.ErrCarrierWebsheetAbsent, want: http.StatusBadGateway}, + {err: errors.New("boom"), want: http.StatusInternalServerError}, + } + for _, tt := range tests { + if got := e911ErrorStatus(tt.err); got != tt.want { + t.Fatalf("e911ErrorStatus(%v)=%d want %d", tt.err, got, tt.want) + } + } +} diff --git a/internal/api/device_mgmt.go b/internal/api/device_mgmt.go new file mode 100644 index 00000000..f7dd1790 --- /dev/null +++ b/internal/api/device_mgmt.go @@ -0,0 +1,2716 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/iniwex5/vohive/internal/apduarbiter" + "github.com/iniwex5/vohive/internal/backend" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/db" + "github.com/iniwex5/vohive/internal/device" + "github.com/iniwex5/vohive/internal/e911" + "github.com/iniwex5/vohive/internal/esim" + "github.com/iniwex5/vohive/internal/modem" + proxytraffic "github.com/iniwex5/vohive/internal/proxy/traffic" + "github.com/iniwex5/vohive/pkg/logger" + "github.com/iniwex5/vowifi-go/runtimehost" + + "github.com/gin-gonic/gin" +) + +type deviceConfigDTO struct { + ID string `json:"id"` + Name string `json:"name"` + ModemIMEI string `json:"modem_imei"` + USBPath string `json:"usb_path"` + ATPort string `json:"at_port"` + ProxyPort int `json:"proxy_port"` + Interface string `json:"interface"` + ControlDevice string `json:"control_device,omitempty"` + QMIUseProxy *bool `json:"qmi_use_proxy,omitempty"` + QMIProxyPath *string `json:"qmi_proxy_path,omitempty"` + QMIProxyExecutable *string `json:"qmi_proxy_executable,omitempty"` + ESIMTransport string `json:"esim_transport,omitempty"` + BaudRate int `json:"baud_rate,omitempty"` + DataBits int `json:"data_bits,omitempty"` + StopBits int `json:"stop_bits,omitempty"` + Parity string `json:"parity,omitempty"` + OperatorSelectionMode string `json:"operator_selection_mode,omitempty"` + OperatorSelectionPLMN string `json:"operator_selection_plmn,omitempty"` + OperatorSelectionRAT string `json:"operator_selection_rat,omitempty"` + SMSEnabled bool `json:"sms_enabled"` + APN string `json:"apn,omitempty"` + IPVersion string `json:"ip_version,omitempty"` + NetworkEnabled bool `json:"network_enabled"` + VoWiFiEnabled bool `json:"vowifi_enabled"` + DeviceBackend string `json:"device_backend,omitempty"` +} + +func deviceConfigToDTO(c config.DeviceConfig) deviceConfigDTO { + return deviceConfigDTO{ + ID: c.ID, + Name: c.Name, + ModemIMEI: c.ModemIMEI, + USBPath: c.USBPath, + ATPort: c.ATPort, + ProxyPort: c.ProxyPort, + Interface: c.Interface, + ControlDevice: c.ControlDevice, + QMIUseProxy: boolPtr(c.QMIUseProxy), + QMIProxyPath: stringPtr(c.QMIProxyPath), + QMIProxyExecutable: stringPtr(c.QMIProxyExecutable), + ESIMTransport: config.NormalizeESIMTransport(c.ESIMTransport), + BaudRate: c.BaudRate, + DataBits: c.DataBits, + StopBits: c.StopBits, + Parity: c.Parity, + OperatorSelectionMode: c.OperatorSelectionMode, + OperatorSelectionPLMN: c.OperatorSelectionPLMN, + OperatorSelectionRAT: c.OperatorSelectionRAT, + SMSEnabled: c.SMSEnabled, + APN: c.APN, + IPVersion: c.IPVersion, + NetworkEnabled: c.NetworkEnabled, + VoWiFiEnabled: c.VoWiFiEnabled, + DeviceBackend: c.DeviceBackend, + } +} + +func deviceConfigFromDTO(d deviceConfigDTO) config.DeviceConfig { + return deviceConfigFromDTOWithBase(d, nil) +} + +func deviceConfigFromDTOWithBase(d deviceConfigDTO, base *config.DeviceConfig) config.DeviceConfig { + id := strings.TrimSpace(d.ID) + if id == "" { + id = strings.TrimSpace(d.Interface) + } + qmiUseProxy := false + qmiProxyPath := "" + qmiProxyExecutable := "" + if base != nil { + qmiUseProxy = base.QMIUseProxy + qmiProxyPath = base.QMIProxyPath + qmiProxyExecutable = base.QMIProxyExecutable + } + if d.QMIUseProxy != nil { + qmiUseProxy = *d.QMIUseProxy + } + if d.QMIProxyPath != nil { + qmiProxyPath = strings.TrimSpace(*d.QMIProxyPath) + } + if d.QMIProxyExecutable != nil { + qmiProxyExecutable = strings.TrimSpace(*d.QMIProxyExecutable) + } + return config.DeviceConfig{ + ID: id, + Name: strings.TrimSpace(d.Name), + ModemIMEI: strings.TrimSpace(d.ModemIMEI), + USBPath: strings.TrimSpace(d.USBPath), + ATPort: strings.TrimSpace(d.ATPort), + ProxyPort: d.ProxyPort, + Interface: strings.TrimSpace(d.Interface), + ControlDevice: strings.TrimSpace(d.ControlDevice), + QMIUseProxy: qmiUseProxy, + QMIProxyPath: qmiProxyPath, + QMIProxyExecutable: qmiProxyExecutable, + ESIMTransport: config.NormalizeESIMTransport(d.ESIMTransport), + BaudRate: d.BaudRate, + DataBits: d.DataBits, + StopBits: d.StopBits, + Parity: strings.TrimSpace(d.Parity), + OperatorSelectionMode: strings.TrimSpace(d.OperatorSelectionMode), + OperatorSelectionPLMN: strings.TrimSpace(d.OperatorSelectionPLMN), + OperatorSelectionRAT: strings.TrimSpace(d.OperatorSelectionRAT), + SMSEnabled: true, // 短信功能始终启用 + APN: strings.TrimSpace(d.APN), + IPVersion: strings.TrimSpace(d.IPVersion), + NetworkEnabled: d.NetworkEnabled, + VoWiFiEnabled: d.VoWiFiEnabled, + DeviceBackend: d.DeviceBackend, + } +} + +func boolPtr(v bool) *bool { + return &v +} + +func stringPtr(v string) *string { + return &v +} + +type deviceMgmtOverviewItem struct { + ID string `json:"id"` + Name string `json:"name"` + Running bool `json:"running"` + Healthy bool `json:"healthy"` + ControlOnline bool `json:"control_online"` + PhysicalPresent bool `json:"physical_present"` + WorkerRunning bool `json:"worker_running"` + DataConnected bool `json:"data_connected"` + RadioRegistered bool `json:"radio_registered"` + LifecyclePhase string `json:"lifecycle_phase"` + LifecycleReason string `json:"lifecycle_reason,omitempty"` + PrivateIP string `json:"private_ip,omitempty"` + PrivateIPv6 string `json:"private_ipv6,omitempty"` + PublicIP string `json:"public_ip"` + PublicIPv6 string `json:"public_ipv6,omitempty"` + Config *deviceConfigDTO `json:"config,omitempty"` + Modem modem.DeviceStatus `json:"modem"` + Traffic map[string]string `json:"traffic,omitempty"` + TrafficRaw map[string]int64 `json:"traffic_raw,omitempty"` + TrafficMeta *deviceTrafficMeta `json:"traffic_meta,omitempty"` + BackendMode string `json:"backend_mode,omitempty"` + NetworkConnected bool `json:"network_connected"` + RegistrationStateLabel string `json:"registration_state_label"` + // Interface / ControlDevice / ATPort / USBPath 是 worker 运行时解析出的当前路径 + // (零路径持久化后不入库),前端据此显示与判定 QMI 后端可用性、流量接口, + // 不再依赖持久化 config 的路径字段。 + Interface string `json:"interface,omitempty"` + ControlDevice string `json:"control_device,omitempty"` + ATPort string `json:"at_port,omitempty"` + USBPath string `json:"usb_path,omitempty"` +} + +func modemSummaryStatus(status modem.DeviceStatus) modem.DeviceStatus { + status.GID1 = "" + status.GID2 = "" + status.PNN = nil + status.OPL = nil + status.SIMServiceTable = nil + return status +} + +func registrationStateLabel(regStatus int) string { + switch regStatus { + case 1, 5: + return "registered" + case 2: + return "searching" + case 3: + return "denied" + default: + return "unknown" + } +} + +// overviewDisplayConfig 合并设备的展示配置:身份与用户意图取自持久化 config, +// 而 interface / control_device / at_port 等运行时路径取自 worker 内存 config。 +// 零路径持久化后持久化侧已不含这些路径,必须用运行时真实值展示,否则在线设备会被 +// 误判为“未探测到数据控制端”、流量按空接口名也统计不到。 +// cardPolicyVoWiFiEnabled 从卡策略读取用户意图,ICCID 为空或查不到时降级用 fallback。 +func cardPolicyVoWiFiEnabled(iccid string, fallback bool) bool { + if iccid == "" { + return fallback + } + pol, err := db.GetCardPolicy(iccid) + if err != nil { + return fallback + } + return pol.VoWiFiEnabled +} + +func overviewDisplayConfig(runtime, persisted config.DeviceConfig, hasPersisted bool) config.DeviceConfig { + if !hasPersisted { + return runtime + } + cfg := persisted + cfg.Interface = runtime.Interface + cfg.ControlDevice = runtime.ControlDevice + cfg.ATPort = runtime.ATPort + cfg.ManagePort = runtime.ManagePort + cfg.USBPath = runtime.USBPath + cfg.QMIDevice = runtime.QMIDevice + cfg.AudioDevice = runtime.AudioDevice + // 策略字段(network/vowifi/airplane/ip/apn)已改为跟卡走、只存在于运行时投影, + // 不再来自 persisted(config.yaml)。必须取 runtime,否则概览显示恒为 off。 + cfg.NetworkEnabled = runtime.NetworkEnabled + cfg.VoWiFiEnabled = runtime.VoWiFiEnabled + cfg.AirplaneEnabled = runtime.AirplaneEnabled + cfg.IPVersion = runtime.IPVersion + cfg.APN = runtime.APN + // SMS 是系统不变量(恒开),不随卡策略/投影时序变化,直接置真, + // 否则 worker 投影完成前或离线时 sms_enabled 为 false,会被短信中心设备过滤掉。 + cfg.SMSEnabled = true + return cfg +} + +func (s *Server) handleDeviceMgmtOverview(c *gin.Context) { + includeConfig := strings.TrimSpace(c.DefaultQuery("include_config", "1")) != "0" + workers := s.pool.GetAllWorkers() + managed := config.ListDevices() + cfgByID := map[string]config.DeviceConfig{} + for _, d := range managed { + cfgByID[d.ID] = d + } + tagByID := map[string]string{} + tags := make([]string, 0, len(workers)) + for _, w := range workers { + cfg := w.Config + if v, ok := cfgByID[w.ID]; ok { + cfg = overviewDisplayConfig(w.Config, v, true) + } + if cfg.Interface == "" { + continue + } + tag := w.ID + "@" + cfg.Interface + tagByID[w.ID] = tag + tags = append(tags, tag) + } + byTag, _ := db.GetLatestMinuteDeltasBatch("iface", tags) + now := time.Now() + + workerByID := map[string]bool{} + items := make([]deviceMgmtOverviewItem, 0, len(workers)) + for _, w := range workers { + workerByID[w.ID] = true + cfg := w.Config + if v, ok := cfgByID[w.ID]; ok { + cfg = overviewDisplayConfig(w.Config, v, true) + } + status := w.GetCachedDeviceStatus() // 设备管理总览列表读缓存,0 IPC + controlOnline := w.GetCachedHealthy() + item := deviceMgmtOverviewItem{ + ID: w.ID, + Name: cfg.Name, + Running: true, + Healthy: controlOnline, // 兼容旧客户端:healthy 表示控制面在线 + ControlOnline: controlOnline, + PublicIP: w.GetCachedIP(), + PublicIPv6: w.GetCachedIPv6(), + Modem: modemSummaryStatus(status), + NetworkConnected: w.NetworkConnected(), + RegistrationStateLabel: registrationStateLabel(status.RegStatus), + BackendMode: func() string { + if w.Backend != nil { + return w.Backend.Mode() + } + return "at" + }(), + } + item.Interface = cfg.Interface + item.ControlDevice = cfg.ControlDevice + item.ATPort = w.ResolvedATPort() + item.USBPath = cfg.USBPath + if includeConfig { + dto := deviceConfigToDTO(cfg) + item.Config = &dto + } + if nc := w.NetworkController(); nc != nil { + item.PrivateIP = nc.GetPrivateIP() + item.PrivateIPv6 = nc.GetPrivateIPv6() + } + item.Traffic, item.TrafficRaw, item.TrafficMeta = buildTrafficOverviewFields(cfg.Interface, byTag[tagByID[w.ID]], now) + s.applyLifecycleToOverviewItem(&item, true, cfg) + items = append(items, item) + } + for _, dc := range managed { + if workerByID[dc.ID] { + continue + } + var cfgDTO *deviceConfigDTO + if includeConfig { + dto := deviceConfigToDTO(dc) + cfgDTO = &dto + } + item := deviceMgmtOverviewItem{ + ID: dc.ID, + Name: dc.Name, + Running: false, + Healthy: false, + ControlOnline: false, + PublicIP: "", + Config: cfgDTO, + Modem: modem.DeviceStatus{}, + Traffic: nil, + BackendMode: resolveOfflineBackendMode(dc), + NetworkConnected: false, + RegistrationStateLabel: registrationStateLabel(0), + } + s.applyLifecycleToOverviewItem(&item, false, dc) + items = append(items, item) + } + c.JSON(http.StatusOK, gin.H{"devices": items}) +} + +type deviceMgmtOverviewLiteItem struct { + ID string `json:"id"` + Name string `json:"name"` + Running bool `json:"running"` + Healthy bool `json:"healthy"` + ControlOnline bool `json:"control_online"` + PhysicalPresent bool `json:"physical_present"` + WorkerRunning bool `json:"worker_running"` + DataConnected bool `json:"data_connected"` + RadioRegistered bool `json:"radio_registered"` + LifecyclePhase string `json:"lifecycle_phase"` + LifecycleReason string `json:"lifecycle_reason,omitempty"` + PrivateIP string `json:"private_ip,omitempty"` + PrivateIPv6 string `json:"private_ipv6,omitempty"` + PublicIP string `json:"public_ip"` + PublicIPv6 string `json:"public_ipv6,omitempty"` + Interface string `json:"interface,omitempty"` + ControlDevice string `json:"control_device,omitempty"` + ESIMTransport string `json:"esim_transport,omitempty"` + ATPort string `json:"at_port,omitempty"` + USBPath string `json:"usb_path,omitempty"` + AudioDevice string `json:"audio_device,omitempty"` + LocalPhone string `json:"local_phone,omitempty"` + E911SetupAvailable bool `json:"e911_setup_available,omitempty"` + ActiveESIMProfileName string `json:"active_esim_profile_name,omitempty"` + SMSEnabled bool `json:"sms_enabled"` + NetworkEnabled bool `json:"network_enabled"` + VoWiFiEnabled bool `json:"vowifi_enabled"` + VoWiFiActive bool `json:"vowifi_active"` + VoWiFiRuntime *voWiFiRuntimeDTO `json:"vowifi_runtime,omitempty"` + RadioLiveOK *bool `json:"radio_live_ok,omitempty"` + Modem modem.DeviceStatus `json:"modem"` + Traffic map[string]string `json:"traffic,omitempty"` + TrafficRaw map[string]int64 `json:"traffic_raw,omitempty"` + TrafficMeta *deviceTrafficMeta `json:"traffic_meta,omitempty"` + BackendMode string `json:"backend_mode"` + NetworkConnected bool `json:"network_connected"` + RegistrationStateLabel string `json:"registration_state_label"` +} + +type deviceMgmtListModem struct { + Operator string `json:"operator"` + NativeSPN string `json:"native_spn,omitempty"` + NativeMCC string `json:"native_mcc,omitempty"` + NativeMNC string `json:"native_mnc,omitempty"` + NetworkMode string `json:"network_mode"` + NetworkDuplex string `json:"network_duplex"` + RadioBand string `json:"radio_band,omitempty"` + RadioChannel uint32 `json:"radio_channel,omitempty"` + SignalDBM int `json:"signal_dbm"` + SignalSINR int `json:"signal_sinr,omitempty"` + IMEI string `json:"imei,omitempty"` + ICCID string `json:"iccid,omitempty"` + RegStatus int `json:"reg_status"` + PSAttached bool `json:"ps_attached"` +} + +type deviceMgmtListItem struct { + ID string `json:"id"` + Name string `json:"name"` + Running bool `json:"running"` + Healthy bool `json:"healthy"` + ControlOnline bool `json:"control_online"` + PhysicalPresent bool `json:"physical_present"` + WorkerRunning bool `json:"worker_running"` + DataConnected bool `json:"data_connected"` + RadioRegistered bool `json:"radio_registered"` + LifecyclePhase string `json:"lifecycle_phase"` + LifecycleReason string `json:"lifecycle_reason,omitempty"` + PublicIP string `json:"public_ip"` + PublicIPv6 string `json:"public_ipv6,omitempty"` + Interface string `json:"interface,omitempty"` + ESIMTransport string `json:"esim_transport,omitempty"` + SMSEnabled bool `json:"sms_enabled"` + NetworkEnabled bool `json:"network_enabled"` + VoWiFiEnabled bool `json:"vowifi_enabled"` + VoWiFiRuntime *voWiFiRuntimeDTO `json:"vowifi_runtime,omitempty"` + Modem deviceMgmtListModem `json:"modem"` + NetworkConnected bool `json:"network_connected"` + RegistrationStateLabel string `json:"registration_state_label"` +} + +type voWiFiRuntimeDTO struct { + DeviceID string `json:"device_id"` + Phase string `json:"phase"` + DataplaneMode string `json:"dataplane_mode"` + ICCID string `json:"iccid,omitempty"` + IMSI string `json:"imsi,omitempty"` + SIMReady bool `json:"sim_ready"` + AccessReady bool `json:"access_ready"` + TunnelReady bool `json:"tunnel_ready"` + IMSReady bool `json:"ims_ready"` + SMSReady bool `json:"sms_ready"` + RegStatus int `json:"reg_status"` + RegStatusText string `json:"reg_status_text"` + NetworkMode string `json:"network_mode"` + LastErrorClass string `json:"last_error_class"` + LastError string `json:"last_error"` + LastReason string `json:"last_reason"` + UpdatedAt time.Time `json:"updated_at"` +} + +func runtimeStateToDTO(st runtimehost.State, status modem.DeviceStatus) *voWiFiRuntimeDTO { + return &voWiFiRuntimeDTO{ + DeviceID: st.DeviceID, + Phase: string(st.Phase), + DataplaneMode: st.DataplaneMode, + ICCID: strings.TrimSpace(status.ICCID), + IMSI: strings.TrimSpace(status.IMSI), + SIMReady: st.SIMReady, + AccessReady: st.AccessReady, + TunnelReady: st.TunnelReady, + IMSReady: st.IMSReady, + SMSReady: st.SMSReady, + RegStatus: st.RegStatus, + RegStatusText: st.RegStatusText, + NetworkMode: st.NetworkMode, + LastErrorClass: st.LastErrorClass, + LastError: st.LastError, + LastReason: st.LastReason, + UpdatedAt: st.UpdatedAt, + } +} + +func (s *Server) getVoWiFiRuntimeDTO(deviceID string) *voWiFiRuntimeDTO { + st, ok := s.pool.GetVoWiFiRuntimeState(deviceID) + if !ok { + return nil + } + status := modem.DeviceStatus{} + if w := s.pool.GetWorker(deviceID); w != nil { + status = w.ProjectDeviceStatus() + } + return runtimeStateToDTO(st, status) +} + +func isLifecycleActiveForAPI(phase string) bool { + switch phase { + case string(device.LifecyclePhaseRebooting), + string(device.LifecyclePhaseUSBWait), + string(device.LifecyclePhaseWorkerStarting), + string(device.LifecyclePhaseQMIStarting), + string(device.LifecyclePhaseRecovering): + return true + default: + return false + } +} + +func lifecyclePhaseString(snap device.LifecycleSnapshot) string { + if snap.Phase == "" { + return string(device.LifecyclePhaseOffline) + } + return string(snap.Phase) +} + +func lifecycleSnapshotForAPI(pool *device.Pool, deviceID string) device.LifecycleSnapshot { + if pool == nil { + return device.LifecycleSnapshot{Phase: device.LifecyclePhaseOffline} + } + return pool.LifecycleSnapshot(deviceID) +} + +func lifecyclePhaseForAPI(snap device.LifecycleSnapshot, workerRunning bool, controlOnline bool) string { + phase := lifecyclePhaseString(snap) + if workerRunning && controlOnline { + switch phase { + case string(device.LifecyclePhaseOffline), + string(device.LifecyclePhaseUSBWait), + string(device.LifecyclePhaseWorkerStarting), + string(device.LifecyclePhaseQMIStarting), + string(device.LifecyclePhaseRecovering): + return string(device.LifecyclePhaseOnline) + } + } + return phase +} + +func (s *Server) applyLifecycleToOverviewItem(item *deviceMgmtOverviewItem, workerRunning bool, cfg config.DeviceConfig) { + if item == nil { + return + } + snap := lifecycleSnapshotForAPI(s.pool, cfg.ID) + phase := lifecyclePhaseForAPI(snap, workerRunning, item.ControlOnline) + item.WorkerRunning = workerRunning + item.DataConnected = item.NetworkConnected + item.RadioRegistered = item.Modem.RegStatus == 1 || item.Modem.RegStatus == 5 + item.LifecyclePhase = phase + item.LifecycleReason = snap.Reason + item.PhysicalPresent = workerRunning || isLifecycleActiveForAPI(phase) +} + +func (s *Server) applyLifecycleToListItem(item *deviceMgmtListItem, workerRunning bool, cfg config.DeviceConfig) { + if item == nil { + return + } + snap := lifecycleSnapshotForAPI(s.pool, cfg.ID) + phase := lifecyclePhaseForAPI(snap, workerRunning, item.ControlOnline) + item.WorkerRunning = workerRunning + item.DataConnected = item.NetworkConnected + item.RadioRegistered = item.Modem.RegStatus == 1 || item.Modem.RegStatus == 5 + item.LifecyclePhase = phase + item.LifecycleReason = snap.Reason + item.PhysicalPresent = workerRunning || isLifecycleActiveForAPI(phase) +} + +func (s *Server) applyLifecycleToOverviewLiteItem(item *deviceMgmtOverviewLiteItem, worker *device.Worker, cfg config.DeviceConfig) { + if item == nil { + return + } + workerRunning := worker != nil + snap := lifecycleSnapshotForAPI(s.pool, cfg.ID) + phase := lifecyclePhaseForAPI(snap, workerRunning, item.ControlOnline) + item.WorkerRunning = workerRunning + item.DataConnected = item.NetworkConnected + item.RadioRegistered = item.Modem.RegStatus == 1 || item.Modem.RegStatus == 5 + item.LifecyclePhase = phase + item.LifecycleReason = snap.Reason + item.PhysicalPresent = workerRunning || isLifecycleActiveForAPI(phase) +} + +func (s *Server) buildOverviewLiteItemFromWorker(w *device.Worker, cfg config.DeviceConfig, status modem.DeviceStatus, radioLiveOK *bool) deviceMgmtOverviewLiteItem { + item := s.buildOverviewLiteItemFromWorkerWithModem(w, cfg, status, radioLiveOK, status) + item.Modem = modemSummaryStatus(item.Modem) + return item +} + +func (s *Server) buildOverviewLiteDetailItemFromWorker(w *device.Worker, cfg config.DeviceConfig, status modem.DeviceStatus, radioLiveOK *bool) deviceMgmtOverviewLiteItem { + return s.buildOverviewLiteItemFromWorkerWithModem(w, cfg, status, radioLiveOK, status) +} + +func (s *Server) buildOverviewLiteItemFromWorkerWithModem(w *device.Worker, cfg config.DeviceConfig, status modem.DeviceStatus, radioLiveOK *bool, modemStatus modem.DeviceStatus) deviceMgmtOverviewLiteItem { + controlOnline := w.GetCachedHealthy() + item := deviceMgmtOverviewLiteItem{ + ID: w.ID, + Name: cfg.Name, + Running: true, + Healthy: controlOnline, + ControlOnline: controlOnline, + PublicIP: w.GetCachedIP(), + PublicIPv6: w.GetCachedIPv6(), + Interface: cfg.Interface, + ControlDevice: cfg.ControlDevice, + ESIMTransport: config.NormalizeESIMTransport(cfg.ESIMTransport), + ATPort: w.ResolvedATPort(), + USBPath: cfg.USBPath, + AudioDevice: cfg.AudioDevice, + LocalPhone: overviewLocalPhone(effectiveOverviewIMSI(w, status), strings.TrimSpace(status.ICCID)), + E911SetupAvailable: e911.SetupAvailable(modemStatus), + SMSEnabled: cfg.SMSEnabled, + NetworkEnabled: cfg.NetworkEnabled, + VoWiFiEnabled: cardPolicyVoWiFiEnabled(strings.TrimSpace(status.ICCID), cfg.VoWiFiEnabled), + VoWiFiActive: s.pool.IsVoWiFiActive(w.ID), + VoWiFiRuntime: s.getVoWiFiRuntimeDTO(w.ID), + RadioLiveOK: radioLiveOK, + Modem: modemStatus, + NetworkConnected: w.NetworkConnected(), + RegistrationStateLabel: registrationStateLabel(status.RegStatus), + BackendMode: func() string { + if w.Backend != nil { + return w.Backend.Mode() + } + return "at" + }(), + } + if nc := w.NetworkController(); nc != nil { + item.PrivateIP = nc.GetPrivateIP() + item.PrivateIPv6 = nc.GetPrivateIPv6() + } + if w.EsimMgr != nil { + if name, err := w.EsimMgr.ActiveProfileName(); err == nil { + item.ActiveESIMProfileName = name + } + } + s.applyLifecycleToOverviewLiteItem(&item, w, cfg) + return item +} + +type overviewStreamEmitVersion struct { + VoWiFiActive bool + LifecyclePhase string + LifecycleReason string + HasRuntime bool + Phase string + TunnelReady bool + IMSReady bool + SMSReady bool + LastErrorClass string +} + +func newOverviewStreamEmitVersion(item deviceMgmtOverviewLiteItem) overviewStreamEmitVersion { + v := overviewStreamEmitVersion{ + VoWiFiActive: item.VoWiFiActive, + LifecyclePhase: item.LifecyclePhase, + LifecycleReason: item.LifecycleReason, + } + if item.VoWiFiRuntime != nil { + v.HasRuntime = true + v.Phase = item.VoWiFiRuntime.Phase + v.TunnelReady = item.VoWiFiRuntime.TunnelReady + v.IMSReady = item.VoWiFiRuntime.IMSReady + v.SMSReady = item.VoWiFiRuntime.SMSReady + v.LastErrorClass = item.VoWiFiRuntime.LastErrorClass + } + return v +} + +func shouldSkipOverviewStatePush(last *overviewStreamEmitVersion, curr overviewStreamEmitVersion) bool { + if last == nil { + return false + } + return *last == curr +} + +func effectiveOverviewIMSI(w *device.Worker, status modem.DeviceStatus) string { + if w != nil && w.SIMIdentitySuppressesOverviewIMSI() { + return "" + } + imsi := strings.TrimSpace(status.IMSI) + if imsi != "" { + return imsi + } + if w == nil { + return "" + } + if !w.SIMIdentityAllowsOverviewFallback() { + return "" + } + return strings.TrimSpace(w.GetCachedIMSI()) +} + +func overviewLocalPhoneByIMSI(imsi string) string { + imsi = strings.TrimSpace(imsi) + if imsi == "" { + return "" + } + phone, err := db.GetSIMCardPhoneNumberByIMSI(imsi) + if err != nil { + return "" + } + return strings.TrimSpace(phone) +} + +func overviewLocalPhone(imsi, iccid string) string { + imsi = strings.TrimSpace(imsi) + iccid = strings.TrimSpace(iccid) + if imsi == "" && iccid == "" { + return "" + } + phone, err := db.GetPhoneNumberByIMSIOrICCID(imsi, iccid) + if err != nil { + return "" + } + return strings.TrimSpace(phone) +} + +func (s *Server) handleDeviceMgmtList(c *gin.Context) { + workers := s.pool.GetAllWorkers() + managed := config.ListDevices() + cfgByID := map[string]config.DeviceConfig{} + for _, d := range managed { + cfgByID[d.ID] = d + } + + workerByID := map[string]bool{} + items := make([]deviceMgmtListItem, 0, len(workers)) + for _, w := range workers { + workerByID[w.ID] = true + cfg := w.Config + if v, ok := cfgByID[w.ID]; ok { + cfg = overviewDisplayConfig(w.Config, v, true) + } + status := w.GetCachedDeviceStatus() + controlOnline := w.GetCachedHealthy() + item := deviceMgmtListItem{ + ID: w.ID, + Name: cfg.Name, + Running: true, + Healthy: controlOnline, + ControlOnline: controlOnline, + PublicIP: w.GetCachedIP(), + PublicIPv6: w.GetCachedIPv6(), + Interface: cfg.Interface, + ESIMTransport: config.NormalizeESIMTransport(cfg.ESIMTransport), + SMSEnabled: cfg.SMSEnabled, + NetworkEnabled: cfg.NetworkEnabled, + VoWiFiEnabled: s.pool.IsVoWiFiActive(w.ID), // 使用多设备状态查询 + VoWiFiRuntime: s.getVoWiFiRuntimeDTO(w.ID), + NetworkConnected: w.NetworkConnected(), + RegistrationStateLabel: registrationStateLabel(status.RegStatus), + Modem: deviceMgmtListModem{ + Operator: status.Operator, + NativeSPN: status.NativeSPN, + NativeMCC: status.NativeMCC, + NativeMNC: status.NativeMNC, + NetworkMode: status.NetworkMode, + NetworkDuplex: status.NetworkDuplex, + RadioBand: status.RadioBand, + RadioChannel: status.RadioChannel, + SignalDBM: status.SignalDBM, + SignalSINR: status.SignalSINR, + IMEI: status.IMEI, + ICCID: status.ICCID, + RegStatus: status.RegStatus, + PSAttached: status.PSAttached, + }, + } + s.applyLifecycleToListItem(&item, true, cfg) + items = append(items, item) + } + + for _, dc := range managed { + if workerByID[dc.ID] { + continue + } + item := deviceMgmtListItem{ + ID: dc.ID, + Name: dc.Name, + Running: false, + Healthy: false, + ControlOnline: false, + PublicIP: "", + Interface: dc.Interface, + ESIMTransport: config.NormalizeESIMTransport(dc.ESIMTransport), + SMSEnabled: true, // SMS 恒开(系统不变量) + NetworkEnabled: dc.NetworkEnabled, + VoWiFiEnabled: false, // 非运行设备无活跃 VoWiFi + NetworkConnected: false, + RegistrationStateLabel: registrationStateLabel(0), + Modem: deviceMgmtListModem{}, + } + s.applyLifecycleToListItem(&item, false, dc) + items = append(items, item) + } + + c.JSON(http.StatusOK, gin.H{"devices": items, "device_limit": device.DefaultFreeDeviceLimit}) +} + +// handleDeviceMgmtRefreshInfo 主动触发设备底层重新采集各种信息(SIM、信号等) +func (s *Server) handleDeviceMgmtRefreshInfo(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到或未运行"}) + return + } + + // 阻塞式刷新,后续执行的 overview-lite 就能马上获取到最新的状态 + if worker.Backend != nil && worker.Backend.Mode() != "at" { + _ = worker.RefreshRuntime(c.Request.Context(), "manual_refresh") + _ = worker.RefreshIdentityLive(c.Request.Context(), "manual_refresh") + s.pool.PersistRuntimeState(worker) + s.pool.PersistIdentityState(worker) + } else if worker.Modem != nil { + worker.Modem.RefreshDeviceInfo() + _ = worker.RefreshRuntime(c.Request.Context(), "manual_refresh") + _ = worker.RefreshIdentityLive(c.Request.Context(), "manual_refresh") + s.pool.PersistRuntimeState(worker) + s.pool.PersistIdentityState(worker) + } + + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "设备信息刷新完成"}) +} + +func (s *Server) handleDeviceMgmtOverviewLite(c *gin.Context) { + id := deviceIDParam(c) + if id == "" { + id = strings.TrimSpace(c.Query("id")) + } + liveRefresh := overviewDetailLiveRefreshRequested(c) + workers := s.pool.GetAllWorkers() + managed := config.ListDevices() + cfgByID := map[string]config.DeviceConfig{} + for _, d := range managed { + cfgByID[d.ID] = d + } + + if id != "" { + for _, w := range workers { + if w.ID != id { + continue + } + cfg := w.Config + if v, ok := cfgByID[w.ID]; ok { + cfg = overviewDisplayConfig(w.Config, v, true) + } + if liveRefresh { + _ = w.RefreshRuntime(c.Request.Context(), "overview_detail") + _ = w.RefreshIdentityLive(c.Request.Context(), "overview_detail") + } + status := w.ProjectDeviceStatus() + var radioLiveOK *bool + if liveRefresh && (w.Backend == nil || w.Backend.Mode() == backend.BackendAT) { + radioLiveOK = new(bool) + *radioLiveOK = true + } + item := s.buildOverviewLiteDetailItemFromWorker(w, cfg, status, radioLiveOK) + controlOnline := w.GetCachedHealthy() + item.Healthy = controlOnline + item.ControlOnline = controlOnline + s.applyLifecycleToOverviewLiteItem(&item, w, cfg) + tag := w.ID + "@" + cfg.Interface + ps, rx, tx, _ := db.GetLatestMinuteDeltas("iface", tag) + item.Traffic, item.TrafficRaw, item.TrafficMeta = buildTrafficOverviewFields(cfg.Interface, db.LatestMinuteDeltas{ + PeriodStart: ps, + RxBytes: rx, + TxBytes: tx, + }, time.Now()) + c.JSON(http.StatusOK, gin.H{"devices": []deviceMgmtOverviewLiteItem{item}}) + return + } + + if dc, err := config.GetDeviceByID(id); err == nil && dc != nil { + pol := resolveOfflineDevicePolicy(id) + item := deviceMgmtOverviewLiteItem{ + ID: dc.ID, + Name: dc.Name, + Running: false, + Healthy: false, + ControlOnline: false, + PublicIP: "", + Interface: dc.Interface, + ControlDevice: dc.ControlDevice, + ESIMTransport: config.NormalizeESIMTransport(dc.ESIMTransport), + ATPort: dc.ATPort, + USBPath: dc.USBPath, + SMSEnabled: pol.SMSEnabled, + NetworkEnabled: pol.NetworkEnabled, + VoWiFiEnabled: pol.VoWiFiEnabled, + VoWiFiActive: false, + NetworkConnected: false, + RegistrationStateLabel: registrationStateLabel(0), + Modem: modem.DeviceStatus{}, + Traffic: nil, + } + s.applyLifecycleToOverviewLiteItem(&item, nil, *dc) + c.JSON(http.StatusOK, gin.H{"devices": []deviceMgmtOverviewLiteItem{item}}) + return + } + + c.JSON(http.StatusOK, gin.H{"devices": []deviceMgmtOverviewLiteItem{}}) + return + } + + tagByID := map[string]string{} + tags := make([]string, 0, len(workers)) + for _, w := range workers { + cfg := w.Config + if v, ok := cfgByID[w.ID]; ok { + cfg = overviewDisplayConfig(w.Config, v, true) + } + if cfg.Interface == "" { + continue + } + tag := w.ID + "@" + cfg.Interface + tagByID[w.ID] = tag + tags = append(tags, tag) + } + byTag, _ := db.GetLatestMinuteDeltasBatch("iface", tags) + now := time.Now() + + workerByID := map[string]bool{} + items := make([]deviceMgmtOverviewLiteItem, 0, len(workers)) + for _, w := range workers { + workerByID[w.ID] = true + cfg := w.Config + if v, ok := cfgByID[w.ID]; ok { + cfg = overviewDisplayConfig(w.Config, v, true) + } + status := w.GetCachedDeviceStatus() // 批量列表读缓存,0 IPC + item := s.buildOverviewLiteItemFromWorker(w, cfg, status, nil) + item.Traffic, item.TrafficRaw, item.TrafficMeta = buildTrafficOverviewFields(cfg.Interface, byTag[tagByID[w.ID]], now) + items = append(items, item) + } + for _, dc := range managed { + if workerByID[dc.ID] { + continue + } + item := deviceMgmtOverviewLiteItem{ + ID: dc.ID, + Name: dc.Name, + Running: false, + Healthy: false, + ControlOnline: false, + PublicIP: "", + Interface: dc.Interface, + ControlDevice: dc.ControlDevice, + ESIMTransport: config.NormalizeESIMTransport(dc.ESIMTransport), + ATPort: dc.ATPort, + SMSEnabled: true, // SMS 恒开(系统不变量) + NetworkEnabled: dc.NetworkEnabled, + VoWiFiActive: false, // 非运行设备无活跃 VoWiFi + NetworkConnected: false, + RegistrationStateLabel: registrationStateLabel(0), + Modem: modem.DeviceStatus{}, + Traffic: nil, + } + s.applyLifecycleToOverviewLiteItem(&item, nil, dc) + items = append(items, item) + } + c.JSON(http.StatusOK, gin.H{"devices": items}) +} + +func overviewDetailLiveRefreshRequested(c *gin.Context) bool { + if c == nil { + return false + } + for _, key := range []string{"refresh", "live"} { + switch strings.ToLower(strings.TrimSpace(c.Query(key))) { + case "1", "true", "yes", "on": + return true + } + } + return false +} + +func (s *Server) handleDeviceMgmtGetDeviceConfig(c *gin.Context) { + id := deviceIDParam(c) + if id == "" { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"}) + return + } + md, err := config.GetDeviceByID(id) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "读取设备配置失败: " + err.Error()}) + return + } + if md == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到"}) + return + } + cfgDTO := deviceConfigToDTO(*md) + if worker := s.pool.GetWorker(id); worker != nil { + cfgDTO.Interface = worker.Config.Interface + cfgDTO.ControlDevice = worker.Config.ControlDevice + cfgDTO.ATPort = worker.ResolvedATPort() + cfgDTO.USBPath = worker.Config.USBPath + } + c.JSON(http.StatusOK, gin.H{"config": cfgDTO}) +} + +type discoveredDevice struct { + DiscoveryKey string `json:"discovery_key"` + ControlPath string `json:"control_path"` + NetInterface string `json:"net_interface"` + USBPath string `json:"usb_path"` + IMEI string `json:"imei,omitempty"` + VendorID uint16 `json:"vendor_id"` + ProductID uint16 `json:"product_id"` + DriverName string `json:"driver_name"` + ATPorts []string `json:"at_ports"` + ATPort string `json:"at_port"` + AudioDevice string `json:"audio_device,omitempty"` + Mode string `json:"mode,omitempty"` // qmi/mbim/ecm/rndis/ncm/unknown + NetworkCapable bool `json:"network_capable"` // 是否可由 QMI Core 接管 + Configured bool `json:"configured"` + ConfiguredID string `json:"configured_id,omitempty"` + Degraded bool `json:"degraded,omitempty"` // 探不到 IMEI,无法确立身份,不可直接添加 +} + +var discoverQMIForMgmtFn = device.DiscoverQMIDevices +var discoverCompatibleModemsFromQMIFn = device.DiscoverCompatibleModemsFromQMI +var enrichDiscoveredCompatibleModemFn = device.EnrichDiscoveredCompatibleModem +var probeIMEIForAddFn = device.ProbeIMEIViaQMI +var probeIMEIViaMBIMForMgmtFn = device.ProbeIMEIViaMBIM + +func ensureAddDeviceIMEI(cfg config.DeviceConfig, probe func(string) (string, error)) (config.DeviceConfig, error) { + if strings.TrimSpace(cfg.ControlDevice) == "" || config.NormalizeIMEI(cfg.ModemIMEI) != "" { + return cfg, nil + } + probed, err := probe(cfg.ControlDevice) + if err != nil || strings.TrimSpace(probed) == "" { + return cfg, fmt.Errorf("IMEI 探测失败,请重新插拔设备或稍后重试") + } + cfg.ModemIMEI = strings.TrimSpace(probed) + return cfg, nil +} + +func (s *Server) handleDeviceMgmtDiscovered(c *gin.Context) { + discoveredQMI, err := discoverQMIForMgmtFn() + if err != nil { + discoveredQMI = nil + } + + list, err := discoverCompatibleModemsFromQMIFn(discoveredQMI) + if err != nil { + c.JSON(http.StatusOK, gin.H{"devices": []discoveredDevice{}}) + return + } + + withIMEI := strings.TrimSpace(c.Query("with_imei")) == "1" + managedIndex := device.BuildWorkerDiscoveryIndex(s.pool.GetAllWorkers(), withIMEI) + + managed := config.ListDevices() + + // 第一阶段:并行补全每块硬件(AT/IMEI探测),不做任何身份判定。 + enriched := make([]device.CompatibleModem, len(list)) + var wg sync.WaitGroup + + for i, d := range list { + wg.Add(1) + go func(idx int, dev device.CompatibleModem) { + defer wg.Done() + + resolvedATPort := strings.TrimSpace(dev.ATPort) + imei := strings.TrimSpace(dev.IMEI) + + if withIMEI { + managedMatch, hasManaged := managedIndex.Lookup(strings.TrimSpace(dev.ControlPath), strings.TrimSpace(dev.USBPath), strings.TrimSpace(dev.NetInterface)) + if hasManaged { + if containsDiscoveredATPort(dev.ATPorts, managedMatch.ATPort) { + resolvedATPort = managedMatch.ATPort + } + if imei == "" { + imei = managedMatch.IMEI + } + } else { + probed, discoveredIMEI := enrichDiscoveredCompatibleModemFn(dev, device.CompatibleModemEnrichOptions{ + EnableATProbe: true, + ATProbeTimeout: 900 * time.Millisecond, + EnableQMIIMEIProbe: strings.TrimSpace(dev.ControlPath) != "" && dev.Mode != "mbim", + }) + dev = probed + if resolved := strings.TrimSpace(probed.ATPort); resolved != "" { + resolvedATPort = resolved + } + if imei == "" { + imei = discoveredIMEI + } + // MBIM 设备没有 AT 端口也不支持 QMI,使用 MBIM DeviceCaps 探测 IMEI + if imei == "" && dev.Mode == "mbim" && strings.TrimSpace(dev.ControlPath) != "" { + if mbimIMEI, err := probeIMEIViaMBIMForMgmtFn(dev.ControlPath); err == nil && mbimIMEI != "" { + imei = mbimIMEI + } + } + } + } + + mode := strings.ToLower(strings.TrimSpace(dev.Mode)) + networkCapable := dev.NetworkCapable + + if mode == "" { + mode = "unknown" + } + + dev.IMEI = imei + dev.ATPort = resolvedATPort + dev.Mode = mode + dev.NetworkCapable = networkCapable + enriched[idx] = dev + }(i, d) + } + wg.Wait() + + // 第二阶段:统一身份解析(按 IMEI),路径不再是身份。 + resolved := device.ResolveDeviceIdentities(enriched, managed) + + out := make([]discoveredDevice, 0, len(enriched)) + for _, pair := range resolved.Matched { + out = append(out, buildDiscoveredDevice(pair.Hardware, true, pair.Config.ID, false)) + } + for _, hw := range resolved.Unmatched { + out = append(out, buildDiscoveredDevice(hw, false, "", false)) + } + for _, hw := range resolved.Degraded { + out = append(out, buildDiscoveredDevice(hw, false, "", true)) + } + + c.JSON(http.StatusOK, gin.H{"devices": out}) +} + +func buildDiscoveredDevice(hw device.CompatibleModem, configured bool, configuredID string, degraded bool) discoveredDevice { + return discoveredDevice{ + DiscoveryKey: hw.DiscoveryKey(), + ControlPath: hw.ControlPath, + NetInterface: hw.NetInterface, + USBPath: hw.USBPath, + IMEI: strings.TrimSpace(hw.IMEI), + VendorID: hw.VendorID, + ProductID: hw.ProductID, + DriverName: hw.DriverName, + ATPorts: hw.ATPorts, + ATPort: hw.ATPort, + AudioDevice: hw.AudioDevice, + Mode: hw.Mode, + NetworkCapable: hw.NetworkCapable, + Configured: configured, + ConfiguredID: configuredID, + Degraded: degraded, + } +} + +func containsDiscoveredATPort(ports []string, target string) bool { + target = strings.TrimSpace(target) + if target == "" { + return false + } + for _, port := range ports { + if strings.TrimSpace(port) == target { + return true + } + } + return false +} + +type setFlightModeRequest struct { + Enabled bool `json:"enabled"` +} + +func isFlightModeEnabled(mode int) bool { + return mode == int(backend.ModeLowPower) || mode == int(backend.ModeRFOff) +} + +func flightModeSuccessMessage(enabled bool) string { + if enabled { + return "飞行模式已开启" + } + return "飞行模式已关闭" +} + +func setWorkerFlightMode(ctx context.Context, worker *device.Worker, flightModeEnabled bool) (operatingMode int, flightMode bool, err error) { + targetMode := backend.ModeOnline + expectedMode := int(backend.ModeOnline) + if flightModeEnabled { + targetMode = backend.ModeRFOff + expectedMode = int(backend.ModeRFOff) + } + + if worker.Backend != nil { + if err := worker.Backend.SetOperatingMode(ctx, targetMode); err != nil { + return 0, false, err + } + opMode, err := worker.Backend.GetOperatingMode(ctx) + if err != nil { + return expectedMode, isFlightModeEnabled(expectedMode), nil + } + operatingMode = int(opMode) + return operatingMode, isFlightModeEnabled(operatingMode), nil + } + + return 0, false, fmt.Errorf("设备后端未初始化,无法切换飞行模式") +} + +type updateDeviceRequest struct { + Config deviceConfigDTO `json:"config"` +} + +func hasManagedNetworkCapability(cfg config.DeviceConfig) bool { + return strings.TrimSpace(cfg.ControlDevice) != "" && strings.TrimSpace(cfg.Interface) != "" +} + +func validateManagedNetworkConfig(cfg config.DeviceConfig) error { + if err := validateDeviceBackendConfig(cfg); err != nil { + return err + } + if _, _, err := config.ResolveIPFamily(cfg.IPVersion); err != nil { + return err + } + // 零路径持久化后 control_device/interface 由运行时从 IMEI 发现,不再作为保存前置条件。 + return nil +} + +func normalizeManagedDeviceConfig(cfg config.DeviceConfig) (config.DeviceConfig, string) { + if cfg.VoWiFiEnabled && cfg.NetworkEnabled { + cfg.NetworkEnabled = false + return cfg, "VoWiFi 已启用" + } + return cfg, "" +} + +func deviceConfigForAdd(cfg config.DeviceConfig) config.DeviceConfig { + cfg.APN = "" + cfg.IPVersion = "" + cfg.NetworkEnabled = false + cfg.VoWiFiEnabled = false + cfg.AirplaneEnabled = false + cfg.SMSEnabled = true + return cfg +} + +func joinWarningMessages(parts ...string) string { + filtered := make([]string, 0, len(parts)) + for _, part := range parts { + part = strings.TrimSpace(part) + if part != "" { + filtered = append(filtered, part) + } + } + return strings.Join(filtered, ";") +} + +type deviceBindingConflict struct { + Field string + Value string + OtherID string +} + +func detectDeviceBindingConflict(cfg config.DeviceConfig, excludeID string) *deviceBindingConflict { + return detectDeviceBindingConflictInList(cfg, excludeID, config.ListDevices()) +} + +func detectDeviceBindingConflictInList(cfg config.DeviceConfig, excludeID string, devices []config.DeviceConfig) *deviceBindingConflict { + type key struct { + field string + value string + } + keys := make([]key, 0, 5) + if v := strings.TrimSpace(cfg.ModemIMEI); v != "" { + keys = append(keys, key{field: "modem_imei", value: v}) + } + if v := strings.TrimSpace(cfg.ControlDevice); v != "" { + keys = append(keys, key{field: "control_device", value: v}) + } + if v := strings.TrimSpace(cfg.USBPath); v != "" { + keys = append(keys, key{field: "usb_path", value: v}) + } + if v := strings.TrimSpace(cfg.Interface); v != "" { + keys = append(keys, key{field: "interface", value: v}) + } + if v := strings.TrimSpace(cfg.ATPort); v != "" { + keys = append(keys, key{field: "at_port", value: v}) + } + if len(keys) == 0 { + return nil + } + + for _, existing := range devices { + existingID := strings.TrimSpace(existing.ID) + if existingID == "" { + continue + } + if existingID == strings.TrimSpace(excludeID) { + continue + } + for _, k := range keys { + switch k.field { + case "modem_imei": + if strings.TrimSpace(existing.ModemIMEI) == k.value { + return &deviceBindingConflict{Field: k.field, Value: k.value, OtherID: existingID} + } + case "control_device": + if strings.TrimSpace(existing.ControlDevice) == k.value { + return &deviceBindingConflict{Field: k.field, Value: k.value, OtherID: existingID} + } + case "usb_path": + if strings.TrimSpace(existing.USBPath) == k.value { + return &deviceBindingConflict{Field: k.field, Value: k.value, OtherID: existingID} + } + case "interface": + if strings.TrimSpace(existing.Interface) == k.value { + return &deviceBindingConflict{Field: k.field, Value: k.value, OtherID: existingID} + } + case "at_port": + if strings.TrimSpace(existing.ATPort) == k.value { + return &deviceBindingConflict{Field: k.field, Value: k.value, OtherID: existingID} + } + } + } + } + return nil +} + +func (s *Server) handleDeviceMgmtUpdateDevice(c *gin.Context) { + id := deviceIDParam(c) + var req updateDeviceRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"}) + return + } + if strings.TrimSpace(req.Config.ID) != "" && strings.TrimSpace(req.Config.ID) != id { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "不支持修改设备 ID"}) + return + } + + oldMD, err := config.GetDeviceByID(id) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "读取设备配置失败: " + err.Error()}) + return + } + if oldMD == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到"}) + return + } + + req.Config.ID = id + newCfg := deviceConfigFromDTOWithBase(req.Config, oldMD) + newCfg, forcedWarning := normalizeManagedDeviceConfig(newCfg) + if err := validateManagedNetworkConfig(newCfg); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": err.Error()}) + return + } + if conflict := detectDeviceBindingConflict(newCfg, id); conflict != nil { + c.JSON(http.StatusConflict, gin.H{ + "status": "error", + "message": fmt.Sprintf("设备资源冲突:%s=%s 已被设备 %s 使用", conflict.Field, conflict.Value, conflict.OtherID), + }) + return + } + + oldCfg := *oldMD + // 策略跟卡走:设备保存只负责硬件/身份字段,不再触碰策略(策略经 PUT /cards/:iccid/policy 独立编辑)。 + // DTO 仍会回传 network/vowifi/ip/apn,但 GET config 不投影这些字段(恒零),直接采信会把卡策略清空。 + // 故把当前有效策略同时写回 oldCfg 与 newCfg,使其在开关转换判断中互相抵消(中性化), + // 不写 card_policies、不误触发 VoWiFi 关闭重建/恢复射频/热拉起。 + _, effNetwork, effVoWiFi, effIP, effAPN := s.currentEffectiveDevicePolicy(id) + oldCfg.NetworkEnabled = effNetwork + oldCfg.VoWiFiEnabled = effVoWiFi + oldCfg.IPVersion = effIP + oldCfg.APN = effAPN + newCfg.NetworkEnabled = effNetwork + newCfg.VoWiFiEnabled = effVoWiFi + newCfg.IPVersion = effIP + newCfg.APN = effAPN + + requiresRestart := deviceConfigRequiresRestart(oldCfg, newCfg) + if err := config.UpdateDeviceInFile(s.configPath, newCfg.ID, newCfg); err != nil { + logger.Error("写入设备配置失败", "err", err) + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "写入配置失败: " + err.Error()}) + return + } + + worker := s.pool.GetWorker(id) + s.pool.UpdateWorkerConfig(id, newCfg, !requiresRestart) + + // 检测 DeviceBackend 状态变化,或 VoWiFi 从开启变为关闭都需要彻底重建 Worker 释放残余句柄 + needsRebuild := oldCfg.DeviceBackend != newCfg.DeviceBackend || + qmiProxyConfigChanged(oldCfg, newCfg) || + (!newCfg.VoWiFiEnabled && oldCfg.VoWiFiEnabled) || + (worker != nil && managedNetworkConfigChanged(oldCfg, newCfg)) + shouldApplyNetworkNow := worker != nil || needsRebuild + + warningMessage := forcedWarning + if needsRebuild { + logger.Info("配置保存触发底盘或 VoWiFi 停止变更,将彻底重建 Worker", "device", id) + if err := s.pool.RebuildWorker(id); err != nil { + logger.Error("重建 Worker 失败", "device", id, "err", err) + warningMessage = joinWarningMessages(warningMessage, "配置已保存,但运行时重建失败: "+err.Error()) + } + } + + shouldRestoreRadio := oldCfg.VoWiFiEnabled && !newCfg.VoWiFiEnabled + if shouldRestoreRadio { + if s.pool.IsVoWiFiActive(id) { + warningMessage = joinWarningMessages(warningMessage, "VoWiFi 尚未完全退出,暂未恢复射频") + } else if err := s.pool.RestoreRadioAfterVoWiFi(id); err != nil { + logger.Warn("配置保存后恢复射频失败", "device", id, "err", err) + warningMessage = joinWarningMessages(warningMessage, "配置已保存,但恢复射频失败: "+err.Error()) + } + } + + // 检测 VoWiFi 状态变化,仅对于由关到开执行热拉起 + if newCfg.VoWiFiEnabled && !oldCfg.VoWiFiEnabled { + logger.Info("配置保存触发 VoWiFi 启动", "device", id) + if err := s.pool.EnableVoWiFi(id); err != nil { + logger.Error("VoWiFi 启动失败", "device", id, "err", err) + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "requires_restart": requiresRestart, + "warning": joinWarningMessages(warningMessage, "VoWiFi 启动失败: "+err.Error()), + "vowifi_error": "VoWiFi 启动失败: " + err.Error(), + }) + return + } + } + + if shouldApplyNetworkNow && !newCfg.VoWiFiEnabled && !s.pool.IsVoWiFiActive(id) { + if err := s.pool.ApplyConfiguredNetwork(id); err != nil { + logger.Warn("配置保存后自动应用网络偏好失败", "device", id, "err", err) + warningMessage = joinWarningMessages(warningMessage, "配置已保存,但自动应用网络失败: "+err.Error()) + } + } + + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "requires_restart": requiresRestart, + "warning": warningMessage, + }) +} + +func (s *Server) handleDeviceMgmtDeleteDevice(c *gin.Context) { + id := deviceIDParam(c) + + existing, err := config.GetDeviceByID(id) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "读取设备配置失败: " + err.Error()}) + return + } + if existing == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到: " + id}) + return + } + + if err := s.pool.RemoveWorker(id); err != nil { + logger.Warn("删除设备配置前停止运行时设备失败", "device_id", id, "err", err) + if !strings.Contains(err.Error(), "设备未找到") { + c.JSON(http.StatusConflict, gin.H{"status": "error", "message": "设备正在停止,请稍后重试: " + err.Error()}) + return + } + } + + if err := config.DeleteDeviceInFile(s.configPath, id); err != nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"status": "ok"}) +} + +type addDeviceRequest struct { + Config deviceConfigDTO `json:"config"` +} + +// validateDeviceBackendConfig 校验 device_backend 配置合法值。 +// 零路径持久化后 control_device 由运行时从 IMEI 发现,不再作为保存前置条件。 +func validateDeviceBackendConfig(cfg config.DeviceConfig) error { + backend := strings.ToLower(strings.TrimSpace(cfg.DeviceBackend)) + switch backend { + case "", "at", "qmi", "mbim": + // 合法值 + default: + return fmt.Errorf("不支持的 device_backend: %q,可选值: at, qmi, mbim", backend) + } + return nil +} + +func validateFreeDeviceConfigLimit(devices []config.DeviceConfig) error { + if device.FreeDeviceLimitReached(len(devices)) { + return fmt.Errorf("%s", device.FreeDeviceAddLimitMessage()) + } + return nil +} + +func (s *Server) handleDeviceMgmtAddDevice(c *gin.Context) { + var req addDeviceRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"}) + return + } + newCfg := deviceConfigFromDTO(req.Config) + newCfg = deviceConfigForAdd(newCfg) + newCfg, forcedWarning := normalizeManagedDeviceConfig(newCfg) + if strings.TrimSpace(newCfg.ID) == "" { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "必须填写 id"}) + return + } + if err := validateManagedNetworkConfig(newCfg); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": err.Error()}) + return + } + + if existing, err := config.GetDeviceByID(newCfg.ID); err == nil && existing != nil { + c.JSON(http.StatusConflict, gin.H{"status": "error", "message": "设备 ID 已存在"}) + return + } + if conflict := detectDeviceBindingConflict(newCfg, ""); conflict != nil { + c.JSON(http.StatusConflict, gin.H{ + "status": "error", + "message": fmt.Sprintf("设备资源冲突:%s=%s 已被设备 %s 使用", conflict.Field, conflict.Value, conflict.OtherID), + }) + return + } + if err := validateFreeDeviceConfigLimit(config.ListDevices()); err != nil { + c.JSON(http.StatusConflict, gin.H{"status": "error", "message": err.Error()}) + return + } + // MBIM 设备使用 MBIM DeviceCaps 探测 IMEI,非 MBIM 设备使用 QMI 探测 + if strings.ToLower(strings.TrimSpace(newCfg.DeviceBackend)) == "mbim" { + if config.NormalizeIMEI(newCfg.ModemIMEI) == "" && strings.TrimSpace(newCfg.ControlDevice) != "" { + if mbimIMEI, err := device.ProbeIMEIViaMBIM(newCfg.ControlDevice); err == nil && mbimIMEI != "" { + newCfg.ModemIMEI = mbimIMEI + } + } + } else { + enrichedCfg, imeiErr := ensureAddDeviceIMEI(newCfg, probeIMEIForAddFn) + if imeiErr != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": imeiErr.Error()}) + return + } + newCfg = enrichedCfg + } + + if err := config.AddDeviceInFile(s.configPath, newCfg); err != nil { + logger.Error("写入新设备配置失败", "err", err) + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "写入配置失败: " + err.Error()}) + return + } + + if _, err := s.pool.AddWorkerFromConfig(newCfg); err != nil { + logger.Warn("设备配置已添加,但启动运行时设备失败", "device_id", newCfg.ID, "err", err) + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "started": false, + "requires_restart": true, + "warning": "设备配置已添加,但运行时启动失败(可尝试重启服务或检查端口/权限): " + err.Error(), + }) + return + } + + warningMessage := forcedWarning + + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "started": true, + "requires_restart": false, + "warning": warningMessage, + }) +} + +type executeATRequest struct { + Cmd string `json:"cmd"` + TimeoutMs int `json:"timeout_ms"` +} + +type manualATSession interface { + Execute(cmd string, timeout time.Duration) (string, error) + Close() error +} + +var openManualATSession = func(port string) (manualATSession, error) { + return modem.NewSerialAT(port, 115200, 8, 1, "N") +} + +func executeManualATOnPort(port, cmd string, timeout time.Duration) (string, error) { + port = strings.TrimSpace(port) + if port == "" { + return "", fmt.Errorf("当前设备没有可用 AT 端口") + } + session, err := openManualATSession(port) + if err != nil { + return "", fmt.Errorf("打开 AT 端口 %s 失败: %w", port, err) + } + defer session.Close() + return session.Execute(cmd, timeout) +} + +func manualATPortForWorker(worker *device.Worker) string { + return worker.ResolvedATPort() +} + +func (s *Server) handleDeviceMgmtExecuteAT(c *gin.Context) { + id := deviceIDParam(c) + var req executeATRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"}) + return + } + cmd := strings.TrimSpace(req.Cmd) + if cmd == "" { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "cmd 不能为空"}) + return + } + if len(cmd) > 512 { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "cmd 过长"}) + return + } + + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到或未运行"}) + return + } + + timeout := 10 * time.Second + if req.TimeoutMs > 0 { + timeout = time.Duration(req.TimeoutMs) * time.Millisecond + } + if timeout > 60*time.Second { + timeout = 60 * time.Second + } + + if worker.Backend != nil && isTransientATBackend(worker.Backend.Mode()) { + resp, err := executeManualATOnPort(manualATPortForWorker(worker), cmd, timeout) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ok", "response": resp}) + return + } + + if worker.Modem == nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "当前设备没有可用 AT 管理器"}) + return + } + if !worker.Modem.HasATPort() { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "当前设备没有可用 AT 端口"}) + return + } + if !worker.Modem.CanExecuteAT() { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "AT 管理器未启动或不可用"}) + return + } + resp, err := worker.Modem.ExecuteAT(cmd, timeout) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ok", "response": resp}) +} + +func isTransientATBackend(mode string) bool { + return mode == backend.BackendQMI || mode == backend.BackendMBIM +} + +type setUSBNetModeRequest struct { + Mode int `json:"mode"` +} + +func (s *Server) handleDeviceMgmtSetUSBNetMode(c *gin.Context) { + id := deviceIDParam(c) + var req setUSBNetModeRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"}) + return + } + + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到或未运行"}) + return + } + + if worker.Modem == nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "当前设备为纯 QMI 模式,不支持 USBNET 模式设置"}) + return + } + if err := worker.Modem.SetUSBNetMode(req.Mode); err != nil { + logger.Error("设置 USBNET 模式失败", "device", id, "err", err) + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "设置模式失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "指令已发送,设备正在重启..."}) +} + +// handleEsimListProfiles 获取 eSIM Profile 列表 +func (s *Server) handleEsimListProfiles(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + refresh := c.Query("refresh") == "true" + if refresh { + if err := worker.EsimMgr.RefreshProfiles(); err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "refresh_profiles", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + + profiles, err := worker.EsimMgr.GetProfiles() + if err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "list_profiles", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, profiles) +} + +// esimSwitchRequest 包含切换的目标 ICCID +type esimSwitchRequest struct { + ICCID string `json:"iccid" binding:"required"` + AIDHex string `json:"aid_hex"` // 可选,前端已知时直接传,跳过遍历 +} + +type esimSwitchResponse struct { + Message string `json:"message"` + TargetICCID string `json:"target_iccid"` + SwitchToken uint64 `json:"switch_token"` + SwitchPhase string `json:"switch_phase"` + SwitchAccepted bool `json:"switch_accepted"` + RecoveryPending bool `json:"recovery_pending"` + DegradedReason string `json:"degraded_reason,omitempty"` + PostSwitchAsync bool `json:"post_switch_async"` + CachePatched bool `json:"cache_patched"` + SIMReloadAttempted bool `json:"sim_reload_attempted"` + SIMReloadOK bool `json:"sim_reload_ok"` + SIMReloadWarning string `json:"sim_reload_warning,omitempty"` +} + +const esimBusyRetryAfterMs = 1200 + +func isEsimBusyError(err error) bool { + return errors.Is(err, esim.ErrOperationInProgress) || errors.Is(err, apduarbiter.ErrAPDUBusy) +} + +func esimDeleteHTTPStatus(err error) int { + switch { + case isEsimBusyError(err) || esim.IsDeleteProfileBusy(err): + return http.StatusConflict + case esim.IsDeleteProfileInvalidInput(err): + return http.StatusBadRequest + case esim.IsDeleteProfileNotFound(err): + return http.StatusNotFound + default: + return http.StatusInternalServerError + } +} + +func respondEsimBusy(c *gin.Context, reason string, err error) { + retryAfterSec := (esimBusyRetryAfterMs + 999) / 1000 + c.Header("Retry-After", strconv.Itoa(retryAfterSec)) + c.JSON(http.StatusConflict, gin.H{ + "error": err.Error(), + "busy": true, + "code": "ESIM_BUSY", + "reason": reason, + "retryAfterMs": esimBusyRetryAfterMs, + }) +} + +func esimDeleteSuccessBody(result esim.DeleteProfileResult) gin.H { + body := gin.H{ + "status": "ok", + "message": "Profile 删除成功", + } + if warning := strings.TrimSpace(result.Warning); warning != "" { + body["warning"] = warning + } + if warningCode := strings.TrimSpace(result.WarningCode); warningCode != "" { + body["warning_code"] = warningCode + } + if result.SpaceDelta != nil { + body["space_delta"] = result.SpaceDelta + } + return body +} + +func formatEsimDownloadDoneEvent(result esim.DownloadProfileResult) string { + base := `{"step":"done","msg":"Profile 下载完成","pct":100` + if result.SpaceDelta != nil { + spaceDeltaJSON, err := json.Marshal(result.SpaceDelta) + if err == nil { + base += fmt.Sprintf(`,"space_delta":%s`, spaceDeltaJSON) + } + } + if warning := strings.TrimSpace(result.Warning); warning != "" { + base += fmt.Sprintf(`,"warning":%q`, warning) + } + if warningCode := strings.TrimSpace(result.WarningCode); warningCode != "" { + base += fmt.Sprintf(`,"warning_code":%q`, warningCode) + } + return base + `}` +} + +func formatEsimDownloadErrorEvent(err error) string { + msg := "下载失败" + var downloadErr *esim.DownloadProfileError + if errors.As(err, &downloadErr) && downloadErr != nil { + if downloadErr.Message != "" { + msg += ": " + downloadErr.Message + } else if err != nil { + msg += ": " + err.Error() + } + base := fmt.Sprintf(`{"step":"error","msg":%q,"pct":-1`, msg) + if code := strings.TrimSpace(downloadErr.Code); code != "" { + base += fmt.Sprintf(`,"code":%q`, code) + } + if details := strings.TrimSpace(downloadErr.Details); details != "" { + base += fmt.Sprintf(`,"details":%q`, details) + } + return base + `}` + } + if err != nil { + msg += ": " + err.Error() + } + return fmt.Sprintf(`{"step":"error","msg":%q,"pct":-1}`, msg) +} + +func writeEsimDownloadDoneEvent(c *gin.Context, result esim.DownloadProfileResult) { + fmt.Fprintf(c.Writer, "data: %s\n\n", formatEsimDownloadDoneEvent(result)) + if flusher, ok := c.Writer.(http.Flusher); ok { + flusher.Flush() + } +} + +func writeEsimDownloadErrorEvent(c *gin.Context, err error) { + fmt.Fprintf(c.Writer, "data: %s\n\n", formatEsimDownloadErrorEvent(err)) + if flusher, ok := c.Writer.(http.Flusher); ok { + flusher.Flush() + } +} + +func writeEsimDeleteSuccessJSON(c *gin.Context, result esim.DeleteProfileResult) { + c.JSON(http.StatusOK, esimDeleteSuccessBody(result)) +} + +func esimDownloadExec(run func(context.Context, string, string, string, string, string, esim.DownloadProgressFn) (esim.DownloadProfileResult, error), ctx context.Context, aidHex, smdp, matchingID, confirmationCode, imei string, progressFn esim.DownloadProgressFn) (esim.DownloadProfileResult, error) { + return run(ctx, aidHex, smdp, matchingID, confirmationCode, imei, progressFn) +} + +var esimNotificationListExec = func(run func(string) ([]esim.NotificationItem, error), aidHex string) ([]esim.NotificationItem, error) { + return run(aidHex) +} + +var esimNotificationRetryExec = func(run func(int64, string) error, sequence int64, aidHex string) error { + return run(sequence, aidHex) +} + +func esimDeleteExec(run func(string, string) (esim.DeleteProfileResult, error), iccid, aidHex string) (esim.DeleteProfileResult, error) { + return run(iccid, aidHex) +} + +func esimNotificationHTTPStatus(err error) int { + switch esim.ClassifyNotificationError(err) { + case esim.NotificationErrorBusy: + return http.StatusConflict + case esim.NotificationErrorInvalidSequence, esim.NotificationErrorInvalidAIDHex: + return http.StatusBadRequest + case esim.NotificationErrorNotFound: + return http.StatusNotFound + default: + return http.StatusInternalServerError + } +} + +func (s *Server) handleEsimListNotifications(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + items, err := esimNotificationListExec(worker.EsimMgr.ListNotifications, strings.TrimSpace(c.Query("aid_hex"))) + if err != nil { + if esimNotificationHTTPStatus(err) == http.StatusConflict { + respondEsimBusy(c, "list_notifications", err) + return + } + c.JSON(esimNotificationHTTPStatus(err), gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"items": items}) +} + +func (s *Server) handleEsimRetryNotification(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + sequence, err := strconv.ParseInt(strings.TrimSpace(c.Param("sequence")), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "无效的通知序号"}) + return + } + err = esimNotificationRetryExec(worker.EsimMgr.RetryNotification, sequence, strings.TrimSpace(c.Query("aid_hex"))) + if err != nil { + if esimNotificationHTTPStatus(err) == http.StatusConflict { + respondEsimBusy(c, "retry_notification", err) + return + } + c.JSON(esimNotificationHTTPStatus(err), gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "通知重试发送成功"}) +} + +// handleEsimSwitchProfile 切换 eSIM Profile +func (s *Server) handleEsimSwitchProfile(c *gin.Context) { + id := deviceIDParam(c) + var req esimSwitchRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + // Profile 切换:EnableProfile 后等待目标 profile 生效;切卡后按 Ready+Delay 门控执行后处理(不等待搜网) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + result, err := worker.EsimMgr.SwitchProfileWithResult(ctx, req.ICCID, req.AIDHex) + if err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "switch_profile", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "esim配置切换失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, esimSwitchResponse{ + Message: "eSIM Profile 切换指令已提交,设备信息将异步刷新", + TargetICCID: result.TargetICCID, + SwitchToken: result.SwitchToken, + SwitchPhase: string(result.Phase), + SwitchAccepted: result.SwitchAccepted, + RecoveryPending: result.RecoveryPending, + DegradedReason: result.DegradedReason, + PostSwitchAsync: result.PostSwitchAsync, + CachePatched: result.CachePatched, + SIMReloadAttempted: result.PowerCycleAttempt, + SIMReloadOK: result.PowerCycleAttempt && result.SIMReloadWarning == "", + SIMReloadWarning: result.SIMReloadWarning, + }) + +} + +// handleEsimGetEID 获取所有 eUICC 的 EID 列表 +func (s *Server) handleEsimGetEID(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + eids, err := worker.EsimMgr.GetEIDs() + if err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "get_eids", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"eids": eids}) +} + +// handleEsimGetChipInfo 获取 eUICC 芯片硬件信息(名称、序列号、固件版本、可用空间) +func (s *Server) handleEsimGetChipInfo(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + forceRefresh := c.Query("refresh") == "true" + chipInfo, err := worker.EsimMgr.GetEUICCChipInfo(forceRefresh) + if err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "get_chip_info", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, chipInfo) +} + +// handleEsimGetOverview 获取 eSIM 总览(合并芯片信息和 profiles) +func (s *Server) handleEsimGetOverview(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + refresh := c.Query("refresh") == "true" + if refresh { + if err := worker.EsimMgr.RefreshOverview(); err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "refresh_overview", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + + overview, err := worker.EsimMgr.GetEsimOverview() + if err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "get_overview", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, overview) +} + +// handleEsimDownloadProfile 下载 eSIM profile(SSE 流式进度推送) +// +// 请求方式:GET,通过 Query 参数传递下载参数: +// +// smdp=(必填) +// matching_id=(可选) +// confirmation_code=<确认码>(可选) +// aid_hex=<目标 AID hex>(可选) +// imei=<下载使用的 IMEI>(可选) +// +// 响应为 text/event-stream,每条事件 data 为 JSON: +// +// {"step":"preflight","msg":"正在检查 eUICC 剩余空间...","pct":10} +// {"step":"auth_client","msg":"...","pct":30} +// {"step":"auth_server","msg":"...","pct":60} +// {"step":"install","msg":"...","pct":80} +// {"step":"notify","msg":"...","pct":90} +// {"step":"done","msg":"Profile 下载完成","pct":100} +// {"step":"error","msg":"<错误信息>","pct":-1} +func (s *Server) handleEsimDownloadProfile(c *gin.Context) { + id := deviceIDParam(c) + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + smdp := strings.TrimSpace(c.Query("smdp")) + if smdp == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "smdp 为必填项"}) + return + } + matchingID := c.Query("matching_id") + confirmationCode := c.Query("confirmation_code") + aidHex := c.Query("aid_hex") + imei := strings.TrimSpace(c.Query("imei")) + + // 设置 SSE 响应头 + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-cache") + c.Header("Connection", "keep-alive") + c.Header("X-Accel-Buffering", "no") + + flusher, ok := c.Writer.(http.Flusher) + if !ok { + c.JSON(http.StatusInternalServerError, gin.H{"error": "流式输出不支持"}) + return + } + + // sseWrite 向客户端推送一条 SSE 事件 + sseWrite := func(step, msg string, pct int) { + fmt.Fprintf(c.Writer, "data: {\"step\":%q,\"msg\":%q,\"pct\":%d}\n\n", step, msg, pct) + flusher.Flush() + } + sseWriteRaw := func(payload string) { + fmt.Fprintf(c.Writer, "data: %s\n\n", payload) + flusher.Flush() + } + + // 下载可能耗时较长,给 5 分钟超时 + ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Minute) + defer cancel() + + progressFn := func(event esim.DownloadProgressEvent) { + sseWrite(event.Step, event.Msg, event.Pct) + } + + result, err := esimDownloadExec(worker.EsimMgr.DownloadProfile, ctx, aidHex, smdp, matchingID, confirmationCode, imei, progressFn) + if err != nil { + writeEsimDownloadErrorEvent(c, err) + return + } + _ = sseWriteRaw + writeEsimDownloadDoneEvent(c, result) +} + +// handleEsimRenameProfile 修改 eSIM profile 名称 +func (s *Server) handleEsimRenameProfile(c *gin.Context) { + id := deviceIDParam(c) + iccid := c.Param("iccid") + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + var req struct { + Name string `json:"name"` + AIDHex string `json:"aid_hex"` + } + if err := c.ShouldBindJSON(&req); err != nil || req.Name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "name 为必填项"}) + return + } + + if err := worker.EsimMgr.RenameProfile(iccid, req.Name, req.AIDHex); err != nil { + if isEsimBusyError(err) { + respondEsimBusy(c, "rename_profile", err) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "修改名称失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "Profile 名称修改成功"}) +} + +// handleEsimDeleteProfile 删除 eSIM profile +func (s *Server) handleEsimDeleteProfile(c *gin.Context) { + id := deviceIDParam(c) + iccid := c.Param("iccid") + worker := s.pool.GetWorker(id) + if worker == nil || worker.EsimMgr == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"}) + return + } + + if iccid == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "iccid 为必填项"}) + return + } + + aidHex := strings.TrimSpace(c.Query("aid_hex")) + + result, err := esimDeleteExec(worker.EsimMgr.DeleteProfile, iccid, aidHex) + if err != nil { + // 删除主路径当前是阻塞等待写锁,通常不会快速返回 busy; + // 保留该分支用于底层未来显式返回 busy 的防御处理。 + if esimDeleteHTTPStatus(err) == http.StatusConflict { + respondEsimBusy(c, "delete_profile", err) + return + } + c.JSON(esimDeleteHTTPStatus(err), gin.H{"error": "删除 profile 失败: " + err.Error()}) + return + } + + writeEsimDeleteSuccessJSON(c, result) +} + +type executeUSSDRequest struct { + Command string `json:"command" binding:"required"` + TimeoutMs int `json:"timeout_ms"` +} + +// handleDeviceMgmtExecuteUSSD 执行 USSD 指令 +// 路由策略:VoWiFi 在线时优先使用 VoWiFi 通道,否则回退到 CS 域 +func (s *Server) handleDeviceMgmtExecuteUSSD(c *gin.Context) { + id := deviceIDParam(c) + var req executeUSSDRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误: " + err.Error()}) + return + } + + cmd := strings.TrimSpace(req.Command) + if cmd == "" { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "command 不能为空"}) + return + } + + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到"}) + return + } + + timeout := 45 * time.Second // 默认 45 秒(与 CS 域 USSD 一致) + if req.TimeoutMs > 0 { + timeout = time.Duration(req.TimeoutMs) * time.Millisecond + } + if timeout > 120*time.Second { + timeout = 120 * time.Second + } + + // VoWiFi 在线时优先走 VoWiFi + if s.pool.IsVoWiFiActive(id) { + ctx, cancel := context.WithTimeout(c.Request.Context(), timeout) + defer cancel() + resp, err := s.pool.SendVoWiFiUSSD(ctx, id, cmd) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error(), "channel": "vowifi"}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ok", "result": resp, "channel": "vowifi"}) + return + } + + // 回退到 CS 域 USSD + provider, ok := worker.Backend.(backend.USSDProvider) + if !ok || provider == nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "当前设备后端不支持 USSD"}) + return + } + resp, err := provider.ExecuteUSSD(c.Request.Context(), cmd, timeout) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error(), "channel": "cs"}) + return + } + markCSUSSDSession(resp) + c.JSON(http.StatusOK, gin.H{"status": "ok", "result": resp, "channel": "cs"}) +} + +type continueUSSDRequest struct { + SessionID string `json:"session_id" binding:"required"` + Input string `json:"input" binding:"required"` + TimeoutMs int `json:"timeout_ms"` +} + +// handleDeviceMgmtContinueUSSD 发送 USSD 后续输入(多轮菜单选择) +func (s *Server) handleDeviceMgmtContinueUSSD(c *gin.Context) { + id := deviceIDParam(c) + var req continueUSSDRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误: " + err.Error()}) + return + } + + input := strings.TrimSpace(req.Input) + if input == "" { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "input 不能为空"}) + return + } + + timeout := 45 * time.Second + if req.TimeoutMs > 0 { + timeout = time.Duration(req.TimeoutMs) * time.Millisecond + } + if timeout > 120*time.Second { + timeout = 120 * time.Second + } + + if !s.pool.IsVoWiFiActive(id) { + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到"}) + return + } + provider, ok := worker.Backend.(backend.USSDContinueProvider) + if !ok || provider == nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "当前设备后端不支持多轮 USSD"}) + return + } + resp, err := provider.ContinueUSSD(c.Request.Context(), input, timeout) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error(), "channel": "cs"}) + return + } + markCSUSSDSession(resp) + c.JSON(http.StatusOK, gin.H{"status": "ok", "result": resp, "channel": "cs"}) + return + } + + ctx, cancel := context.WithTimeout(c.Request.Context(), timeout) + defer cancel() + resp, err := s.pool.ContinueVoWiFiUSSD(ctx, id, req.SessionID, input) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ok", "result": resp, "channel": "vowifi"}) +} + +type cancelUSSDRequest struct { + SessionID string `json:"session_id"` +} + +// handleDeviceMgmtCancelUSSD 取消活跃的 USSD 会话 +func (s *Server) handleDeviceMgmtCancelUSSD(c *gin.Context) { + id := deviceIDParam(c) + var req cancelUSSDRequest + if err := c.ShouldBindJSON(&req); err != nil { + // session_id 是可选的 + req.SessionID = "" + } + + if !s.pool.IsVoWiFiActive(id) { + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到"}) + return + } + provider, ok := worker.Backend.(backend.USSDProvider) + if !ok || provider == nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "当前设备后端不支持 USSD 取消"}) + return + } + if err := provider.CancelUSSD(c.Request.Context()); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "USSD 会话已取消", "channel": "cs"}) + return + } + + if err := s.pool.CancelVoWiFiUSSD(c.Request.Context(), id, req.SessionID); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "USSD 会话已取消"}) +} + +func markCSUSSDSession(resp *backend.USSDResult) { + if resp != nil && resp.Status == 1 { + resp.SessionID = "cs" + } +} + +// handleDeviceMgmtReboot 执行模组重启 (发送 AT+CFUN=1,1) +func (s *Server) handleDeviceMgmtSetFlightMode(c *gin.Context) { + id := deviceIDParam(c) + if id == "" { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"}) + return + } + + if s.pool == nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"status": "error", "message": "服务未就绪"}) + return + } + + var req setFlightModeRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "参数错误"}) + return + } + + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到或未运行"}) + return + } + if s.pool.IsESIMSwitching(id) { + c.JSON(http.StatusConflict, gin.H{"status": "error", "message": "设备正在切卡,请稍后再切换飞行模式"}) + return + } + + if s.pool.IsVoWiFiActive(id) { + c.JSON(http.StatusConflict, gin.H{"status": "error", "message": "VoWiFi 正在接管飞行模式,请先停用或退出 VoWiFi"}) + return + } + + flightModeEnabled := req.Enabled + + // 先落库卡策略(飞行模式跟卡走):开飞行与 network/vowifi 互斥,关飞行仅清 airplane。 + // best-effort:落库失败不阻断热切(与 network/vowifi 热切路径一致)。 + s.patchCardPolicyForDevice(id, func(p *db.CardPolicy) { + if flightModeEnabled { + p.AirplaneEnabled = true + p.VoWiFiEnabled = false + p.NetworkEnabled = false + } else { + p.AirplaneEnabled = false + } + }) + // 同步 w.Config,使概览即时反映飞行/在线模式(setWorkerFlightMode 只切硬件不碰 Config)。 + s.pool.SetWorkerAirplanePolicy(id, flightModeEnabled) + + operatingMode, flightMode, err := setWorkerFlightMode(c.Request.Context(), worker, flightModeEnabled) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "切换飞行模式失败: " + err.Error()}) + return + } + go func(disabled bool) { + _ = worker.RefreshRuntime(nil, "flight_mode_change") + if !disabled { + // 切回在线后补一次延迟刷新,覆盖“先注册后PLMN”恢复窗口。 + time.Sleep(3 * time.Second) + _ = worker.RefreshRuntime(nil, "flight_mode_recover") + } + }(!flightModeEnabled) + + c.JSON(http.StatusOK, gin.H{ + "status": "ok", + "message": flightModeSuccessMessage(flightModeEnabled), + "operating_mode": operatingMode, + "flight_mode": flightMode, + }) +} + +// shouldUseATFirstReboot 判断重启时是否应优先尝试 AT+CFUN=1,1。 +// QMI 模式设备直接走 QMI ModeReset(backend.Reboot);AT 优先路径仅保留给 AT 模式设备, +// 原先"QMI 模式也优先走 AT"是为了规避部分模组 QMI ModeReset 假死的历史问题, +// 现已实测确认本机型号 QMI ModeReset 正常工作,因此 QMI 模式不再绕道 AT。 +func shouldUseATFirstReboot(backendMode string) bool { + return backendMode != backend.BackendQMI +} + +// handleDeviceMgmtReboot 执行模组重启 (QMI 模式走 QMI ModeReset,AT 模式走 AT+CFUN=1,1) +func (s *Server) handleDeviceMgmtReboot(c *gin.Context) { + id := deviceIDParam(c) + + worker := s.pool.GetWorker(id) + if worker == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备未找到"}) + return + } + + if err := validateRebootWorkerIdentity(c.Request.Context(), worker); err != nil { + c.JSON(http.StatusConflict, gin.H{"status": "error", "message": err.Error()}) + return + } + + rebootSent := false + + useATFirst := worker.Backend == nil || shouldUseATFirstReboot(worker.Backend.Mode()) + + // AT 模式设备优先尝试使用 AT 端口软重启;QMI 模式设备直接走 QMI ModeReset(见下方 fallback) + if useATFirst && worker.Modem != nil && worker.Modem.HasATPort() && worker.Modem.CanExecuteAT() { + _, err := worker.Modem.ExecuteAT("AT+CFUN=1,1", 20*time.Second) + if err == nil { + rebootSent = true + } else { + // 如果发送后立刻断开,可能会报错,视同成功发送 + msg := strings.ToLower(err.Error()) + if strings.Contains(msg, "timeout") || strings.Contains(msg, "eof") || strings.Contains(msg, "closed") || strings.Contains(msg, "no such file") { + rebootSent = true + } + } + } + + // QMI 模式设备的主路径;AT 模式设备在 AT 端口不可用/发送失败时的降级路径 + if !rebootSent && worker.Backend != nil { + if err := worker.Backend.Reboot(c.Request.Context()); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "重启指令失败: " + err.Error()}) + return + } + rebootSent = true + } + + if !rebootSent { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "无法发送重启指令,无可用通道"}) + return + } + + s.pool.MarkLifecycleRecovery(id, device.LifecyclePhaseRebooting, "manual_reboot", 3*time.Minute) + s.pool.ScheduleModemRebootRecovery(id, "manual_reboot") + + // 因为重启后设备会脱网并暂时下线,前端仅需知道命令已送达 + c.JSON(http.StatusOK, gin.H{"status": "ok", "response": "重启指令已发送"}) +} + +func validateRebootWorkerIdentity(ctx context.Context, worker *device.Worker) error { + if worker == nil || worker.Backend == nil { + return nil + } + expectedIMEI := strings.TrimSpace(worker.Config.ModemIMEI) + if expectedIMEI == "" { + return nil + } + probeCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + currentIMEI, err := worker.Backend.GetIMEI(probeCtx) + if err != nil || strings.TrimSpace(currentIMEI) == "" { + return nil + } + currentIMEI = strings.TrimSpace(currentIMEI) + if !config.IMEIMatches(currentIMEI, expectedIMEI) { + return fmt.Errorf("设备路径已漂移:当前控制面 IMEI=%s,不匹配配置 IMEI=%s,请先重新扫描/重新绑定后再重启", currentIMEI, expectedIMEI) + } + return nil +} + +// handleDeviceMgmtReconnectVoWiFi 执行重连 VoWiFi 的操作 +func (s *Server) handleDeviceMgmtReconnectVoWiFi(c *gin.Context) { + id := deviceIDParam(c) + + // 验证设备存在(硬件/传输配置仍在 config.yaml) + md, err := config.GetDeviceByID(id) + if err != nil || md == nil { + c.JSON(http.StatusNotFound, gin.H{"status": "error", "message": "设备配置不存在"}) + return + } + + // VoWiFi 开关已跟卡走、只存在于运行时投影。门禁读 worker 的有效策略; + // 无 worker 时跳过友好门禁,交由 RestartVoWiFi 报告底层错误。 + if worker := s.pool.GetWorker(id); worker != nil && !worker.Config.VoWiFiEnabled { + c.JSON(http.StatusBadRequest, gin.H{"status": "error", "message": "设备未开启 VoWiFi,无法重连"}) + return + } + + if err := s.pool.RestartVoWiFi(id); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "VoWiFi 重连失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "已触发 VoWiFi 重连"}) +} + +// handleDeviceMgmtOverviewStreamSingle 给前端管理的概览信息提供带有动态刷新的 SSE 推流(仅针对选中的单个设备) +func (s *Server) handleDeviceMgmtOverviewStreamSingle(c *gin.Context) { + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-cache") + c.Header("Connection", "keep-alive") + + deviceID := deviceIDParam(c) + if deviceID == "" { + return + } + + worker := s.pool.GetWorker(deviceID) + if worker != nil { + worker.IncStreamSub() + defer worker.DecStreamSub() + } + + notify := c.Writer.CloseNotify() + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + + // 订阅 VoWiFi 运行态变更——状态一变(如 IMS 注册成功)立即推送,无需等待 Ticker。 + // 若 VoWiFi 未启动则 stateCh 为 nil,nil channel 在 select 中永远阻塞,行为安全。 + stateCh, unsubState := s.pool.SubscribeVoWiFiState(deviceID) + defer unsubState() + trafficStream := overviewTrafficStreamState{ + subscriber: s.trafficRT, + deviceID: deviceID, + ctx: c.Request.Context(), + } + defer trafficStream.stop() + var trafficCh <-chan proxytraffic.RealtimeSnapshot + + var ( + cachedCfg *config.DeviceConfig + lastSent *overviewStreamEmitVersion + ) + getConfig := func(refresh bool) *config.DeviceConfig { + if !refresh && cachedCfg != nil { + return cachedCfg + } + md, _ := config.GetDeviceByID(deviceID) + cachedCfg = md + return md + } + + sendData := func(refreshConfig bool, fromStateEvent bool) { + md := getConfig(refreshConfig) + if md == nil { + return + } + var item deviceMgmtOverviewLiteItem + + w := s.pool.GetWorker(deviceID) + if w != nil { + status := w.GetCachedDeviceStatus() + trueVal := true + // 用运行时投影(w.Config)合并展示,使策略字段反映跟卡走的有效值 + item = s.buildOverviewLiteDetailItemFromWorker(w, overviewDisplayConfig(w.Config, *md, true), status, &trueVal) + if overviewRealtimeTrafficEnabled(item) { + tag := w.ID + "@" + md.Interface + ps, rx, tx, _ := db.GetLatestMinuteDeltas("iface", tag) + item.Traffic, item.TrafficRaw, item.TrafficMeta = buildTrafficOverviewFields(md.Interface, db.LatestMinuteDeltas{ + PeriodStart: ps, + RxBytes: rx, + TxBytes: tx, + }, time.Now()) + } + } else { + trueVal := true + pol := resolveOfflineDevicePolicy(deviceID) + item = deviceMgmtOverviewLiteItem{ + ID: md.ID, + Name: md.Name, + Running: false, + Healthy: false, + ControlOnline: false, + PublicIP: "", + Interface: md.Interface, + ControlDevice: md.ControlDevice, + ESIMTransport: config.NormalizeESIMTransport(md.ESIMTransport), + ATPort: md.ATPort, + AudioDevice: md.AudioDevice, + SMSEnabled: pol.SMSEnabled, + NetworkEnabled: pol.NetworkEnabled, + VoWiFiEnabled: pol.VoWiFiEnabled, + VoWiFiActive: false, + NetworkConnected: false, + RegistrationStateLabel: registrationStateLabel(0), + RadioLiveOK: &trueVal, + Modem: modem.DeviceStatus{}, + Traffic: nil, + BackendMode: resolveOfflineBackendMode(*md), + } + s.applyLifecycleToOverviewLiteItem(&item, nil, *md) + } + + trafficCh = trafficStream.sync(item) + curr := newOverviewStreamEmitVersion(item) + if fromStateEvent && shouldSkipOverviewStatePush(lastSent, curr) { + return + } + lastSent = &curr + if fromStateEvent { + phase := "" + if item.VoWiFiRuntime != nil { + phase = item.VoWiFiRuntime.Phase + } + logger.Debug("overview SSE 推送 VoWiFi 状态变更", "device", deviceID, "phase", phase) + } + + // 仍然使用 devices 结构体包裹返回单项从而无缝对接前台旧结构 + c.SSEvent("overview", gin.H{"devices": []deviceMgmtOverviewLiteItem{item}}) + c.Writer.Flush() + } + + sendData(true, false) + + for { + select { + case <-notify: + return + case <-c.Request.Context().Done(): + return + case <-s.shutdownCh: + return + case <-ticker.C: + sendData(true, false) + case <-stateCh: // VoWiFi 状态变化(隧道建立/IMS 注册/SMS 就绪等),立即推送 + sendData(false, true) + case snap, ok := <-trafficCh: + if !ok { + trafficStream.stop() + trafficCh = nil + continue + } + c.SSEvent("traffic", snap) + c.Writer.Flush() + } + } +} + +type overviewTrafficStreamState struct { + subscriber realtimeTrafficSubscriber + deviceID string + ctx context.Context + ch <-chan proxytraffic.RealtimeSnapshot + unsubscribe func() +} + +func (s *overviewTrafficStreamState) sync(item deviceMgmtOverviewLiteItem) <-chan proxytraffic.RealtimeSnapshot { + if s == nil || s.subscriber == nil || s.deviceID == "" { + return nil + } + if !overviewRealtimeTrafficEnabled(item) { + s.stop() + return nil + } + if s.ch != nil { + return s.ch + } + ctx := s.ctx + if ctx == nil { + ctx = context.Background() + } + s.ch, s.unsubscribe = s.subscriber.Subscribe(ctx, s.deviceID) + return s.ch +} + +func (s *overviewTrafficStreamState) stop() { + if s == nil { + return + } + if s.unsubscribe != nil { + s.unsubscribe() + } + s.ch = nil + s.unsubscribe = nil +} + +func overviewRealtimeTrafficEnabled(item deviceMgmtOverviewLiteItem) bool { + return item.NetworkEnabled && item.NetworkConnected +} + +func resolveOfflineBackendMode(cfg config.DeviceConfig) string { + m := strings.ToLower(strings.TrimSpace(cfg.DeviceBackend)) + if m == "" && strings.TrimSpace(cfg.ControlDevice) != "" { + return "qmi" + } + if m == "qmi" { + return "qmi" + } + return "at" +} diff --git a/internal/api/device_mgmt_add_imei_test.go b/internal/api/device_mgmt_add_imei_test.go new file mode 100644 index 00000000..d83213d3 --- /dev/null +++ b/internal/api/device_mgmt_add_imei_test.go @@ -0,0 +1,60 @@ +package api + +import ( + "errors" + "testing" + + "github.com/iniwex5/vohive/internal/config" +) + +func TestEnsureAddDeviceIMEIBackfillsWhenEmpty(t *testing.T) { + cfg := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2"} + probe := func(controlPath string) (string, error) { + if controlPath != "/dev/cdc-wdm2" { + t.Fatalf("probe got %q", controlPath) + } + return "864388041069422", nil + } + + got, err := ensureAddDeviceIMEI(cfg, probe) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got.ModemIMEI != "864388041069422" { + t.Fatalf("ModemIMEI = %q, want probed value", got.ModemIMEI) + } +} + +func TestEnsureAddDeviceIMEIRejectsWhenProbeFails(t *testing.T) { + cfg := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2"} + probe := func(string) (string, error) { return "", errors.New("timeout") } + + if _, err := ensureAddDeviceIMEI(cfg, probe); err == nil { + t.Fatal("expected error when probe fails, got nil") + } +} + +func TestEnsureAddDeviceIMEIRejectsWhenProbeEmpty(t *testing.T) { + cfg := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2"} + probe := func(string) (string, error) { return " ", nil } + + if _, err := ensureAddDeviceIMEI(cfg, probe); err == nil { + t.Fatal("expected error when probe returns blank, got nil") + } +} + +func TestEnsureAddDeviceIMEILeavesExistingIMEIAndATOnly(t *testing.T) { + withIMEI := config.DeviceConfig{ID: "ec20-1", ControlDevice: "/dev/cdc-wdm2", ModemIMEI: "864388041069422"} + probeFail := func(string) (string, error) { + t.Fatal("probe must not run when IMEI present") + return "", nil + } + if got, err := ensureAddDeviceIMEI(withIMEI, probeFail); err != nil || got.ModemIMEI != "864388041069422" { + t.Fatalf("with-IMEI: got %+v err %v", got, err) + } + + atOnly := config.DeviceConfig{ID: "at-1", ATPort: "/dev/ttyUSB2"} + if _, err := ensureAddDeviceIMEI(atOnly, probeFail); err != nil { + t.Fatalf("AT-only must not be enforced: %v", err) + } +} diff --git a/internal/api/device_mgmt_at_test.go b/internal/api/device_mgmt_at_test.go new file mode 100644 index 00000000..8707de3c --- /dev/null +++ b/internal/api/device_mgmt_at_test.go @@ -0,0 +1,144 @@ +package api + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/backend" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/device" + "github.com/iniwex5/vohive/internal/modem" +) + +type fakeManualATSession struct { + resp string + err error + cmd string + timeout time.Duration + closed bool + closeErr error +} + +func (s *fakeManualATSession) Execute(cmd string, timeout time.Duration) (string, error) { + s.cmd = cmd + s.timeout = timeout + return s.resp, s.err +} + +func (s *fakeManualATSession) Close() error { + s.closed = true + return s.closeErr +} + +func TestExecuteManualATOnPortUsesTransientSerialSession(t *testing.T) { + orig := openManualATSession + defer func() { openManualATSession = orig }() + + fake := &fakeManualATSession{resp: "OK\r\n"} + var gotPort string + openManualATSession = func(port string) (manualATSession, error) { + gotPort = port + return fake, nil + } + + resp, err := executeManualATOnPort("/dev/ttyUSB2", "AT+CSQ", 7*time.Second) + if err != nil { + t.Fatalf("executeManualATOnPort() error = %v", err) + } + if resp != "OK\r\n" { + t.Fatalf("executeManualATOnPort() resp = %q, want OK", resp) + } + if gotPort != "/dev/ttyUSB2" { + t.Fatalf("open port = %q, want /dev/ttyUSB2", gotPort) + } + if fake.cmd != "AT+CSQ" || fake.timeout != 7*time.Second { + t.Fatalf("Execute() got cmd=%q timeout=%s", fake.cmd, fake.timeout) + } + if !fake.closed { + t.Fatal("manual AT session was not closed") + } +} + +func TestExecuteManualATOnPortRejectsEmptyPort(t *testing.T) { + if _, err := executeManualATOnPort(" ", "AT", time.Second); err == nil { + t.Fatal("executeManualATOnPort() error = nil, want empty-port error") + } +} + +func TestExecuteManualATOnPortReturnsOpenError(t *testing.T) { + orig := openManualATSession + defer func() { openManualATSession = orig }() + + openManualATSession = func(port string) (manualATSession, error) { + return nil, errors.New("busy") + } + + if _, err := executeManualATOnPort("/dev/ttyUSB2", "AT", time.Second); err == nil || err.Error() != "打开 AT 端口 /dev/ttyUSB2 失败: busy" { + t.Fatalf("executeManualATOnPort() error = %v", err) + } +} + +func TestHandleDeviceMgmtExecuteATUsesTransientSessionForMBIMBackend(t *testing.T) { + gin.SetMode(gin.TestMode) + orig := openManualATSession + defer func() { openManualATSession = orig }() + + fake := &fakeManualATSession{resp: "OK\r\n"} + var gotPort string + openManualATSession = func(port string) (manualATSession, error) { + gotPort = port + return fake, nil + } + + p := device.NewPool(&config.Config{}) + be := &ussdDeviceBackendStub{mode: backend.BackendMBIM} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-mbim": { + ID: "dev-mbim", + Config: config.DeviceConfig{ID: "dev-mbim", DeviceBackend: backend.BackendMBIM, ATPort: "/dev/ttyUSB9"}, + Backend: be, + }, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-mbim"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-mbim/actions/at", strings.NewReader(`{"cmd":"AT+CSQ","timeout_ms":7000}`)) + ctx.Request.Header.Set("Content-Type", "application/json") + + server.handleDeviceMgmtExecuteAT(ctx) + + if rec.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + if gotPort != "/dev/ttyUSB9" { + t.Fatalf("open port = %q, want /dev/ttyUSB9", gotPort) + } + if fake.cmd != "AT+CSQ" || fake.timeout != 7*time.Second { + t.Fatalf("Execute() got cmd=%q timeout=%s", fake.cmd, fake.timeout) + } + if !fake.closed { + t.Fatal("manual AT session was not closed") + } + if !strings.Contains(rec.Body.String(), `"response":"OK\r\n"`) { + t.Fatalf("body=%s want AT response", rec.Body.String()) + } +} + +func TestManualATPortForWorkerFallsBackToModemPort(t *testing.T) { + m, err := modem.New(config.DeviceConfig{ID: "d", DeviceBackend: "qmi", ManagePort: "/dev/ttyUSB2"}) + if err != nil { + t.Fatalf("modem.New() error = %v", err) + } + // worker.Config 路径全空(零路径),只有 Modem 内存里有端口。 + w := &device.Worker{ID: "d", Config: config.DeviceConfig{ID: "d", DeviceBackend: "qmi"}, Modem: m} + if got := manualATPortForWorker(w); got != "/dev/ttyUSB2" { + t.Fatalf("manualATPortForWorker() = %q, want /dev/ttyUSB2", got) + } +} diff --git a/internal/api/device_mgmt_backend_mode_test.go b/internal/api/device_mgmt_backend_mode_test.go new file mode 100644 index 00000000..99db6a59 --- /dev/null +++ b/internal/api/device_mgmt_backend_mode_test.go @@ -0,0 +1,32 @@ +package api + +import ( + "strings" + "testing" + + "github.com/iniwex5/vohive/internal/config" +) + +func TestValidateDeviceBackendConfigMBIM(t *testing.T) { + // 零路径架构: control_device 由运行时从 IMEI 发现,不再是保存前置条件。 + // mbim 配置无论是否含 control_device 均合法。 + for _, b := range []string{"mbim", "MBIM"} { + if err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: b}); err != nil { + t.Fatalf("backend=%q 应合法,却返回: %v", b, err) + } + if err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: b, ControlDevice: "/dev/cdc-wdm2"}); err != nil { + t.Fatalf("backend=%q+control_device 应合法,却返回: %v", b, err) + } + } + + err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: "foo"}) + if err == nil || !strings.Contains(err.Error(), "mbim") { + t.Fatalf("非法值错误信息应列出 mbim,实际: %v", err) + } + + for _, b := range []string{"", "at", "qmi"} { + if err := validateDeviceBackendConfig(config.DeviceConfig{DeviceBackend: b}); err != nil { + t.Fatalf("backend=%q 应合法,却返回: %v", b, err) + } + } +} diff --git a/internal/api/device_mgmt_cardpolicy_writethrough_test.go b/internal/api/device_mgmt_cardpolicy_writethrough_test.go new file mode 100644 index 00000000..0e0d6e43 --- /dev/null +++ b/internal/api/device_mgmt_cardpolicy_writethrough_test.go @@ -0,0 +1,88 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/db" + "github.com/iniwex5/vohive/internal/device" +) + +func TestCardPolicyFromDeviceConfigMapping(t *testing.T) { + cfg := config.DeviceConfig{ + NetworkEnabled: true, VoWiFiEnabled: true, IPVersion: "v4v6", APN: "ims", + } + pol := cardPolicyFromDeviceConfig("ICC9", cfg) + if pol.ICCID != "ICC9" || !pol.NetworkEnabled || !pol.VoWiFiEnabled { + t.Fatalf("映射错: %+v", pol) + } + if pol.IPVersion != "v4v6" || pol.APN != "ims" || pol.Source != "user" { + t.Fatalf("映射错: %+v", pol) + } +} + +// 策略跟卡走后,保存设备配置必须是策略中性的: +// 不得用 DTO 回传的(GET config 恒零的)策略字段覆盖 card_policies。 +// 策略只能经 PUT /cards/:iccid/policy 修改。 +func TestUpdateDeviceDoesNotClobberCardPolicy(t *testing.T) { + gin.SetMode(gin.TestMode) + initPolicyTestDB(t) + + iccid := "8986008888888888888" + if err := db.DB.Create(&db.Device{IMEI: "imei-x", Alias: "wwan9", CurrentICCID: &iccid}).Error; err != nil { + t.Fatal(err) + } + + // 预置一条用户态卡策略:vowifi 开启、用户飞行意图开启、network 关闭、双栈。 + if err := db.UpsertCardPolicy(db.CardPolicy{ + ICCID: iccid, VoWiFiEnabled: true, AirplaneEnabled: true, IPVersion: "v4v6", APN: "ims", Source: "user", + }); err != nil { + t.Fatal(err) + } + + path := writeDeviceMgmtLimitConfig(t, ` +server: + port: ":7575" +devices: + - id: wwan9 + interface: wwan9 +`) + if err := config.InitGlobalManager(path); err != nil { + t.Fatalf("InitGlobalManager() error = %v", err) + } + server := &Server{pool: device.NewPool(&config.Config{}), configPath: path} + + // 仅改设备名称;DTO 不携带策略(等价于前端配置页不再编辑策略,策略字段恒零)。 + // 旧实现会把 network=false/vowifi=false/ip="" 透写从而清空卡策略。 + body := `{"config":{"id":"wwan9","name":"renamed"}}` + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "wwan9"}} + ctx.Request = httptest.NewRequest(http.MethodPut, "/devices/wwan9", strings.NewReader(body)) + ctx.Request.Header.Set("Content-Type", "application/json") + + server.handleDeviceMgmtUpdateDevice(ctx) + + if rec.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } + + // 卡策略必须原样保留,未被设备保存清空。 + got, err := db.GetCardPolicy(iccid) + if err != nil { + t.Fatalf("卡策略丢失: %v", err) + } + if !got.VoWiFiEnabled || !got.AirplaneEnabled { + t.Fatalf("卡策略被设备保存清空: %+v", got) + } + if got.NetworkEnabled { + t.Fatalf("不变式被破坏(vowifi 开应 network 关): %+v", got) + } + if got.IPVersion != "v4v6" || got.APN != "ims" { + t.Fatalf("卡策略内容被改写: %+v", got) + } +} diff --git a/internal/api/device_mgmt_discovery_test.go b/internal/api/device_mgmt_discovery_test.go new file mode 100644 index 00000000..0ed025c8 --- /dev/null +++ b/internal/api/device_mgmt_discovery_test.go @@ -0,0 +1,247 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/device" +) + +// 不同 IMEI 落在已配置设备的旧路径上,不再是"冲突":新模组就是一台可正常添加的设备, +// 旧配置离线(身份锚定后路径不再有否决权)。 +func TestHandleDeviceMgmtDiscoveredDifferentIMEIIsPlainAddable(t *testing.T) { + gin.SetMode(gin.TestMode) + path := writeDeviceMgmtDiscoveryConfig(t, ` +server: + port: ":7575" +devices: + - id: old-device + modem_imei: "111111111111111" + control_device: /dev/cdc-wdm0 + interface: wwan0 + usb_path: /sys/bus/usb/devices/1-1 + at_port: /dev/ttyUSB2 + device_backend: qmi +`) + if err := config.InitGlobalManager(path); err != nil { + t.Fatalf("InitGlobalManager() error = %v", err) + } + restoreDiscoveryStubs(t) + discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil } + discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) { + return []device.CompatibleModem{{ + ControlPath: "/dev/cdc-wdm0", + NetInterface: "wwan0", + USBPath: "/sys/bus/usb/devices/1-1", + ATPorts: []string{"/dev/ttyUSB2"}, + ATPort: "/dev/ttyUSB2", + Mode: "qmi", + NetworkCapable: true, + }}, nil + } + enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) { + dev.IMEI = "222222222222222" + return dev, "222222222222222" + } + + + got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path}) + if len(got.Devices) != 1 { + t.Fatalf("devices len = %d, want 1", len(got.Devices)) + } + d := got.Devices[0] + if d.Configured { + t.Fatalf("Configured = true, want false: %+v", d) + } + if d.Degraded { + t.Fatalf("Degraded = true, want false (IMEI is readable): %+v", d) + } + if d.IMEI != "222222222222222" { + t.Fatalf("IMEI = %q, want new device IMEI", d.IMEI) + } +} + +// 探不到 IMEI 的硬件(如 MBIM 挂死返回垃圾)归 degraded:不可直接添加,UI 需提示。 +func TestHandleDeviceMgmtDiscoveredMarksDegradedWhenIMEIUnreadable(t *testing.T) { + gin.SetMode(gin.TestMode) + path := writeDeviceMgmtDiscoveryConfig(t, ` +server: + port: ":7575" +devices: [] +`) + if err := config.InitGlobalManager(path); err != nil { + t.Fatalf("InitGlobalManager() error = %v", err) + } + restoreDiscoveryStubs(t) + discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil } + discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) { + return []device.CompatibleModem{{ + ControlPath: "/dev/cdc-wdm1", + NetInterface: "wwan3", + USBPath: "/sys/bus/usb/devices/1-9", + Mode: "mbim", + }}, nil + } + enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) { + return dev, "" // AT/QMI 探不到 IMEI + } + probeIMEIViaMBIMForMgmtFn = func(string) (string, error) { return "", fmt.Errorf("mbim hung") } // MBIM 也读不到 + + + got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path}) + if len(got.Devices) != 1 { + t.Fatalf("devices len = %d, want 1", len(got.Devices)) + } + d := got.Devices[0] + if d.Configured || !d.Degraded { + t.Fatalf("want Configured=false Degraded=true, got %+v", d) + } +} + +func TestHandleDeviceMgmtDiscoveredMarksConfiguredForSameIMEI(t *testing.T) { + gin.SetMode(gin.TestMode) + path := writeDeviceMgmtDiscoveryConfig(t, ` +server: + port: ":7575" +devices: + - id: old-device + modem_imei: "111111111111111" + control_device: /dev/cdc-wdm0 + interface: wwan0 + usb_path: /sys/bus/usb/devices/1-1 + at_port: /dev/ttyUSB2 + device_backend: qmi +`) + if err := config.InitGlobalManager(path); err != nil { + t.Fatalf("InitGlobalManager() error = %v", err) + } + restoreDiscoveryStubs(t) + discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil } + discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) { + return []device.CompatibleModem{{ + ControlPath: "/dev/cdc-wdm0", + NetInterface: "wwan0", + USBPath: "/sys/bus/usb/devices/1-1", + ATPorts: []string{"/dev/ttyUSB2"}, + ATPort: "/dev/ttyUSB2", + Mode: "qmi", + }}, nil + } + enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) { + dev.IMEI = "111111111111111" + return dev, "111111111111111" + } + + + got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path}) + d := got.Devices[0] + if !d.Configured || d.ConfiguredID != "old-device" { + t.Fatalf("configured fields = %+v, want configured old-device", d) + } + if d.Degraded { + t.Fatalf("Degraded = true, want false: %+v", d) + } +} + +// TestHandleDeviceMgmtDiscoveredLegacyPathConfigDegrades verifies that after the +// zero-path migration, a device configured with only path fields (no IMEI) can no +// longer be matched by legacyPathMatch because the migration scrubs those keys from +// disk on Load(). The discovered device appears as Degraded — this is the accepted +// behavioral risk of Option A (unconditional deprecation). +func TestHandleDeviceMgmtDiscoveredLegacyPathConfigDegrades(t *testing.T) { + gin.SetMode(gin.TestMode) + path := writeDeviceMgmtDiscoveryConfig(t, ` +server: + port: ":7575" +devices: + - id: legacy-device + control_device: /dev/cdc-wdm0 + interface: wwan0 + usb_path: /sys/bus/usb/devices/1-1 + at_port: /dev/ttyUSB2 + device_backend: qmi +`) + if err := config.InitGlobalManager(path); err != nil { + t.Fatalf("InitGlobalManager() error = %v", err) + } + restoreDiscoveryStubs(t) + discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil } + discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) { + return []device.CompatibleModem{{ + ControlPath: "/dev/cdc-wdm0", + NetInterface: "wwan0", + USBPath: "/sys/bus/usb/devices/1-1", + ATPorts: []string{"/dev/ttyUSB2"}, + ATPort: "/dev/ttyUSB2", + Mode: "qmi", + }}, nil + } + enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) { + return dev, "" + } + + got := requestDiscoveredDevices(t, &Server{pool: device.NewPool(&config.Config{}), configPath: path}) + d := got.Devices[0] + // 零路径迁移后:磁盘路径键已删,legacyPathMatch 无法命中,设备归入 degraded。 + if d.Configured { + t.Fatalf("device should not be matched after path migration, got: %+v", d) + } + if !d.Degraded { + t.Fatalf("device should be degraded (no IMEI, no matched config), got: %+v", d) + } +} + +type discoveredDevicesResponse struct { + Devices []discoveredDevice `json:"devices"` +} + +func requestDiscoveredDevices(t *testing.T, srv *Server) discoveredDevicesResponse { + t.Helper() + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodGet, "/api/devices/discovered?with_imei=1", nil) + + srv.handleDeviceMgmtDiscovered(ctx) + + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 body=%s", recorder.Code, recorder.Body.String()) + } + var resp discoveredDevicesResponse + if err := json.Unmarshal(recorder.Body.Bytes(), &resp); err != nil { + t.Fatalf("response JSON error = %v body=%s", err, recorder.Body.String()) + } + return resp +} + +func restoreDiscoveryStubs(t *testing.T) { + t.Helper() + origDiscoverQMI := discoverQMIForMgmtFn + origDiscoverCompat := discoverCompatibleModemsFromQMIFn + origEnrich := enrichDiscoveredCompatibleModemFn + + origProbeMBIM := probeIMEIViaMBIMForMgmtFn + t.Cleanup(func() { + discoverQMIForMgmtFn = origDiscoverQMI + discoverCompatibleModemsFromQMIFn = origDiscoverCompat + enrichDiscoveredCompatibleModemFn = origEnrich + + probeIMEIViaMBIMForMgmtFn = origProbeMBIM + }) +} + +func writeDeviceMgmtDiscoveryConfig(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(strings.TrimSpace(content)+"\n"), 0o600); err != nil { + t.Fatalf("WriteFile() error = %v", err) + } + return path +} diff --git a/internal/api/device_mgmt_flightmode_test.go b/internal/api/device_mgmt_flightmode_test.go new file mode 100644 index 00000000..52402e48 --- /dev/null +++ b/internal/api/device_mgmt_flightmode_test.go @@ -0,0 +1,52 @@ +package api + +import ( + "context" + "strings" + "testing" + + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/device" + "github.com/iniwex5/vohive/internal/modem" +) + +func TestFlightModeSuccessMessageUsesRequestedState(t *testing.T) { + tests := []struct { + name string + enabled bool + want string + }{ + {name: "enable", enabled: true, want: "飞行模式已开启"}, + {name: "disable", enabled: false, want: "飞行模式已关闭"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := flightModeSuccessMessage(tt.enabled); got != tt.want { + t.Fatalf("flightModeSuccessMessage(%v)=%q want %q", tt.enabled, got, tt.want) + } + }) + } +} + +func TestSetWorkerFlightModeFailsWhenBackendMissingEvenWithATModem(t *testing.T) { + m, err := modem.New(config.DeviceConfig{ + ID: "dev-qmi", + DeviceBackend: "qmi", + ATPort: "/dev/ttyUSB-test", + }) + if err != nil { + t.Fatalf("modem.New() error = %v", err) + } + + _, _, err = setWorkerFlightMode(context.Background(), &device.Worker{Modem: m}, false) + if err == nil { + t.Fatal("setWorkerFlightMode() error = nil, want backend initialization error") + } + if !strings.Contains(err.Error(), "设备后端未初始化") { + t.Fatalf("setWorkerFlightMode() error = %q, want backend initialization error", err.Error()) + } + if strings.Contains(err.Error(), "AT 管理器") || strings.Contains(err.Error(), "AT 端口") { + t.Fatalf("setWorkerFlightMode() error = %q, must not come from legacy AT fallback", err.Error()) + } +} diff --git a/internal/api/device_mgmt_ipversion_test.go b/internal/api/device_mgmt_ipversion_test.go new file mode 100644 index 00000000..469a8a7b --- /dev/null +++ b/internal/api/device_mgmt_ipversion_test.go @@ -0,0 +1,36 @@ +package api + +import ( + "testing" + + "github.com/iniwex5/vohive/internal/config" +) + +func TestValidateManagedNetworkConfigRejectsBadIPVersion(t *testing.T) { + err := validateManagedNetworkConfig(config.DeviceConfig{ + ID: "dev-ipv", + IPVersion: "v9", + }) + if err == nil { + t.Fatal("validateManagedNetworkConfig() error = nil, want invalid ip_version") + } +} + +func TestDeviceConfigForAddDropsDevicePolicyFields(t *testing.T) { + cfg := deviceConfigForAdd(config.DeviceConfig{ + ID: "dev-1", + APN: "ims", + IPVersion: "bad", + NetworkEnabled: true, + VoWiFiEnabled: true, + AirplaneEnabled: true, + SMSEnabled: false, + }) + + if cfg.APN != "" || cfg.IPVersion != "" || cfg.NetworkEnabled || cfg.VoWiFiEnabled || cfg.AirplaneEnabled { + t.Fatalf("设备添加不应保留卡策略字段: %+v", cfg) + } + if !cfg.SMSEnabled { + t.Fatal("SMS 应保持系统不变量 true") + } +} diff --git a/internal/api/device_mgmt_lifecycle_test.go b/internal/api/device_mgmt_lifecycle_test.go new file mode 100644 index 00000000..44c4d184 --- /dev/null +++ b/internal/api/device_mgmt_lifecycle_test.go @@ -0,0 +1,89 @@ +package api + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/device" + "github.com/iniwex5/vohive/internal/modem" + "github.com/iniwex5/vowifi-go/runtimehost" +) + +func TestApplyLifecycleToOfflineOverviewItemKeepsRecoveryVisible(t *testing.T) { + pool := device.NewPool(&config.Config{}) + pool.MarkLifecycleRecovery("dev1", device.LifecyclePhaseUSBWait, "manual_reboot", 3*time.Minute) + server := &Server{pool: pool} + + item := deviceMgmtOverviewLiteItem{ + ID: "dev1", + Running: false, + Healthy: false, + ControlOnline: false, + } + + server.applyLifecycleToOverviewLiteItem(&item, nil, config.DeviceConfig{ID: "dev1"}) + + if item.LifecyclePhase != string(device.LifecyclePhaseUSBWait) { + t.Fatalf("LifecyclePhase=%q want %q", item.LifecyclePhase, device.LifecyclePhaseUSBWait) + } + if !item.PhysicalPresent { + t.Fatal("PhysicalPresent=false want true during active recovery") + } + if item.WorkerRunning { + t.Fatal("WorkerRunning=true want false") + } +} + +func TestApplyLifecycleToListItemDerivesRadioRegistered(t *testing.T) { + pool := device.NewPool(&config.Config{}) + pool.MarkLifecycleRecovery("dev1", device.LifecyclePhaseQMIStarting, "startup", 3*time.Minute) + server := &Server{pool: pool} + + item := deviceMgmtListItem{ + ID: "dev1", + Running: true, + Healthy: true, + ControlOnline: true, + NetworkConnected: true, + Modem: deviceMgmtListModem{RegStatus: 5}, + } + + server.applyLifecycleToListItem(&item, true, config.DeviceConfig{ID: "dev1"}) + + if !item.RadioRegistered { + t.Fatal("RadioRegistered=false want true for reg status 5") + } + if !item.DataConnected { + t.Fatal("DataConnected=false want true when network is connected") + } + if item.LifecyclePhase != string(device.LifecyclePhaseOnline) { + t.Fatalf("LifecyclePhase=%q want %q", item.LifecyclePhase, device.LifecyclePhaseOnline) + } +} + +func TestVoWiFiRuntimeDTOExportsSIMReadyOnly(t *testing.T) { + dto := runtimeStateToDTO(runtimehost.State{ + Phase: runtimehost.PhaseSIMReady, + DeviceID: "dev1", + SIMReady: true, + LastReason: "sim_ready", + }, modem.DeviceStatus{IMSI: "001010123456789"}) + + if !dto.SIMReady { + t.Fatalf("SIMReady=false in dto=%+v", dto) + } + body, err := json.Marshal(dto) + if err != nil { + t.Fatalf("Marshal() err=%v", err) + } + raw := string(body) + if !strings.Contains(raw, `"sim_ready":true`) { + t.Fatalf("json=%s, want sim_ready=true", raw) + } + if strings.Contains(raw, "radio_ready") { + t.Fatalf("json=%s should not contain radio_ready", raw) + } +} diff --git a/internal/api/device_mgmt_overview_display_test.go b/internal/api/device_mgmt_overview_display_test.go new file mode 100644 index 00000000..d29ea8ed --- /dev/null +++ b/internal/api/device_mgmt_overview_display_test.go @@ -0,0 +1,52 @@ +package api + +import ( + "testing" + + "github.com/iniwex5/vohive/internal/config" +) + +// 重构后策略字段(network/vowifi/airplane/ip/apn/sms)只存在于运行时投影(w.Config), +// 不再来自 config.yaml(persisted)。overviewDisplayConfig 必须从 runtime 取这些字段, +// 否则概览 UI 会对所有设备显示 off。 +func TestOverviewDisplayConfigTakesPolicyFromRuntime(t *testing.T) { + runtime := config.DeviceConfig{ + ID: "wwan0", + Interface: "wwan0", + NetworkEnabled: true, + VoWiFiEnabled: true, + AirplaneEnabled: true, + IPVersion: "v4v6", + APN: "ims", + SMSEnabled: true, + } + persisted := config.DeviceConfig{ + ID: "wwan0", + Interface: "", // 持久化里硬件路径为空,应被 runtime 覆盖 + // 策略字段全为零值(重构后 yaml 不再加载) + } + + got := overviewDisplayConfig(runtime, persisted, true) + + if !got.NetworkEnabled || !got.VoWiFiEnabled || !got.AirplaneEnabled { + t.Fatalf("策略开关应取自 runtime: %+v", got) + } + if got.IPVersion != "v4v6" || got.APN != "ims" { + t.Fatalf("ip/apn 应取自 runtime: %+v", got) + } + if got.Interface != "wwan0" { + t.Fatalf("硬件路径仍应取自 runtime: %+v", got) + } +} + +// 回归:SMS 是系统不变量(恒开),即使 runtime/persisted 都为 false, +// overviewDisplayConfig 也必须返回 sms_enabled=true,否则短信中心设备会被过滤消失。 +func TestOverviewDisplayConfigSMSAlwaysEnabled(t *testing.T) { + runtime := config.DeviceConfig{ID: "wwan0", Interface: "wwan0", SMSEnabled: false} + persisted := config.DeviceConfig{ID: "wwan0", SMSEnabled: false} + + got := overviewDisplayConfig(runtime, persisted, true) + if !got.SMSEnabled { + t.Fatalf("SMS 应恒为 true(不变量),got=%+v", got) + } +} diff --git a/internal/api/device_mgmt_overview_stream_test.go b/internal/api/device_mgmt_overview_stream_test.go new file mode 100644 index 00000000..0298ca44 --- /dev/null +++ b/internal/api/device_mgmt_overview_stream_test.go @@ -0,0 +1,184 @@ +package api + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + proxytraffic "github.com/iniwex5/vohive/internal/proxy/traffic" +) + +func TestOverviewStreamEmitVersionIgnoresRuntimeUpdatedAt(t *testing.T) { + last := newOverviewStreamEmitVersion(deviceMgmtOverviewLiteItem{ + VoWiFiActive: true, + VoWiFiRuntime: &voWiFiRuntimeDTO{ + Phase: "registering", + TunnelReady: true, + IMSReady: false, + SMSReady: false, + LastErrorClass: "", + UpdatedAt: time.Unix(1, 0), + }, + }) + curr := newOverviewStreamEmitVersion(deviceMgmtOverviewLiteItem{ + VoWiFiActive: true, + VoWiFiRuntime: &voWiFiRuntimeDTO{ + Phase: "registering", + TunnelReady: true, + IMSReady: false, + SMSReady: false, + LastErrorClass: "", + UpdatedAt: time.Unix(2, 0), + }, + }) + + if !shouldSkipOverviewStatePush(&last, curr) { + t.Fatal("state push was not skipped when only UpdatedAt changed") + } +} + +func TestOverviewStreamEmitVersionTracksRuntimeBusinessState(t *testing.T) { + baseItem := deviceMgmtOverviewLiteItem{ + VoWiFiActive: true, + VoWiFiRuntime: &voWiFiRuntimeDTO{ + Phase: "registering", + TunnelReady: true, + }, + } + base := newOverviewStreamEmitVersion(baseItem) + + tests := []struct { + name string + item deviceMgmtOverviewLiteItem + }{ + { + name: "phase changed", + item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "ready", TunnelReady: true}}, + }, + { + name: "tunnel changed", + item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: false}}, + }, + { + name: "ims changed", + item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true, IMSReady: true}}, + }, + { + name: "sms changed", + item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true, SMSReady: true}}, + }, + { + name: "last error class changed", + item: deviceMgmtOverviewLiteItem{VoWiFiActive: true, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true, LastErrorClass: "ims_register_failed"}}, + }, + { + name: "active changed", + item: deviceMgmtOverviewLiteItem{VoWiFiActive: false, VoWiFiRuntime: &voWiFiRuntimeDTO{Phase: "registering", TunnelReady: true}}, + }, + { + name: "runtime disappeared", + item: deviceMgmtOverviewLiteItem{VoWiFiActive: true}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + curr := newOverviewStreamEmitVersion(tc.item) + if shouldSkipOverviewStatePush(&base, curr) { + t.Fatal("state push was skipped despite business state change") + } + }) + } + + empty := newOverviewStreamEmitVersion(deviceMgmtOverviewLiteItem{VoWiFiActive: true}) + appeared := newOverviewStreamEmitVersion(baseItem) + if shouldSkipOverviewStatePush(&empty, appeared) { + t.Fatal("state push was skipped when runtime state appeared") + } +} + +func TestOverviewDetailLiveRefreshRequestedDefaultsToCache(t *testing.T) { + gin.SetMode(gin.TestMode) + + tests := []struct { + name string + url string + want bool + }{ + {name: "absent", url: "/devices/dev1/overview", want: false}, + {name: "refresh false", url: "/devices/dev1/overview?refresh=false", want: false}, + {name: "refresh true", url: "/devices/dev1/overview?refresh=true", want: true}, + {name: "refresh one", url: "/devices/dev1/overview?refresh=1", want: true}, + {name: "live true", url: "/devices/dev1/overview?live=true", want: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodGet, tt.url, nil) + + if got := overviewDetailLiveRefreshRequested(ctx); got != tt.want { + t.Fatalf("overviewDetailLiveRefreshRequested()=%v want %v", got, tt.want) + } + }) + } +} + +func TestOverviewTrafficStreamStateFollowsNetworkConnectivity(t *testing.T) { + sub := &fakeRealtimeTrafficSubscriber{} + state := overviewTrafficStreamState{ + subscriber: sub, + deviceID: "dev-a", + ctx: context.Background(), + } + + if ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: false, NetworkConnected: false}); ch != nil { + t.Fatalf("channel=%v want nil when network disabled", ch) + } + if sub.subscribeCalls != 0 { + t.Fatalf("subscribeCalls=%d want 0 before network is active", sub.subscribeCalls) + } + + ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: true}) + if ch == nil { + t.Fatal("expected traffic channel when network is connected") + } + again := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: true}) + if again != ch { + t.Fatal("expected connected sync to reuse existing traffic subscription") + } + if sub.subscribeCalls != 1 { + t.Fatalf("subscribeCalls=%d want 1 after repeated connected sync", sub.subscribeCalls) + } + + if ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: false}); ch != nil { + t.Fatalf("channel=%v want nil after network disconnects", ch) + } + if sub.unsubscribeCalls != 1 { + t.Fatalf("unsubscribeCalls=%d want 1 after network disconnects", sub.unsubscribeCalls) + } + + if ch := state.sync(deviceMgmtOverviewLiteItem{NetworkEnabled: true, NetworkConnected: true}); ch == nil { + t.Fatal("expected traffic channel after network reconnects") + } + if sub.subscribeCalls != 2 { + t.Fatalf("subscribeCalls=%d want 2 after reconnect", sub.subscribeCalls) + } +} + +type fakeRealtimeTrafficSubscriber struct { + subscribeCalls int + unsubscribeCalls int +} + +func (f *fakeRealtimeTrafficSubscriber) Subscribe(ctx context.Context, deviceID string) (<-chan proxytraffic.RealtimeSnapshot, func()) { + f.subscribeCalls++ + ch := make(chan proxytraffic.RealtimeSnapshot) + return ch, func() { + f.unsubscribeCalls++ + } +} diff --git a/internal/api/device_mgmt_overview_test.go b/internal/api/device_mgmt_overview_test.go new file mode 100644 index 00000000..82eca7f4 --- /dev/null +++ b/internal/api/device_mgmt_overview_test.go @@ -0,0 +1,40 @@ +package api + +import ( + "testing" + + "github.com/iniwex5/vohive/internal/config" +) + +// 零路径持久化后,持久化 config 不再含 control_device/interface 等路径; +// 总览展示必须用 worker 运行时 config 的路径与策略投影,意图字段(name/backend)仍取持久化值。 +func TestOverviewDisplayConfigPrefersRuntimePaths(t *testing.T) { + runtime := config.DeviceConfig{ + ID: "wwan0", ModemIMEI: "863212060398051", DeviceBackend: "qmi", + Interface: "wwan0", ControlDevice: "/dev/cdc-wdm0", ATPort: "/dev/ttyUSB2", + QMIDevice: "/dev/cdc-wdm0", USBPath: "/sys/bus/usb/devices/1-4", + VoWiFiEnabled: true, // 策略跟卡走,存在于运行时投影 + } + persisted := config.DeviceConfig{ + ID: "wwan0", Name: "主卡", ModemIMEI: "863212060398051", DeviceBackend: "qmi", + } + + got := overviewDisplayConfig(runtime, persisted, true) + + if got.Name != "主卡" || !got.VoWiFiEnabled || got.DeviceBackend != "qmi" { + t.Fatalf("intent fields lost: %+v", got) + } + if got.ControlDevice != "/dev/cdc-wdm0" || got.Interface != "wwan0" || + got.ATPort != "/dev/ttyUSB2" || got.QMIDevice != "/dev/cdc-wdm0" || + got.USBPath != "/sys/bus/usb/devices/1-4" { + t.Fatalf("runtime paths not applied: %+v", got) + } +} + +func TestOverviewDisplayConfigNoPersistedReturnsRuntime(t *testing.T) { + runtime := config.DeviceConfig{ID: "x", ControlDevice: "/dev/cdc-wdm1", Interface: "wwan1"} + got := overviewDisplayConfig(runtime, config.DeviceConfig{}, false) + if got.ControlDevice != "/dev/cdc-wdm1" || got.Interface != "wwan1" { + t.Fatalf("expected runtime config, got %+v", got) + } +} diff --git a/internal/api/device_mgmt_phone_test.go b/internal/api/device_mgmt_phone_test.go new file mode 100644 index 00000000..74fffc31 --- /dev/null +++ b/internal/api/device_mgmt_phone_test.go @@ -0,0 +1,752 @@ +package api + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "path/filepath" + "reflect" + "strings" + "testing" + "unsafe" + + sgp22 "github.com/damonto/euicc-go/v2" + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/apduarbiter" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/db" + "github.com/iniwex5/vohive/internal/device" + "github.com/iniwex5/vohive/internal/esim" + "github.com/iniwex5/vohive/internal/modem" + "golang.org/x/sync/singleflight" +) + +func initDeviceMgmtPhoneTestDB(t *testing.T) { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "device_mgmt_phone.db") + if err := db.Init(dbPath); err != nil { + t.Fatalf("db.Init() error=%v", err) + } + t.Cleanup(func() { db.DB = nil }) +} + +func setNestedPrivateField(t *testing.T, target any, fieldPath []string, value any) { + t.Helper() + field := reflect.ValueOf(target).Elem() + for _, name := range fieldPath { + field = field.FieldByName(name) + if !field.IsValid() { + t.Fatalf("field path %v not found", fieldPath) + } + } + reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Set(reflect.ValueOf(value)) +} + +func mgrTestSetProfilesLoader(t *testing.T, mgr *esim.Manager, loader func() ([]esim.EUICCProfiles, error)) { + t.Helper() + setNestedPrivateField(t, mgr, []string{"profilesLoader"}, loader) +} + +func mgrTestSetOverviewCache(t *testing.T, mgr *esim.Manager, overview *esim.EsimOverview) { + t.Helper() + setNestedPrivateField(t, mgr, []string{"overviewCache"}, overview) +} + +func newTestEsimManager() *esim.Manager { + mgr := &esim.Manager{} + field := reflect.ValueOf(mgr).Elem().FieldByName("sf") + reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Set(reflect.ValueOf(&singleflight.Group{})) + return mgr +} + +func containsAll(s string, parts ...string) bool { + for _, part := range parts { + if !strings.Contains(s, part) { + return false + } + } + return true +} + +func TestBuildOverviewLiteItemIncludesLocalPhone(t *testing.T) { + initDeviceMgmtPhoneTestDB(t) + + if err := db.UpdateSIMCardModemPhoneNumberByIMSI("imsi-overview-1", "+8613800138000"); err != nil { + t.Fatalf("UpdateSIMCardModemPhoneNumberByIMSI() error=%v", err) + } + if err := db.UpdateSIMCardVoWiFiPhoneNumberByIMSI("imsi-overview-1", "+8613900139000"); err != nil { + t.Fatalf("UpdateSIMCardVoWiFiPhoneNumberByIMSI() error=%v", err) + } + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "dev-1"} + server := &Server{pool: p} + + item := server.buildOverviewLiteItemFromWorker( + w, + config.DeviceConfig{ID: "dev-1", Name: "Device 1", VoWiFiEnabled: true}, + modem.DeviceStatus{IMSI: "imsi-overview-1"}, + nil, + ) + + if item.LocalPhone != "+8613900139000" { + t.Fatalf("LocalPhone=%q want=+8613900139000", item.LocalPhone) + } +} + +func TestBuildOverviewLiteItemUsesCachedIMSIFallbackForLocalPhone(t *testing.T) { + initDeviceMgmtPhoneTestDB(t) + + if err := db.UpdateSIMCardVoWiFiPhoneNumberByIMSI("imsi-cached-1", "+8613911111111"); err != nil { + t.Fatalf("UpdateSIMCardVoWiFiPhoneNumberByIMSI() error=%v", err) + } + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "dev-cached-1"} + setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, "imsi-cached-1") + setNestedPrivateField(t, w, []string{"state", "Identity", "Ready"}, true) + server := &Server{pool: p} + + item := server.buildOverviewLiteItemFromWorker( + w, + config.DeviceConfig{ID: "dev-cached-1", Name: "Device Cached", VoWiFiEnabled: false}, + modem.DeviceStatus{}, + nil, + ) + + if item.LocalPhone != "+8613911111111" { + t.Fatalf("LocalPhone=%q want=+8613911111111 when cached IMSI exists", item.LocalPhone) + } +} + +func TestBuildOverviewLiteItemSuppressesCachedIMSIDuringIdentityTransition(t *testing.T) { + initDeviceMgmtPhoneTestDB(t) + + if err := db.UpdateSIMCardVoWiFiPhoneNumberByIMSI("old-imsi", "+12133316760"); err != nil { + t.Fatalf("UpdateSIMCardVoWiFiPhoneNumberByIMSI() error=%v", err) + } + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "dev-switching-1"} + setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, "old-imsi") + setNestedPrivateField(t, w, []string{"state", "Identity", "Ready"}, false) + setNestedPrivateField(t, w, []string{"state", "Identity", "Phase"}, "transitioning") + server := &Server{pool: p} + + item := server.buildOverviewLiteItemFromWorker( + w, + config.DeviceConfig{ID: "dev-switching-1", Name: "Device Switching", VoWiFiEnabled: false}, + modem.DeviceStatus{}, + nil, + ) + + if item.LocalPhone != "" { + t.Fatalf("LocalPhone=%q want empty while SIM identity is transitioning", item.LocalPhone) + } +} + +func TestBuildOverviewLiteItemIncludesActiveEsimProfileName(t *testing.T) { + mgr := newTestEsimManager() + mgrTestSetOverviewCache(t, mgr, &esim.EsimOverview{ + Profiles: []esim.EUICCProfiles{{ + EID: "eid-a", + AIDHex: "A000", + Profiles: []esim.ProfileItem{ + {ICCID: "iccid-disabled", Name: "Disabled", State: 0, StateText: "未启用"}, + {ICCID: "iccid-enabled", Name: "China Mobile", State: 1, StateText: "已启用"}, + }, + }}, + }) + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "dev-esim", EsimMgr: mgr} + server := &Server{pool: p} + + item := server.buildOverviewLiteItemFromWorker( + w, + config.DeviceConfig{ID: "dev-esim", Name: "Device eSIM"}, + modem.DeviceStatus{}, + nil, + ) + + if item.ActiveESIMProfileName != "China Mobile" { + t.Fatalf("ActiveESIMProfileName=%q want=China Mobile", item.ActiveESIMProfileName) + } +} + +func TestBuildOverviewLiteItemSeparatesControlOnlineFromDataNetwork(t *testing.T) { + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "dev-qmi"} + setNestedPrivateField(t, w, []string{"state", "Runtime", "Ready"}, true) + setNestedPrivateField(t, w, []string{"state", "Meta", "Healthy"}, true) + server := &Server{pool: p} + + item := server.buildOverviewLiteItemFromWorker( + w, + config.DeviceConfig{ID: "dev-qmi", Name: "QMI Device", NetworkEnabled: false}, + modem.DeviceStatus{RegStatus: 2}, + nil, + ) + + if !item.Healthy { + t.Fatal("Healthy=false, want true for backward-compatible control plane health") + } + if !item.ControlOnline { + t.Fatal("ControlOnline=false, want true when control plane is healthy") + } + if item.NetworkEnabled { + t.Fatal("NetworkEnabled=true, want false for data switch off") + } + if item.NetworkConnected { + t.Fatal("NetworkConnected=true, want false when data plane is disconnected") + } + if item.RegistrationStateLabel != "searching" { + t.Fatalf("RegistrationStateLabel=%q want searching", item.RegistrationStateLabel) + } +} + +func TestRegistrationStateLabel(t *testing.T) { + tests := []struct { + name string + reg int + want string + }{ + {name: "home", reg: 1, want: "registered"}, + {name: "roaming", reg: 5, want: "registered"}, + {name: "searching", reg: 2, want: "searching"}, + {name: "denied", reg: 3, want: "denied"}, + {name: "unknown", reg: 0, want: "unknown"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := registrationStateLabel(tt.reg); got != tt.want { + t.Fatalf("registrationStateLabel(%d)=%q want %q", tt.reg, got, tt.want) + } + }) + } +} + +func TestBuildOverviewLiteItemDoesNotTriggerEsimScanWhenActiveProfileCacheMissing(t *testing.T) { + mgr := newTestEsimManager() + setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) { + t.Fatal("buildOverviewLiteItemFromWorker() should not trigger overview loader when cache is empty") + return nil, nil + }) + + p := device.NewPool(&config.Config{}) + w := &device.Worker{ID: "dev-esim", EsimMgr: mgr} + server := &Server{pool: p} + + item := server.buildOverviewLiteItemFromWorker( + w, + config.DeviceConfig{ID: "dev-esim", Name: "Device eSIM"}, + modem.DeviceStatus{}, + nil, + ) + + if item.ActiveESIMProfileName != "" { + t.Fatalf("ActiveESIMProfileName=%q want empty when cache is missing", item.ActiveESIMProfileName) + } +} + +func TestHandleEsimListProfilesRefreshUsesProfilesRefreshPath(t *testing.T) { + gin.SetMode(gin.TestMode) + + mgr := newTestEsimManager() + mgrTestSetProfilesLoader(t, mgr, func() ([]esim.EUICCProfiles, error) { + return []esim.EUICCProfiles{{ + EID: "eid-a", + AIDHex: "A000", + Profiles: []esim.ProfileItem{{ICCID: "iccid-a2", State: 1, StateText: "已启用"}}, + }}, nil + }) + mgrTestSetOverviewCache(t, mgr, &esim.EsimOverview{ + ChipInfo: &esim.EUICCChipInfo{SkuName: "chip"}, + Profiles: []esim.EUICCProfiles{{ + EID: "eid-a", + AIDHex: "A000", + Profiles: []esim.ProfileItem{{ICCID: "iccid-a1", State: 1, StateText: "已启用"}}, + }}, + }) + + p := device.NewPool(&config.Config{}) + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-esim": {ID: "dev-esim", EsimMgr: mgr}, + }) + server := &Server{pool: p} + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}} + ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim/profiles?refresh=true", nil) + + server.handleEsimListProfiles(ctx) + + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String()) + } + if body := recorder.Body.String(); body == "" || !containsAll(body, "iccid-a2", "A000") { + t.Fatalf("body=%q want refreshed profiles payload", body) + } +} + +func TestHandleEsimGetOverviewRefreshUsesFullRefreshPath(t *testing.T) { + gin.SetMode(gin.TestMode) + + mgr := newTestEsimManager() + mgrTestSetOverviewCache(t, mgr, &esim.EsimOverview{ + ChipInfo: &esim.EUICCChipInfo{SkuName: "before"}, + Profiles: []esim.EUICCProfiles{{ + EID: "eid-old", + AIDHex: "OLD", + Profiles: []esim.ProfileItem{{ICCID: "iccid-old", State: 1, StateText: "已启用"}}, + }}, + }) + setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) { + return &esim.EsimOverview{ + ChipInfo: &esim.EUICCChipInfo{SkuName: "after"}, + Profiles: []esim.EUICCProfiles{{ + EID: "eid-new", + AIDHex: "NEW", + Profiles: []esim.ProfileItem{{ICCID: "iccid-new", State: 1, StateText: "已启用"}}, + }}, + }, nil + }) + + p := device.NewPool(&config.Config{}) + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-esim": {ID: "dev-esim", EsimMgr: mgr}, + }) + server := &Server{pool: p} + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}} + ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim?refresh=true", nil) + + server.handleEsimGetOverview(ctx) + + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String()) + } + if body := recorder.Body.String(); body == "" || !containsAll(body, "after", "iccid-new", "NEW") { + t.Fatalf("body=%q want fully refreshed overview payload", body) + } +} + +func TestHandleEsimGetOverviewRefreshPreservesBusyContractOnRefreshFailure(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, tc := range []struct { + name string + err error + }{ + {name: "operation in progress", err: esim.ErrOperationInProgress}, + {name: "apdu busy", err: apduarbiter.ErrAPDUBusy}, + } { + t.Run(tc.name, func(t *testing.T) { + mgr := newTestEsimManager() + setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) { + return nil, tc.err + }) + + p := device.NewPool(&config.Config{}) + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-esim": {ID: "dev-esim", EsimMgr: mgr}, + }) + server := &Server{pool: p} + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}} + ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim?refresh=true", nil) + + server.handleEsimGetOverview(ctx) + + if recorder.Code != http.StatusConflict { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusConflict, recorder.Body.String()) + } + if got := recorder.Header().Get("Retry-After"); got != "2" { + t.Fatalf("Retry-After=%q want=2", got) + } + if body := recorder.Body.String(); body == "" || !containsAll(body, `"busy":true`, `"code":"ESIM_BUSY"`, `"reason":"refresh_overview"`, tc.err.Error()) { + t.Fatalf("body=%q want busy refresh-overview contract", body) + } + }) + } +} + +func TestHandleEsimGetOverviewRefreshPreservesResponseSemanticsWhenGetFailsAfterRefresh(t *testing.T) { + gin.SetMode(gin.TestMode) + + internalErr := errors.New("overview load failed") + for _, tc := range []struct { + name string + getErr error + wantStatus int + wantParts []string + }{ + { + name: "busy after refresh", + getErr: esim.ErrOperationInProgress, + wantStatus: http.StatusConflict, + wantParts: []string{`"busy":true`, `"code":"ESIM_BUSY"`, `"reason":"get_overview"`, esim.ErrOperationInProgress.Error()}, + }, + { + name: "internal after refresh", + getErr: internalErr, + wantStatus: http.StatusInternalServerError, + wantParts: []string{internalErr.Error()}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + mgr := newTestEsimManager() + var calls int + setNestedPrivateField(t, mgr, []string{"overviewLoader"}, func() (*esim.EsimOverview, error) { + calls++ + if calls == 1 { + setNestedPrivateField(t, mgr, []string{"overviewGeneration"}, uint64(2)) + return &esim.EsimOverview{ChipInfo: &esim.EUICCChipInfo{SkuName: "refreshed"}}, nil + } + return nil, tc.getErr + }) + + p := device.NewPool(&config.Config{}) + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-esim": {ID: "dev-esim", EsimMgr: mgr}, + }) + server := &Server{pool: p} + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "id", Value: "dev-esim"}} + ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim?refresh=true", nil) + + server.handleEsimGetOverview(ctx) + + if recorder.Code != tc.wantStatus { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.wantStatus, recorder.Body.String()) + } + if tc.wantStatus == http.StatusConflict { + if got := recorder.Header().Get("Retry-After"); got != "2" { + t.Fatalf("Retry-After=%q want=2", got) + } + } + if body := recorder.Body.String(); body == "" || !containsAll(body, tc.wantParts...) { + t.Fatalf("body=%q want parts=%v", body, tc.wantParts) + } + }) + } +} + +func TestEsimDeleteSuccessBodyIncludesWarningFields(t *testing.T) { + body := esimDeleteSuccessBody(esim.DeleteProfileResult{ + Warning: "Profile 已删除,但删除通知发送未完全确认", + WarningCode: "delete_notification_not_observed", + SpaceDelta: &esim.SpaceDelta{ + Direction: esim.SpaceDeltaDirectionReleased, + Bytes: 4096, + }, + }) + + if body["status"] != "ok" || body["message"] != "Profile 删除成功" { + t.Fatalf("body=%v want ok delete success base fields", body) + } + if body["warning"] != "Profile 已删除,但删除通知发送未完全确认" { + t.Fatalf("warning=%v want propagated warning", body["warning"]) + } + if body["warning_code"] != "delete_notification_not_observed" { + t.Fatalf("warning_code=%v want propagated warning_code", body["warning_code"]) + } + spaceDelta, ok := body["space_delta"].(*esim.SpaceDelta) + if !ok || spaceDelta == nil || spaceDelta.Direction != esim.SpaceDeltaDirectionReleased || spaceDelta.Bytes != 4096 { + t.Fatalf("space_delta=%#v want released/4096", body["space_delta"]) + } +} + +func TestEsimDeleteSuccessBodyOmitsSpaceDeltaWhenUnavailable(t *testing.T) { + body := esimDeleteSuccessBody(esim.DeleteProfileResult{}) + if _, ok := body["space_delta"]; ok { + t.Fatalf("body=%v want space_delta omitted", body) + } +} + +func TestFormatEsimDownloadDoneEventIncludesSpaceDelta(t *testing.T) { + event := formatEsimDownloadDoneEvent(esim.DownloadProfileResult{ + SpaceDelta: &esim.SpaceDelta{ + Direction: esim.SpaceDeltaDirectionConsumed, + Bytes: 8192, + }, + }) + + if !containsAll(event, `"step":"done"`, `"msg":"Profile 下载完成"`, `"pct":100`, `"space_delta":{"direction":"consumed","bytes":8192}`) { + t.Fatalf("event=%q want done payload with space_delta", event) + } +} + +func TestFormatEsimDownloadDoneEventIncludesWarningFields(t *testing.T) { + event := formatEsimDownloadDoneEvent(esim.DownloadProfileResult{ + Warning: "Profile 下载完成,但通知未完全确认", + WarningCode: "download_notification_handle_failed", + }) + + if !containsAll(event, `"step":"done"`, `"msg":"Profile 下载完成"`, `"pct":100`, `"warning":"Profile 下载完成,但通知未完全确认"`, `"warning_code":"download_notification_handle_failed"`) { + t.Fatalf("event=%q want done payload with warning fields", event) + } +} + +func TestWriteEsimDownloadDoneEventWritesSingleWarningDoneFrame(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + writeEsimDownloadDoneEvent(ctx, esim.DownloadProfileResult{ + Warning: "Profile 下载完成,但通知未完全确认", + WarningCode: "download_notification_handle_failed", + }) + + body := recorder.Body.String() + if !containsAll(body, `data: {"step":"done"`, `"warning":"Profile 下载完成,但通知未完全确认"`, `"warning_code":"download_notification_handle_failed"`) { + t.Fatalf("body=%q want SSE done frame with warning fields", body) + } +} + +func TestFormatEsimDownloadErrorEventKeepsLegacyFieldsAndAddsCode(t *testing.T) { + event := formatEsimDownloadErrorEvent(esim.NewDownloadProfileError(sgp22.LoadBoundProfilePackageError{ + BPPCommandID: 5, + ErrorReason: 10, + })) + + if !containsAll(event, + `"step":"error"`, + `"msg":"下载失败: eUICC 安装 profile 时空间不足,请删除未使用的 profile 后重试"`, + `"pct":-1`, + `"code":"euicc_insufficient_memory"`, + `"details":"loadProfileElements,installFailedDueToInsufficientMemoryForProfile"`, + ) { + t.Fatalf("event=%q want legacy error fields plus code/details", event) + } +} + +func TestFormatEsimDownloadErrorEventSupportsPlainError(t *testing.T) { + event := formatEsimDownloadErrorEvent(errors.New("network down")) + + if !containsAll(event, `"step":"error"`, `"msg":"下载失败: network down"`, `"pct":-1`) { + t.Fatalf("event=%q want legacy plain error fields", event) + } + if strings.Contains(event, `"code"`) || strings.Contains(event, `"details"`) { + t.Fatalf("event=%q should not include structured fields for plain errors", event) + } +} + +func TestWriteEsimDeleteSuccessJSONWritesWarningFields(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + writeEsimDeleteSuccessJSON(ctx, esim.DeleteProfileResult{ + Warning: "Profile 已删除,但删除通知发送未完全确认", + WarningCode: "delete_notification_not_observed", + }) + + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String()) + } + if body := recorder.Body.String(); body == "" || !containsAll(body, `"status":"ok"`, `"message":"Profile 删除成功"`, `"warning":"Profile 已删除,但删除通知发送未完全确认"`, `"warning_code":"delete_notification_not_observed"`) { + t.Fatalf("body=%q want success-with-warning delete payload", body) + } +} + +func TestEsimDownloadExecPropagatesWarningResult(t *testing.T) { + var gotIMEI string + result, err := esimDownloadExec(func(ctx context.Context, aidHex, smdp, matchingID, confirmationCode, imei string, progressFn esim.DownloadProgressFn) (esim.DownloadProfileResult, error) { + gotIMEI = imei + return esim.DownloadProfileResult{ + Warning: "Profile 下载完成,但通知未完全确认", + WarningCode: "download_notification_handle_failed", + }, nil + }, context.Background(), "A000", "example.com", "", "", "350225641234561", nil) + if err != nil { + t.Fatalf("esimDownloadExec() error=%v", err) + } + if result.WarningCode != "download_notification_handle_failed" { + t.Fatalf("result=%#v want warning result passthrough", result) + } + if gotIMEI != "350225641234561" { + t.Fatalf("imei=%q want forwarded custom IMEI", gotIMEI) + } +} + +func TestEsimDeleteExecPropagatesWarningResult(t *testing.T) { + result, err := esimDeleteExec(func(string, string) (esim.DeleteProfileResult, error) { + return esim.DeleteProfileResult{ + Warning: "Profile 已删除,但删除通知发送未完全确认", + WarningCode: "delete_notification_not_observed", + }, nil + }, "8986001234567890123", "A000") + if err != nil { + t.Fatalf("esimDeleteExec() error=%v", err) + } + if result.WarningCode != "delete_notification_not_observed" { + t.Fatalf("result=%#v want warning result passthrough", result) + } +} + +func TestEsimNotificationsHTTPStatusMapsStructuredErrors(t *testing.T) { + cases := []struct { + name string + err error + want int + }{ + {name: "busy", err: esim.ErrOperationInProgress, want: http.StatusConflict}, + {name: "invalid sequence", err: esim.NewNotificationError(esim.NotificationErrorInvalidSequence, "bad seq", nil), want: http.StatusBadRequest}, + {name: "invalid aid", err: esim.NewNotificationError(esim.NotificationErrorInvalidAIDHex, "bad aid", nil), want: http.StatusBadRequest}, + {name: "not found", err: esim.NewNotificationError(esim.NotificationErrorNotFound, "missing", nil), want: http.StatusNotFound}, + {name: "internal", err: esim.NewNotificationError(esim.NotificationErrorInternal, "boom", nil), want: http.StatusInternalServerError}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := esimNotificationHTTPStatus(tc.err); got != tc.want { + t.Fatalf("status=%d want=%d", got, tc.want) + } + }) + } +} + +func TestEsimNotificationExecHelpersPropagateResults(t *testing.T) { + items, err := esimNotificationListExec(func(string) ([]esim.NotificationItem, error) { + return []esim.NotificationItem{{SequenceNumber: 11, Event: "install", ICCID: "8986001234567890123", Address: "install.example.com", AIDHex: "A000", CanRetry: true}}, nil + }, "A000") + if err != nil { + t.Fatalf("esimNotificationListExec() error=%v", err) + } + if len(items) != 1 || items[0].SequenceNumber != 11 || items[0].Event != "install" { + t.Fatalf("items=%#v want passthrough notification item", items) + } + if err := esimNotificationRetryExec(func(sequence int64, aidHex string) error { + if sequence != 11 || aidHex != "A000" { + t.Fatalf("sequence=%d aidHex=%q want 11/A000", sequence, aidHex) + } + return nil + }, 11, "A000"); err != nil { + t.Fatalf("esimNotificationRetryExec() error=%v", err) + } +} + +func TestHandleEsimNotificationListUsesJSONContract(t *testing.T) { + gin.SetMode(gin.TestMode) + oldExec := esimNotificationListExec + defer func() { esimNotificationListExec = oldExec }() + + mgr := newTestEsimManager() + p := device.NewPool(&config.Config{}) + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-esim": {ID: "dev-esim", EsimMgr: mgr}, + }) + server := &Server{pool: p} + + esimNotificationListExec = func(_ func(string) ([]esim.NotificationItem, error), aidHex string) ([]esim.NotificationItem, error) { + if aidHex != "A000" { + t.Fatalf("aidHex=%q want A000", aidHex) + } + return []esim.NotificationItem{{SequenceNumber: 11, Event: "install", ICCID: "8986001234567890123", Address: "install.example.com", AIDHex: "A000", CanRetry: true}}, nil + } + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-esim"}} + ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim/notifications?aid_hex=A000", nil) + + server.handleEsimListNotifications(ctx) + + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String()) + } + if body := recorder.Body.String(); body == "" || !containsAll(body, `"items"`, `"sequence_number":11`, `"event":"install"`, `"aid_hex":"A000"`, `"can_retry":true`) { + t.Fatalf("body=%q want notification list payload", body) + } +} + +func TestHandleEsimNotificationListPassesEmptyAidForCurrentCardDefault(t *testing.T) { + gin.SetMode(gin.TestMode) + oldExec := esimNotificationListExec + defer func() { esimNotificationListExec = oldExec }() + + mgr := newTestEsimManager() + p := device.NewPool(&config.Config{}) + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-esim": {ID: "dev-esim", EsimMgr: mgr}, + }) + server := &Server{pool: p} + + esimNotificationListExec = func(_ func(string) ([]esim.NotificationItem, error), aidHex string) ([]esim.NotificationItem, error) { + if aidHex != "" { + t.Fatalf("aidHex=%q want empty current-card default", aidHex) + } + return []esim.NotificationItem{{SequenceNumber: 11, Event: "install", AIDHex: "A000", CanRetry: true}}, nil + } + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-esim"}} + ctx.Request = httptest.NewRequest(http.MethodGet, "/devices/dev-esim/esim/notifications", nil) + + server.handleEsimListNotifications(ctx) + + if recorder.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String()) + } +} + +func TestHandleEsimRetryNotificationMapsStatusCodes(t *testing.T) { + gin.SetMode(gin.TestMode) + oldExec := esimNotificationRetryExec + defer func() { esimNotificationRetryExec = oldExec }() + + cases := []struct { + name string + err error + wantStatus int + wantParts []string + }{ + {name: "success", err: nil, wantStatus: http.StatusOK, wantParts: []string{`"status":"ok"`, `"message":"通知重试发送成功"`}}, + {name: "busy", err: esim.ErrOperationInProgress, wantStatus: http.StatusConflict, wantParts: []string{`"busy":true`, `"code":"ESIM_BUSY"`, `"reason":"retry_notification"`}}, + {name: "invalid", err: esim.NewNotificationError(esim.NotificationErrorInvalidSequence, "bad seq", nil), wantStatus: http.StatusBadRequest, wantParts: []string{`bad seq`}}, + {name: "not found", err: esim.NewNotificationError(esim.NotificationErrorNotFound, "missing", nil), wantStatus: http.StatusNotFound, wantParts: []string{`missing`}}, + {name: "internal", err: esim.NewNotificationError(esim.NotificationErrorInternal, "boom", nil), wantStatus: http.StatusInternalServerError, wantParts: []string{`boom`}}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mgr := newTestEsimManager() + p := device.NewPool(&config.Config{}) + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-esim": {ID: "dev-esim", EsimMgr: mgr}, + }) + server := &Server{pool: p} + esimNotificationRetryExec = func(_ func(int64, string) error, sequence int64, aidHex string) error { + if sequence != 11 || aidHex != "A000" { + t.Fatalf("sequence=%d aidHex=%q want 11/A000", sequence, aidHex) + } + return tc.err + } + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-esim"}, {Key: "sequence", Value: "11"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-esim/esim/notifications/11/actions/retry?aid_hex=A000", nil) + + server.handleEsimRetryNotification(ctx) + + if recorder.Code != tc.wantStatus { + t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.wantStatus, recorder.Body.String()) + } + if tc.wantStatus == http.StatusConflict { + if got := recorder.Header().Get("Retry-After"); got != "2" { + t.Fatalf("Retry-After=%q want=2", got) + } + } + if body := recorder.Body.String(); body == "" || !containsAll(body, tc.wantParts...) { + t.Fatalf("body=%q want parts=%v", body, tc.wantParts) + } + }) + } +} diff --git a/internal/api/device_mgmt_qmi_proxy_test.go b/internal/api/device_mgmt_qmi_proxy_test.go new file mode 100644 index 00000000..82acbe50 --- /dev/null +++ b/internal/api/device_mgmt_qmi_proxy_test.go @@ -0,0 +1,114 @@ +package api + +import ( + "testing" + + "github.com/iniwex5/vohive/internal/config" +) + +func TestDeviceConfigDTOPreservesQMIProxyFields(t *testing.T) { + cfg := config.DeviceConfig{ + ID: "dev-qmi", + QMIUseProxy: true, + QMIProxyPath: "custom-qmi-proxy", + QMIProxyExecutable: "/opt/vohive/bin/qmi-proxy", + } + + dto := deviceConfigToDTO(cfg) + if dto.QMIUseProxy == nil || !*dto.QMIUseProxy { + t.Fatal("dto.QMIUseProxy=nil/false, want true") + } + if dto.QMIProxyPath == nil || *dto.QMIProxyPath != cfg.QMIProxyPath { + t.Fatalf("dto.QMIProxyPath=%v, want %q", dto.QMIProxyPath, cfg.QMIProxyPath) + } + if dto.QMIProxyExecutable == nil || *dto.QMIProxyExecutable != cfg.QMIProxyExecutable { + t.Fatalf("dto.QMIProxyExecutable=%v, want %q", dto.QMIProxyExecutable, cfg.QMIProxyExecutable) + } + + roundTrip := deviceConfigFromDTO(dto) + if !roundTrip.QMIUseProxy { + t.Fatal("roundTrip.QMIUseProxy=false, want true") + } + if roundTrip.QMIProxyPath != cfg.QMIProxyPath { + t.Fatalf("roundTrip.QMIProxyPath=%q, want %q", roundTrip.QMIProxyPath, cfg.QMIProxyPath) + } + if roundTrip.QMIProxyExecutable != cfg.QMIProxyExecutable { + t.Fatalf("roundTrip.QMIProxyExecutable=%q, want %q", roundTrip.QMIProxyExecutable, cfg.QMIProxyExecutable) + } +} + +func TestDeviceConfigDTOPreservesIPVersion(t *testing.T) { + cfg := config.DeviceConfig{ + ID: "dev-ipv", + IPVersion: "v4v6", + } + + dto := deviceConfigToDTO(cfg) + if dto.IPVersion != "v4v6" { + t.Fatalf("dto.IPVersion=%q, want v4v6", dto.IPVersion) + } + + roundTrip := deviceConfigFromDTO(dto) + if roundTrip.IPVersion != "v4v6" { + t.Fatalf("roundTrip.IPVersion=%q, want v4v6", roundTrip.IPVersion) + } +} + +func TestDeviceConfigFromDTOWithBasePreservesOmittedQMIProxyFields(t *testing.T) { + base := config.DeviceConfig{ + ID: "dev-qmi", + Name: "old name", + ControlDevice: "/dev/cdc-wdm0", + QMIUseProxy: true, + QMIProxyPath: "qmi-proxy", + QMIProxyExecutable: "/usr/libexec/qmi-proxy", + } + + cfg := deviceConfigFromDTOWithBase(deviceConfigDTO{ + ID: "dev-qmi", + Name: "new name", + ControlDevice: "/dev/cdc-wdm0", + }, &base) + + if cfg.Name != "new name" { + t.Fatalf("Name=%q, want %q", cfg.Name, "new name") + } + if !cfg.QMIUseProxy { + t.Fatal("QMIUseProxy=false, want preserved true") + } + if cfg.QMIProxyPath != base.QMIProxyPath { + t.Fatalf("QMIProxyPath=%q, want %q", cfg.QMIProxyPath, base.QMIProxyPath) + } + if cfg.QMIProxyExecutable != base.QMIProxyExecutable { + t.Fatalf("QMIProxyExecutable=%q, want %q", cfg.QMIProxyExecutable, base.QMIProxyExecutable) + } +} + +func TestDeviceConfigFromDTOWithBaseAppliesExplicitQMIProxyFields(t *testing.T) { + base := config.DeviceConfig{ + ID: "dev-qmi", + QMIUseProxy: true, + QMIProxyPath: "qmi-proxy", + QMIProxyExecutable: "/usr/libexec/qmi-proxy", + } + useProxy := false + proxyPath := "" + proxyExecutable := "" + + cfg := deviceConfigFromDTOWithBase(deviceConfigDTO{ + ID: "dev-qmi", + QMIUseProxy: &useProxy, + QMIProxyPath: &proxyPath, + QMIProxyExecutable: &proxyExecutable, + }, &base) + + if cfg.QMIUseProxy { + t.Fatal("QMIUseProxy=true, want explicit false") + } + if cfg.QMIProxyPath != "" { + t.Fatalf("QMIProxyPath=%q, want empty", cfg.QMIProxyPath) + } + if cfg.QMIProxyExecutable != "" { + t.Fatalf("QMIProxyExecutable=%q, want empty", cfg.QMIProxyExecutable) + } +} diff --git a/internal/api/device_mgmt_restart.go b/internal/api/device_mgmt_restart.go new file mode 100644 index 00000000..63ad7be2 --- /dev/null +++ b/internal/api/device_mgmt_restart.go @@ -0,0 +1,73 @@ +package api + +import "github.com/iniwex5/vohive/internal/config" + +func deviceConfigRequiresRestart(old config.DeviceConfig, next config.DeviceConfig) bool { + if config.NormalizeIMEI(old.ModemIMEI) != config.NormalizeIMEI(next.ModemIMEI) { + return true + } + if old.USBPath != next.USBPath { + return true + } + if old.Interface != next.Interface { + return true + } + if old.ProxyPort != next.ProxyPort { + return true + } + if old.ATPort != next.ATPort { + return true + } + if old.ControlDevice != next.ControlDevice { + return true + } + if config.NormalizeESIMTransport(old.ESIMTransport) != config.NormalizeESIMTransport(next.ESIMTransport) { + return true + } + if old.BaudRate != next.BaudRate { + return true + } + if old.DataBits != next.DataBits { + return true + } + if old.StopBits != next.StopBits { + return true + } + if old.Parity != next.Parity { + return true + } + if old.APN != next.APN { + return true + } + if old.IPVersion != next.IPVersion { + return true + } + // 后端模式变更(at↔qmi↔auto)需要重建 Worker + if old.DeviceBackend != next.DeviceBackend { + return true + } + if qmiProxyConfigChanged(old, next) { + return true + } + return false +} + +func qmiProxyConfigChanged(old config.DeviceConfig, next config.DeviceConfig) bool { + if old.QMIUseProxy != next.QMIUseProxy { + return true + } + if old.QMIProxyPath != next.QMIProxyPath { + return true + } + if old.QMIProxyExecutable != next.QMIProxyExecutable { + return true + } + return false +} + +func managedNetworkConfigChanged(old, next config.DeviceConfig) bool { + return old.APN != next.APN || + old.Interface != next.Interface || + old.ControlDevice != next.ControlDevice || + old.IPVersion != next.IPVersion +} diff --git a/internal/api/device_mgmt_restart_test.go b/internal/api/device_mgmt_restart_test.go new file mode 100644 index 00000000..794039b9 --- /dev/null +++ b/internal/api/device_mgmt_restart_test.go @@ -0,0 +1,128 @@ +package api + +import ( + "testing" + + "github.com/iniwex5/vohive/internal/config" +) + +func TestDeviceConfigRequiresRestartWhenQMIProxyConfigChanges(t *testing.T) { + base := config.DeviceConfig{ + ID: "dev-qmi", + ControlDevice: "/dev/cdc-wdm0", + DeviceBackend: "qmi", + QMIUseProxy: true, + QMIProxyPath: "qmi-proxy", + QMIProxyExecutable: "/usr/libexec/qmi-proxy", + } + + tests := []struct { + name string + edit func(*config.DeviceConfig) + }{ + { + name: "use proxy toggled", + edit: func(next *config.DeviceConfig) { + next.QMIUseProxy = false + }, + }, + { + name: "proxy path changed", + edit: func(next *config.DeviceConfig) { + next.QMIProxyPath = "custom-qmi-proxy" + }, + }, + { + name: "proxy executable changed", + edit: func(next *config.DeviceConfig) { + next.QMIProxyExecutable = "/opt/qmi-proxy" + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + next := base + tt.edit(&next) + if !deviceConfigRequiresRestart(base, next) { + t.Fatal("deviceConfigRequiresRestart()=false, want true") + } + }) + } +} + +func TestDeviceConfigRequiresRestartIgnoresIMEIFormatOnly(t *testing.T) { + old := config.DeviceConfig{ModemIMEI: "864388041069422"} + next := config.DeviceConfig{ModemIMEI: " 864388041069422"} + + if deviceConfigRequiresRestart(old, next) { + t.Fatal("format-only IMEI difference must not require restart") + } + + if deviceConfigRequiresRestart(config.DeviceConfig{}, config.DeviceConfig{}) { + t.Fatal("two empty IMEIs must not require restart") + } + + diff := config.DeviceConfig{ModemIMEI: "864513045234397"} + if !deviceConfigRequiresRestart(old, diff) { + t.Fatal("different modem IMEI must require restart") + } + + imeisv := config.DeviceConfig{ModemIMEI: "8643880410694201"} + if deviceConfigRequiresRestart(old, imeisv) { + t.Fatal("IMEISV-only IMEI difference must not require restart") + } +} + +func TestDeviceConfigMBIMManagedNetworkChangesRequiresRebuild(t *testing.T) { + base := config.DeviceConfig{ + APN: "internet", + Interface: "wwan0", + ControlDevice: "/dev/cdc-wdm0", + IPVersion: "ipv4", + } + + tests := []struct { + name string + edit func(*config.DeviceConfig) + }{ + { + name: "APN changed", + edit: func(next *config.DeviceConfig) { + next.APN = "fast.t-mobile.com" + }, + }, + { + name: "Interface changed", + edit: func(next *config.DeviceConfig) { + next.Interface = "wwan1" + }, + }, + { + name: "ControlDevice changed", + edit: func(next *config.DeviceConfig) { + next.ControlDevice = "/dev/cdc-wdm1" + }, + }, + { + name: "IPVersion changed", + edit: func(next *config.DeviceConfig) { + next.IPVersion = "ipv4v6" + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + next := base + tt.edit(&next) + if !managedNetworkConfigChanged(base, next) { + t.Fatalf("managedNetworkConfigChanged()=false, want true for %s", tt.name) + } + }) + } + + if managedNetworkConfigChanged(base, base) { + t.Fatal("managedNetworkConfigChanged()=true for identical configs, want false") + } +} diff --git a/internal/api/device_mgmt_test_helpers_test.go b/internal/api/device_mgmt_test_helpers_test.go new file mode 100644 index 00000000..7611dcd6 --- /dev/null +++ b/internal/api/device_mgmt_test_helpers_test.go @@ -0,0 +1,17 @@ +package api + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func writeDeviceMgmtLimitConfig(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(strings.TrimSpace(content)+"\n"), 0o600); err != nil { + t.Fatalf("WriteFile() error = %v", err) + } + return path +} diff --git a/internal/api/device_mgmt_ussd_test.go b/internal/api/device_mgmt_ussd_test.go new file mode 100644 index 00000000..b1482b05 --- /dev/null +++ b/internal/api/device_mgmt_ussd_test.go @@ -0,0 +1,426 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/backend" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/device" +) + +type ussdDeviceBackendStub struct { + mode string + imei string + rebootErr error + rebooted bool +} + +var _ backend.DeviceBackend = (*ussdDeviceBackendStub)(nil) + +func (s *ussdDeviceBackendStub) GetIMEI(ctx context.Context) (string, error) { return s.imei, nil } +func (s *ussdDeviceBackendStub) GetIMSI(ctx context.Context) (string, error) { return "", nil } +func (s *ussdDeviceBackendStub) GetICCID(ctx context.Context) (string, error) { return "", nil } +func (s *ussdDeviceBackendStub) GetMSISDN(ctx context.Context) (string, error) { return "", nil } +func (s *ussdDeviceBackendStub) GetRevision(ctx context.Context) (string, error) { return "", nil } +func (s *ussdDeviceBackendStub) GetSignalInfo(ctx context.Context) (*backend.SignalInfo, error) { + return nil, nil +} +func (s *ussdDeviceBackendStub) GetServingSystem(ctx context.Context) (*backend.ServingSystem, error) { + return nil, nil +} +func (s *ussdDeviceBackendStub) IsSimInserted(ctx context.Context) (bool, error) { return true, nil } +func (s *ussdDeviceBackendStub) GetNativeMCCMNC(ctx context.Context) (string, string, error) { + return "", "", nil +} +func (s *ussdDeviceBackendStub) GetNativeSPN(ctx context.Context) (string, error) { return "", nil } +func (s *ussdDeviceBackendStub) GetSIMMetadata(ctx context.Context) (*backend.SIMMetadata, error) { + return nil, nil +} +func (s *ussdDeviceBackendStub) SendSMS(ctx context.Context, to, body string) error { return nil } +func (s *ussdDeviceBackendStub) ReadSMS(ctx context.Context, index int) (*backend.SMS, error) { + return nil, nil +} +func (s *ussdDeviceBackendStub) DeleteSMS(ctx context.Context, index int) error { return nil } +func (s *ussdDeviceBackendStub) ListSMS(ctx context.Context) ([]backend.SMSSummary, error) { + return nil, nil +} +func (s *ussdDeviceBackendStub) DeleteAllSMS(ctx context.Context) error { return nil } +func (s *ussdDeviceBackendStub) SetOperatingMode(ctx context.Context, mode backend.OperatingMode) error { + return nil +} +func (s *ussdDeviceBackendStub) GetOperatingMode(ctx context.Context) (backend.OperatingMode, error) { + return backend.ModeOnline, nil +} +func (s *ussdDeviceBackendStub) Reboot(ctx context.Context) error { + s.rebooted = true + return s.rebootErr +} +func (s *ussdDeviceBackendStub) OpenLogicalChannel(ctx context.Context, aid string) (int, error) { + return 0, nil +} +func (s *ussdDeviceBackendStub) CloseLogicalChannel(ctx context.Context, channelID int) error { + return nil +} +func (s *ussdDeviceBackendStub) TransmitAPDU(ctx context.Context, channelID int, command string) (string, error) { + return "", nil +} +func (s *ussdDeviceBackendStub) TransmitBasicAPDU(ctx context.Context, command string) (string, error) { + return "", nil +} +func (s *ussdDeviceBackendStub) Mode() string { + if s.mode == "" { + return backend.BackendAT + } + return s.mode +} +func (s *ussdDeviceBackendStub) Close() error { return nil } + +type ussdProviderBackendStub struct { + ussdDeviceBackendStub + command string + timeout time.Duration + continueInput string + continueTimeout time.Duration + cancelCalled bool +} + +var _ backend.USSDProvider = (*ussdProviderBackendStub)(nil) + +func (s *ussdProviderBackendStub) ExecuteUSSD(ctx context.Context, command string, timeout time.Duration) (*backend.USSDResult, error) { + s.command = command + s.timeout = timeout + return &backend.USSDResult{Status: 0, Text: "ok", RawText: "ok", DCS: 15}, nil +} + +func (s *ussdProviderBackendStub) ContinueUSSD(ctx context.Context, input string, timeout time.Duration) (*backend.USSDResult, error) { + s.continueInput = input + s.continueTimeout = timeout + return &backend.USSDResult{Status: 0, Text: "continued", RawText: "continued", DCS: 15}, nil +} + +func (s *ussdProviderBackendStub) CancelUSSD(ctx context.Context) error { + s.cancelCalled = true + return nil +} + +func TestHandleDeviceMgmtExecuteUSSDUsesBackendProvider(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendQMI}} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-qmi": {ID: "dev-qmi", Backend: be}, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/ussd", strings.NewReader(`{"command":" *100# ","timeout_ms":7000}`)) + ctx.Request.Header.Set("Content-Type", "application/json") + + server.handleDeviceMgmtExecuteUSSD(ctx) + + if rec.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + if be.command != "*100#" || be.timeout != 7*time.Second { + t.Fatalf("provider got command=%q timeout=%s", be.command, be.timeout) + } + var body struct { + Status string `json:"status"` + Result backend.USSDResult `json:"result"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("response JSON error=%v body=%s", err, rec.Body.String()) + } + if body.Status != "ok" || body.Result.Text != "ok" { + t.Fatalf("response=%+v want ok result", body) + } +} + +func TestHandleDeviceMgmtExecuteUSSDDefaultsToStandardNetworkTimeout(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendQMI}} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-qmi": {ID: "dev-qmi", Backend: be}, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/ussd", strings.NewReader(`{"command":"*100#"}`)) + ctx.Request.Header.Set("Content-Type", "application/json") + + server.handleDeviceMgmtExecuteUSSD(ctx) + + if rec.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + if be.timeout != 45*time.Second { + t.Fatalf("provider timeout=%s want 45s default", be.timeout) + } +} + +func TestHandleDeviceMgmtExecuteUSSDRejectsUnsupportedBackend(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdDeviceBackendStub{mode: backend.BackendQMI} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-qmi": {ID: "dev-qmi", Backend: be}, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/ussd", strings.NewReader(`{"command":"*100#"}`)) + ctx.Request.Header.Set("Content-Type", "application/json") + + server.handleDeviceMgmtExecuteUSSD(ctx) + + if rec.Code != http.StatusBadRequest { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusBadRequest, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "当前设备后端不支持 USSD") { + t.Fatalf("body=%s want capability error", rec.Body.String()) + } +} + +func TestHandleDeviceMgmtContinueUSSDUsesBackendProviderWhenVoWiFiInactive(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendMBIM}} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-mbim": {ID: "dev-mbim", Backend: be}, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-mbim"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-mbim/actions/ussd/continue", strings.NewReader(`{"session_id":"cs","input":" 1 ","timeout_ms":8000}`)) + ctx.Request.Header.Set("Content-Type", "application/json") + + server.handleDeviceMgmtContinueUSSD(ctx) + + if rec.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + if be.continueInput != "1" || be.continueTimeout != 8*time.Second { + t.Fatalf("provider got input=%q timeout=%s", be.continueInput, be.continueTimeout) + } + if !strings.Contains(rec.Body.String(), `"channel":"cs"`) { + t.Fatalf("body=%s want CS channel", rec.Body.String()) + } +} + +func TestHandleDeviceMgmtCancelUSSDUsesBackendProviderWhenVoWiFiInactive(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdProviderBackendStub{ussdDeviceBackendStub: ussdDeviceBackendStub{mode: backend.BackendMBIM}} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-mbim": {ID: "dev-mbim", Backend: be}, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-mbim"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-mbim/actions/ussd/cancel", strings.NewReader(`{"session_id":"cs"}`)) + ctx.Request.Header.Set("Content-Type", "application/json") + + server.handleDeviceMgmtCancelUSSD(ctx) + + if rec.Code != http.StatusOK { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + if !be.cancelCalled { + t.Fatal("provider CancelUSSD was not called") + } +} + +// TestShouldUseATFirstRebootSkipsForQMIBackend 测试 QMI 模式设备重启不应优先走 AT+CFUN, +// 应直接使用 QMI ModeReset(backend.Reboot),仅 AT 模式设备才保留 AT 优先路径。 +func TestShouldUseATFirstRebootSkipsForQMIBackend(t *testing.T) { + if shouldUseATFirstReboot(backend.BackendQMI) { + t.Fatal("shouldUseATFirstReboot(qmi) = true, want false — QMI 模式应直接走 QMI ModeReset") + } + if !shouldUseATFirstReboot(backend.BackendAT) { + t.Fatal("shouldUseATFirstReboot(at) = false, want true — AT 模式应保留 AT 优先路径") + } +} + +func TestHandleDeviceMgmtRebootDoesNotScheduleRecoveryOnQMITransportFailure(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdDeviceBackendStub{ + mode: backend.BackendQMI, + rebootErr: errors.New("write failed: write unix @->@qmi-proxy: write: broken pipe"), + } + worker := &device.Worker{ID: "dev-qmi", Backend: be} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-qmi": worker, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/reboot", nil) + + server.handleDeviceMgmtReboot(ctx) + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String()) + } + if strings.Contains(rec.Body.String(), "已转入控制面恢复") { + t.Fatalf("body=%s should not report recovery", rec.Body.String()) + } + snapshot := worker.HealthSnapshot() + if snapshot.State == device.HealthStateReprobing { + t.Fatalf("health state=%s should not enter recovery", snapshot.State) + } +} + +func TestHandleDeviceMgmtRebootDoesNotScheduleRecoveryWhenQMIControlNotReady(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdDeviceBackendStub{ + mode: backend.BackendQMI, + rebootErr: errors.New("QMI 服务未就绪: DMS"), + } + worker := &device.Worker{ID: "dev-qmi", Backend: be} + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-qmi": worker, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/reboot", nil) + + server.handleDeviceMgmtReboot(ctx) + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String()) + } + if strings.Contains(rec.Body.String(), "已转入控制面恢复") { + t.Fatalf("body=%s should not report recovery", rec.Body.String()) + } + snapshot := worker.HealthSnapshot() + if snapshot.State == device.HealthStateReprobing { + t.Fatalf("health state=%s should not enter recovery", snapshot.State) + } + lifecycle := p.LifecycleSnapshot("dev-qmi") + if lifecycle.Phase == device.LifecyclePhaseRebooting { + t.Fatalf("lifecycle phase=%s should not remain rebooting after failed reboot command", lifecycle.Phase) + } +} + +func TestHandleDeviceMgmtRebootDoesNotEnterRebootingWhenCommandFails(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdDeviceBackendStub{ + mode: backend.BackendAT, + rebootErr: errors.New("AT channel unavailable"), + } + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-at": {ID: "dev-at", Backend: be}, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-at"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-at/actions/reboot", nil) + + server.handleDeviceMgmtReboot(ctx) + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String()) + } + lifecycle := p.LifecycleSnapshot("dev-at") + if lifecycle.Phase == device.LifecyclePhaseRebooting { + t.Fatalf("lifecycle phase=%s should not be set before reboot command succeeds", lifecycle.Phase) + } +} + +func TestHandleDeviceMgmtRebootRejectsMismatchedQMIIdentity(t *testing.T) { + gin.SetMode(gin.TestMode) + p := device.NewPool(&config.Config{}) + be := &ussdDeviceBackendStub{ + mode: backend.BackendQMI, + imei: "222222222222222", + } + worker := &device.Worker{ + ID: "dev-qmi", + Config: config.DeviceConfig{ + ID: "dev-qmi", + ModemIMEI: "111111111111111", + DeviceBackend: backend.BackendQMI, + }, + Backend: be, + } + setNestedPrivateField(t, p, []string{"workers"}, map[string]*device.Worker{ + "dev-qmi": worker, + }) + server := &Server{pool: p} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-qmi"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-qmi/actions/reboot", nil) + + server.handleDeviceMgmtReboot(ctx) + + if rec.Code != http.StatusConflict { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusConflict, rec.Body.String()) + } + if be.rebooted { + t.Fatal("backend Reboot was called despite IMEI mismatch") + } + if !strings.Contains(rec.Body.String(), "设备路径已漂移") { + t.Fatalf("body=%s want identity drift message", rec.Body.String()) + } +} + +func TestHandleDeviceMgmtReconnectVoWiFiReturnsRestartError(t *testing.T) { + gin.SetMode(gin.TestMode) + path := writeDeviceMgmtLimitConfig(t, ` +server: + port: ":7575" +devices: + - id: dev-missing-worker + interface: wwan0 + vowifi_enabled: true +`) + if err := config.InitGlobalManager(path); err != nil { + t.Fatalf("InitGlobalManager() error = %v", err) + } + server := &Server{pool: device.NewPool(&config.Config{}), configPath: path} + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Params = gin.Params{{Key: "device_id", Value: "dev-missing-worker"}} + ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-missing-worker/vowifi/actions/reconnect", nil) + + server.handleDeviceMgmtReconnectVoWiFi(ctx) + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status=%d want=%d body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "VoWiFi 重连失败") { + t.Fatalf("body=%s want reconnect failure", rec.Body.String()) + } +} diff --git a/internal/api/device_operator_selection.go b/internal/api/device_operator_selection.go new file mode 100644 index 00000000..b6a39d14 --- /dev/null +++ b/internal/api/device_operator_selection.go @@ -0,0 +1,200 @@ +package api + +import ( + "errors" + "net/http" + "time" + + "github.com/gin-gonic/gin" + "github.com/iniwex5/vohive/internal/backend" + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/device" + "github.com/iniwex5/vohive/pkg/logger" +) + +type operatorScanResponse struct { + ScanID string `json:"scan_id"` + Status string `json:"status"` + StartedAt time.Time `json:"started_at"` + UpdatedAt time.Time `json:"updated_at"` + Complete bool `json:"complete"` + Retryable bool `json:"retryable"` + Message string `json:"message"` + Error string `json:"error,omitempty"` + Candidates []backend.OperatorCandidate `json:"candidates"` +} + +func operatorSelectionErrorStatus(err error) int { + switch { + case errors.Is(err, device.ErrVoWiFiActive), errors.Is(err, device.ErrESIMSwitching): + return http.StatusConflict + case errors.Is(err, device.ErrOperatorSelectionNotSupported): + return http.StatusBadRequest + case errors.Is(err, device.ErrBackendNotAvailable): + return http.StatusServiceUnavailable + default: + return http.StatusInternalServerError + } +} + +func (s *Server) handleDeviceMgmtOperatorScan(c *gin.Context) { + deviceID := deviceIDParam(c) + w := s.pool.GetWorker(deviceID) + if w == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备未找到或已离线"}) + return + } + + if err := validateOperatorScanWorker(w); err != nil { + logger.Error("扫描运营商失败", "device", deviceID, "err", err) + c.JSON(operatorSelectionErrorStatus(err), gin.H{"error": "扫描失败: " + err.Error()}) + return + } + + status, body := operatorScanHTTPStatusAndBody(w.StartOrGetOperatorScan(c.Request.Context())) + c.JSON(status, body) +} + +func (s *Server) handleDeviceMgmtOperatorScanStream(c *gin.Context) { + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-cache") + c.Header("Connection", "keep-alive") + + deviceID := deviceIDParam(c) + w := s.pool.GetWorker(deviceID) + if w == nil { + c.SSEvent("operator_scan", operatorScanResponse{ + Status: string(device.OperatorScanStatusFailed), + UpdatedAt: time.Now(), + Retryable: false, + Message: "设备未找到或已离线", + Error: "device_not_found", + }) + c.Writer.Flush() + return + } + + if err := validateOperatorScanWorker(w); err != nil { + c.SSEvent("operator_scan", operatorScanResponse{ + Status: string(device.OperatorScanStatusFailed), + UpdatedAt: time.Now(), + Retryable: false, + Message: "扫描失败: " + err.Error(), + Error: err.Error(), + }) + c.Writer.Flush() + return + } + + notify := c.Writer.CloseNotify() + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + + send := func(result device.OperatorScanResult) bool { + _, body := operatorScanHTTPStatusAndBody(result) + c.SSEvent("operator_scan", body) + c.Writer.Flush() + return operatorScanSSEShouldContinue(result) + } + + if !send(w.StartOrGetOperatorScan(c.Request.Context())) { + return + } + + for { + select { + case <-notify: + return + case <-c.Request.Context().Done(): + return + case <-s.shutdownCh: + return + case <-ticker.C: + if !send(w.GetOperatorScanSnapshot()) { + return + } + } + } +} + +func validateOperatorScanWorker(w *device.Worker) error { + if w == nil { + return device.ErrWorkerNil + } + if w.Backend == nil { + return device.ErrBackendNotAvailable + } + if _, ok := w.Backend.(backend.OperatorSelectionProvider); !ok { + return device.ErrOperatorSelectionNotSupported + } + return nil +} + +func operatorScanSSEShouldContinue(result device.OperatorScanResult) bool { + return result.Status == device.OperatorScanStatusRunning +} + +func operatorScanHTTPStatusAndBody(result device.OperatorScanResult) (int, operatorScanResponse) { + status := http.StatusOK + if result.Status == device.OperatorScanStatusRunning && len(result.Candidates) == 0 { + status = http.StatusAccepted + } + return status, operatorScanResponse{ + ScanID: result.ScanID, + Status: string(result.Status), + StartedAt: result.StartedAt, + UpdatedAt: result.UpdatedAt, + Complete: result.Complete, + Retryable: result.Retryable, + Message: result.Message, + Error: result.Err, + Candidates: result.Candidates, + } +} + +func (s *Server) handleDeviceMgmtGetOperatorSelection(c *gin.Context) { + deviceID := deviceIDParam(c) + w := s.pool.GetWorker(deviceID) + if w == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备未找到或已离线"}) + return + } + + sel, err := w.GetOperatorSelection(c.Request.Context()) + if err != nil { + logger.Error("读取运营商选择配置失败", "device", deviceID, "err", err) + c.JSON(operatorSelectionErrorStatus(err), gin.H{"error": "读取失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, sel) +} + +func (s *Server) handleDeviceMgmtSetOperatorSelection(c *gin.Context) { + deviceID := deviceIDParam(c) + var req backend.SetOperatorSelectionRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "参数无效"}) + return + } + + w := s.pool.GetWorker(deviceID) + if w == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "设备未找到或已离线"}) + return + } + + sel, err := w.SetOperatorSelection(c.Request.Context(), req) + if err != nil { + logger.Error("设置运营商失败", "device", deviceID, "err", err) + c.JSON(operatorSelectionErrorStatus(err), gin.H{"error": "设置失败: " + err.Error()}) + return + } + + // Persist to file + if err := config.UpdateDeviceInFile(s.configPath, deviceID, w.Config); err != nil { + logger.Error("写入设备配置失败 (operator selection)", "device", deviceID, "err", err) + } + + c.JSON(http.StatusOK, sel) +} diff --git a/internal/api/device_operator_selection_test.go b/internal/api/device_operator_selection_test.go new file mode 100644 index 00000000..3462f782 --- /dev/null +++ b/internal/api/device_operator_selection_test.go @@ -0,0 +1,110 @@ +package api + +import ( + "errors" + "net/http" + "testing" + "time" + + "github.com/iniwex5/vohive/internal/backend" + "github.com/iniwex5/vohive/internal/device" +) + +func TestOperatorSelectionErrorStatusMapsBusyStatesToConflict(t *testing.T) { + tests := []struct { + name string + err error + want int + }{ + {name: "vowifi active", err: device.ErrVoWiFiActive, want: http.StatusConflict}, + {name: "esim switching", err: device.ErrESIMSwitching, want: http.StatusConflict}, + {name: "unsupported", err: device.ErrOperatorSelectionNotSupported, want: http.StatusBadRequest}, + {name: "backend missing", err: device.ErrBackendNotAvailable, want: http.StatusServiceUnavailable}, + {name: "generic", err: errors.New("qmi failed"), want: http.StatusInternalServerError}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := operatorSelectionErrorStatus(tt.err); got != tt.want { + t.Fatalf("operatorSelectionErrorStatus(%v)=%d want %d", tt.err, got, tt.want) + } + }) + } +} + +func TestOperatorScanHTTPStatusAndBodyRunningWithoutCandidatesReturnsAccepted(t *testing.T) { + now := time.Now() + status, body := operatorScanHTTPStatusAndBody(device.OperatorScanResult{ + ScanID: "scan-1", + Status: device.OperatorScanStatusRunning, + StartedAt: now, + UpdatedAt: now, + Message: "扫描进行中", + }) + if status != http.StatusAccepted { + t.Fatalf("status=%d want %d", status, http.StatusAccepted) + } + if body.Status != string(device.OperatorScanStatusRunning) { + t.Fatalf("body status=%q", body.Status) + } +} + +func TestOperatorScanHTTPStatusAndBodyRetryableFailureReturnsOK(t *testing.T) { + now := time.Now() + status, body := operatorScanHTTPStatusAndBody(device.OperatorScanResult{ + ScanID: "scan-2", + Status: device.OperatorScanStatusFailed, + StartedAt: now, + UpdatedAt: now, + Retryable: true, + Message: "扫描超时或模组忙,请稍后重试", + Err: "context deadline exceeded", + }) + if status != http.StatusOK { + t.Fatalf("status=%d want %d", status, http.StatusOK) + } + if !body.Retryable { + t.Fatal("retryable=false want true") + } + if body.Message != "扫描超时或模组忙,请稍后重试" { + t.Fatalf("message=%q", body.Message) + } +} + +func TestOperatorScanHTTPStatusAndBodyCompleteKeepsCandidates(t *testing.T) { + now := time.Now() + status, body := operatorScanHTTPStatusAndBody(device.OperatorScanResult{ + ScanID: "scan-3", + Status: device.OperatorScanStatusComplete, + StartedAt: now, + UpdatedAt: now, + Complete: true, + Message: "扫描完成", + Candidates: []backend.OperatorCandidate{{PLMN: "46000", OperatorName: "CMCC", Status: "available"}}, + }) + if status != http.StatusOK { + t.Fatalf("status=%d want %d", status, http.StatusOK) + } + if len(body.Candidates) != 1 { + t.Fatalf("len(candidates)=%d want 1", len(body.Candidates)) + } +} + +func TestOperatorScanSSEShouldContinueOnlyForRunning(t *testing.T) { + tests := []struct { + name string + result device.OperatorScanResult + want bool + }{ + {name: "running", result: device.OperatorScanResult{Status: device.OperatorScanStatusRunning}, want: true}, + {name: "complete", result: device.OperatorScanResult{Status: device.OperatorScanStatusComplete}, want: false}, + {name: "failed", result: device.OperatorScanResult{Status: device.OperatorScanStatusFailed}, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := operatorScanSSEShouldContinue(tt.result); got != tt.want { + t.Fatalf("operatorScanSSEShouldContinue(%s)=%v want %v", tt.result.Status, got, tt.want) + } + }) + } +} diff --git a/internal/api/device_policy_display.go b/internal/api/device_policy_display.go new file mode 100644 index 00000000..7b58f831 --- /dev/null +++ b/internal/api/device_policy_display.go @@ -0,0 +1,68 @@ +package api + +import ( + "errors" + + "github.com/iniwex5/vohive/internal/config" + "github.com/iniwex5/vohive/internal/db" +) + +// cardPolicyFromDeviceConfig 把设备保存 DTO 解析出的策略字段映射为 card_policies 行。 +// SMS 不入策略(恒开),source 标记为 user(人工编辑)。不变式由 db.UpsertCardPolicy 归一。 +func cardPolicyFromDeviceConfig(iccid string, cfg config.DeviceConfig) db.CardPolicy { + return db.CardPolicy{ + ICCID: iccid, + NetworkEnabled: cfg.NetworkEnabled, + VoWiFiEnabled: cfg.VoWiFiEnabled, + AirplaneEnabled: cfg.AirplaneEnabled, + IPVersion: cfg.IPVersion, + APN: cfg.APN, + Source: "user", + } +} + +// currentEffectiveDevicePolicy 返回设备保存前的旧有效策略(用于开关转换判断): +// 在线取 worker 投影(已是有效值),离线退回 card_policies 解析。同时返回解析到的 ICCID。 +func (s *Server) currentEffectiveDevicePolicy(deviceID string) (iccid string, network, vowifi bool, ipVersion, apn string) { + if s.pool != nil { + if w := s.pool.GetWorker(deviceID); w != nil { + return w.CurrentICCID(), w.Config.NetworkEnabled, w.Config.VoWiFiEnabled, w.Config.IPVersion, w.Config.APN + } + } + off := resolveOfflineDevicePolicy(deviceID) + return db.CurrentICCIDForDevice(deviceID), off.NetworkEnabled, off.VoWiFiEnabled, off.IPVersion, off.APN +} + +// offlineDevicePolicy 是离线设备(无运行中 worker)用于展示的有效卡策略。 +type offlineDevicePolicy struct { + NetworkEnabled bool + VoWiFiEnabled bool + SMSEnabled bool + IPVersion string + APN string +} + +// resolveOfflineDevicePolicy 解析离线设备的有效策略用于 UI 展示: +// device → 当前 ICCID → card_policies。无 ICCID 或无策略记录时返回安全默认。 +// SMS 恒为启用(写死系统语义),与 card_policies 无关。 +func resolveOfflineDevicePolicy(deviceID string) offlineDevicePolicy { + out := offlineDevicePolicy{SMSEnabled: true, IPVersion: "v4"} + iccid := db.CurrentICCIDForDevice(deviceID) + if iccid == "" { + return out + } + pol, err := db.GetCardPolicy(iccid) + if err != nil { + if errors.Is(err, db.ErrCardPolicyNotFound) { + return out + } + return out + } + out.NetworkEnabled = pol.NetworkEnabled + out.VoWiFiEnabled = pol.VoWiFiEnabled + if pol.IPVersion != "" { + out.IPVersion = pol.IPVersion + } + out.APN = pol.APN + return out +} diff --git a/internal/api/device_policy_display_test.go b/internal/api/device_policy_display_test.go new file mode 100644 index 00000000..ea6ffe0b --- /dev/null +++ b/internal/api/device_policy_display_test.go @@ -0,0 +1,53 @@ +package api + +import ( + "path/filepath" + "testing" + + "github.com/iniwex5/vohive/internal/db" +) + +func initPolicyTestDB(t *testing.T) { + t.Helper() + if err := db.Init(filepath.Join(t.TempDir(), "policy.db")); err != nil { + t.Fatalf("db.Init() error=%v", err) + } + t.Cleanup(func() { + if db.DB != nil { + if sqlDB, err := db.DB.DB(); err == nil && sqlDB != nil { + _ = sqlDB.Close() + } + db.DB = nil + } + }) +} + +func TestResolveOfflineDevicePolicyFromCard(t *testing.T) { + initPolicyTestDB(t) + iccid := "8986007777777777777" + if err := db.DB.Create(&db.Device{IMEI: "imei-1", Alias: "wwan0", CurrentICCID: &iccid}).Error; err != nil { + t.Fatal(err) + } + if err := db.UpsertCardPolicy(db.CardPolicy{ICCID: iccid, NetworkEnabled: true, VoWiFiEnabled: true, IPVersion: "v4v6", Source: "user"}); err != nil { + t.Fatal(err) + } + + got := resolveOfflineDevicePolicy("wwan0") + if !got.NetworkEnabled || !got.VoWiFiEnabled { + t.Fatalf("应取卡策略: %+v", got) + } + if got.IPVersion != "v4v6" || !got.SMSEnabled { + t.Fatalf("ip/sms 错: %+v", got) + } +} + +func TestResolveOfflineDevicePolicyNoCardSafeDefault(t *testing.T) { + initPolicyTestDB(t) + got := resolveOfflineDevicePolicy("unknown-device") + if got.NetworkEnabled || got.VoWiFiEnabled { + t.Fatalf("无卡应全关: %+v", got) + } + if !got.SMSEnabled || got.IPVersion != "v4" { + t.Fatalf("默认应 sms=on/ip=v4: %+v", got) + } +} diff --git a/internal/api/device_traffic.go b/internal/api/device_traffic.go new file mode 100644 index 00000000..7e60f5d7 --- /dev/null +++ b/internal/api/device_traffic.go @@ -0,0 +1,68 @@ +package api + +import ( + "strings" + "time" + + "github.com/iniwex5/vohive/internal/db" + "github.com/iniwex5/vohive/internal/proxy/server" +) + +const ( + deviceTrafficStatusOK = "ok" + deviceTrafficStatusWaitingSample = "waiting_sample" + deviceTrafficStatusStale = "stale" +) + +const deviceTrafficStaleAfter = 150 * time.Second + +type deviceTrafficMeta struct { + Interface string `json:"interface"` + PeriodStart *time.Time `json:"period_start,omitempty"` + AgeSeconds int64 `json:"age_seconds,omitempty"` + Status string `json:"status"` +} + +func buildTrafficOverviewFields(iface string, delta db.LatestMinuteDeltas, now time.Time) (map[string]string, map[string]int64, *deviceTrafficMeta) { + iface = strings.TrimSpace(iface) + if iface == "" { + return nil, nil, nil + } + + meta := &deviceTrafficMeta{ + Interface: iface, + Status: deviceTrafficStatusWaitingSample, + } + if delta.PeriodStart.IsZero() { + return nil, nil, meta + } + + age := now.Sub(delta.PeriodStart) + if age < 0 { + age = 0 + } + meta.PeriodStart = &delta.PeriodStart + meta.AgeSeconds = int64(age.Seconds()) + meta.Status = deviceTrafficStatusOK + if age > deviceTrafficStaleAfter { + meta.Status = deviceTrafficStatusStale + } + + rx := delta.RxBytes + tx := delta.TxBytes + if rx < 0 { + rx = 0 + } + if tx < 0 { + tx = 0 + } + rate := float64(rx+tx) / 60.0 + return map[string]string{ + "rx": server.FormatBytes(rx), + "tx": server.FormatBytes(tx), + "rate": server.FormatBytes(int64(rate)) + "/s", + }, map[string]int64{ + "bytes_received": rx, + "bytes_sent": tx, + }, meta +} diff --git a/internal/api/device_traffic_test.go b/internal/api/device_traffic_test.go new file mode 100644 index 00000000..7e65fe0d --- /dev/null +++ b/internal/api/device_traffic_test.go @@ -0,0 +1,54 @@ +package api + +import ( + "testing" + "time" + + "github.com/iniwex5/vohive/internal/db" +) + +func TestBuildTrafficOverviewFieldsDistinguishesWaitingZeroAndStale(t *testing.T) { + now := time.Date(2026, time.May, 26, 10, 35, 0, 0, time.UTC) + + t.Run("waiting sample", func(t *testing.T) { + traffic, raw, meta := buildTrafficOverviewFields("wwan0", db.LatestMinuteDeltas{}, now) + if traffic != nil || raw != nil { + t.Fatalf("traffic=%v raw=%v want nil while waiting for first sample", traffic, raw) + } + if meta == nil || meta.Status != "waiting_sample" || meta.Interface != "wwan0" { + t.Fatalf("meta=%+v want waiting_sample for wwan0", meta) + } + }) + + t.Run("zero traffic sample", func(t *testing.T) { + periodStart := now.Add(-time.Minute) + traffic, raw, meta := buildTrafficOverviewFields("wwan0", db.LatestMinuteDeltas{ + PeriodStart: periodStart, + RxBytes: 0, + TxBytes: 0, + }, now) + if traffic["rx"] != "0 B" || traffic["tx"] != "0 B" || traffic["rate"] != "0 B/s" { + t.Fatalf("traffic=%v want formatted zero values", traffic) + } + if raw["bytes_received"] != 0 || raw["bytes_sent"] != 0 { + t.Fatalf("raw=%v want zero byte counters", raw) + } + if meta == nil || meta.Status != "ok" || meta.PeriodStart == nil || !meta.PeriodStart.Equal(periodStart) || meta.AgeSeconds != 60 { + t.Fatalf("meta=%+v want ok zero sample metadata", meta) + } + }) + + t.Run("stale sample", func(t *testing.T) { + traffic, raw, meta := buildTrafficOverviewFields("wwan0", db.LatestMinuteDeltas{ + PeriodStart: now.Add(-5 * time.Minute), + RxBytes: 100, + TxBytes: 50, + }, now) + if traffic["rx"] != "100 B" || raw["bytes_sent"] != 50 { + t.Fatalf("traffic=%v raw=%v want stale sample to keep byte values", traffic, raw) + } + if meta == nil || meta.Status != "stale" || meta.AgeSeconds != 300 { + t.Fatalf("meta=%+v want stale metadata", meta) + } + }) +} diff --git a/internal/api/docs_assets/swagger-ui/LICENSE b/internal/api/docs_assets/swagger-ui/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/internal/api/docs_assets/swagger-ui/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. 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. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You 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 the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You 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 such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its 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. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/api/docs_assets/swagger-ui/NOTICE b/internal/api/docs_assets/swagger-ui/NOTICE new file mode 100644 index 00000000..ab788a27 --- /dev/null +++ b/internal/api/docs_assets/swagger-ui/NOTICE @@ -0,0 +1,2 @@ +swagger-ui +Copyright 2020-2021 SmartBear Software Inc. diff --git a/internal/api/docs_assets/swagger-ui/swagger-ui-bundle.js b/internal/api/docs_assets/swagger-ui/swagger-ui-bundle.js new file mode 100644 index 00000000..d983f9cc --- /dev/null +++ b/internal/api/docs_assets/swagger-ui/swagger-ui-bundle.js @@ -0,0 +1,2 @@ +/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */ +!function webpackUniversalModuleDefinition(s,o){"object"==typeof exports&&"object"==typeof module?module.exports=o():"function"==typeof define&&define.amd?define([],o):"object"==typeof exports?exports.SwaggerUIBundle=o():s.SwaggerUIBundle=o()}(this,(()=>(()=>{var s={67526(s,o){"use strict";o.byteLength=function byteLength(s){var o=getLens(s),i=o[0],a=o[1];return 3*(i+a)/4-a},o.toByteArray=function toByteArray(s){var o,i,_=getLens(s),w=_[0],x=_[1],C=new u(function _byteLength(s,o,i){return 3*(o+i)/4-i}(0,w,x)),j=0,L=x>0?w-4:w;for(i=0;i>16&255,C[j++]=o>>8&255,C[j++]=255&o;2===x&&(o=a[s.charCodeAt(i)]<<2|a[s.charCodeAt(i+1)]>>4,C[j++]=255&o);1===x&&(o=a[s.charCodeAt(i)]<<10|a[s.charCodeAt(i+1)]<<4|a[s.charCodeAt(i+2)]>>2,C[j++]=o>>8&255,C[j++]=255&o);return C},o.fromByteArray=function fromByteArray(s){for(var o,a=s.length,u=a%3,_=[],w=16383,x=0,C=a-u;xC?C:x+w));1===u?(o=s[a-1],_.push(i[o>>2]+i[o<<4&63]+"==")):2===u&&(o=(s[a-2]<<8)+s[a-1],_.push(i[o>>10]+i[o>>4&63]+i[o<<2&63]+"="));return _.join("")};for(var i=[],a=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w=0;w<64;++w)i[w]=_[w],a[_.charCodeAt(w)]=w;function getLens(s){var o=s.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=s.indexOf("=");return-1===i&&(i=o),[i,i===o?0:4-i%4]}function encodeChunk(s,o,a){for(var u,_,w=[],x=o;x>18&63]+i[_>>12&63]+i[_>>6&63]+i[63&_]);return w.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},48287(s,o,i){"use strict";const a=i(67526),u=i(251),_="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;o.Buffer=Buffer,o.SlowBuffer=function SlowBuffer(s){+s!=s&&(s=0);return Buffer.alloc(+s)},o.INSPECT_MAX_BYTES=50;const w=2147483647;function createBuffer(s){if(s>w)throw new RangeError('The value "'+s+'" is invalid for option "size"');const o=new Uint8Array(s);return Object.setPrototypeOf(o,Buffer.prototype),o}function Buffer(s,o,i){if("number"==typeof s){if("string"==typeof o)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(s)}return from(s,o,i)}function from(s,o,i){if("string"==typeof s)return function fromString(s,o){"string"==typeof o&&""!==o||(o="utf8");if(!Buffer.isEncoding(o))throw new TypeError("Unknown encoding: "+o);const i=0|byteLength(s,o);let a=createBuffer(i);const u=a.write(s,o);u!==i&&(a=a.slice(0,u));return a}(s,o);if(ArrayBuffer.isView(s))return function fromArrayView(s){if(isInstance(s,Uint8Array)){const o=new Uint8Array(s);return fromArrayBuffer(o.buffer,o.byteOffset,o.byteLength)}return fromArrayLike(s)}(s);if(null==s)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(isInstance(s,ArrayBuffer)||s&&isInstance(s.buffer,ArrayBuffer))return fromArrayBuffer(s,o,i);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(s,SharedArrayBuffer)||s&&isInstance(s.buffer,SharedArrayBuffer)))return fromArrayBuffer(s,o,i);if("number"==typeof s)throw new TypeError('The "value" argument must not be of type number. Received type number');const a=s.valueOf&&s.valueOf();if(null!=a&&a!==s)return Buffer.from(a,o,i);const u=function fromObject(s){if(Buffer.isBuffer(s)){const o=0|checked(s.length),i=createBuffer(o);return 0===i.length||s.copy(i,0,0,o),i}if(void 0!==s.length)return"number"!=typeof s.length||numberIsNaN(s.length)?createBuffer(0):fromArrayLike(s);if("Buffer"===s.type&&Array.isArray(s.data))return fromArrayLike(s.data)}(s);if(u)return u;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof s[Symbol.toPrimitive])return Buffer.from(s[Symbol.toPrimitive]("string"),o,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}function assertSize(s){if("number"!=typeof s)throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function allocUnsafe(s){return assertSize(s),createBuffer(s<0?0:0|checked(s))}function fromArrayLike(s){const o=s.length<0?0:0|checked(s.length),i=createBuffer(o);for(let a=0;a=w)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+w.toString(16)+" bytes");return 0|s}function byteLength(s,o){if(Buffer.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||isInstance(s,ArrayBuffer))return s.byteLength;if("string"!=typeof s)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);const i=s.length,a=arguments.length>2&&!0===arguments[2];if(!a&&0===i)return 0;let u=!1;for(;;)switch(o){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return utf8ToBytes(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return base64ToBytes(s).length;default:if(u)return a?-1:utf8ToBytes(s).length;o=(""+o).toLowerCase(),u=!0}}function slowToString(s,o,i){let a=!1;if((void 0===o||o<0)&&(o=0),o>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(o>>>=0))return"";for(s||(s="utf8");;)switch(s){case"hex":return hexSlice(this,o,i);case"utf8":case"utf-8":return utf8Slice(this,o,i);case"ascii":return asciiSlice(this,o,i);case"latin1":case"binary":return latin1Slice(this,o,i);case"base64":return base64Slice(this,o,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,o,i);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),a=!0}}function swap(s,o,i){const a=s[o];s[o]=s[i],s[i]=a}function bidirectionalIndexOf(s,o,i,a,u){if(0===s.length)return-1;if("string"==typeof i?(a=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),numberIsNaN(i=+i)&&(i=u?0:s.length-1),i<0&&(i=s.length+i),i>=s.length){if(u)return-1;i=s.length-1}else if(i<0){if(!u)return-1;i=0}if("string"==typeof o&&(o=Buffer.from(o,a)),Buffer.isBuffer(o))return 0===o.length?-1:arrayIndexOf(s,o,i,a,u);if("number"==typeof o)return o&=255,"function"==typeof Uint8Array.prototype.indexOf?u?Uint8Array.prototype.indexOf.call(s,o,i):Uint8Array.prototype.lastIndexOf.call(s,o,i):arrayIndexOf(s,[o],i,a,u);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(s,o,i,a,u){let _,w=1,x=s.length,C=o.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(s.length<2||o.length<2)return-1;w=2,x/=2,C/=2,i/=2}function read(s,o){return 1===w?s[o]:s.readUInt16BE(o*w)}if(u){let a=-1;for(_=i;_x&&(i=x-C),_=i;_>=0;_--){let i=!0;for(let a=0;au&&(a=u):a=u;const _=o.length;let w;for(a>_/2&&(a=_/2),w=0;w>8,u=i%256,_.push(u),_.push(a);return _}(o,s.length-i),s,i,a)}function base64Slice(s,o,i){return 0===o&&i===s.length?a.fromByteArray(s):a.fromByteArray(s.slice(o,i))}function utf8Slice(s,o,i){i=Math.min(s.length,i);const a=[];let u=o;for(;u239?4:o>223?3:o>191?2:1;if(u+w<=i){let i,a,x,C;switch(w){case 1:o<128&&(_=o);break;case 2:i=s[u+1],128==(192&i)&&(C=(31&o)<<6|63&i,C>127&&(_=C));break;case 3:i=s[u+1],a=s[u+2],128==(192&i)&&128==(192&a)&&(C=(15&o)<<12|(63&i)<<6|63&a,C>2047&&(C<55296||C>57343)&&(_=C));break;case 4:i=s[u+1],a=s[u+2],x=s[u+3],128==(192&i)&&128==(192&a)&&128==(192&x)&&(C=(15&o)<<18|(63&i)<<12|(63&a)<<6|63&x,C>65535&&C<1114112&&(_=C))}}null===_?(_=65533,w=1):_>65535&&(_-=65536,a.push(_>>>10&1023|55296),_=56320|1023&_),a.push(_),u+=w}return function decodeCodePointsArray(s){const o=s.length;if(o<=x)return String.fromCharCode.apply(String,s);let i="",a=0;for(;aa.length?(Buffer.isBuffer(o)||(o=Buffer.from(o)),o.copy(a,u)):Uint8Array.prototype.set.call(a,o,u);else{if(!Buffer.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(a,u)}u+=o.length}return a},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){const s=this.length;if(s%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let o=0;oi&&(s+=" ... "),""},_&&(Buffer.prototype[_]=Buffer.prototype.inspect),Buffer.prototype.compare=function compare(s,o,i,a,u){if(isInstance(s,Uint8Array)&&(s=Buffer.from(s,s.offset,s.byteLength)),!Buffer.isBuffer(s))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof s);if(void 0===o&&(o=0),void 0===i&&(i=s?s.length:0),void 0===a&&(a=0),void 0===u&&(u=this.length),o<0||i>s.length||a<0||u>this.length)throw new RangeError("out of range index");if(a>=u&&o>=i)return 0;if(a>=u)return-1;if(o>=i)return 1;if(this===s)return 0;let _=(u>>>=0)-(a>>>=0),w=(i>>>=0)-(o>>>=0);const x=Math.min(_,w),C=this.slice(a,u),j=s.slice(o,i);for(let s=0;s>>=0,isFinite(i)?(i>>>=0,void 0===a&&(a="utf8")):(a=i,i=void 0)}const u=this.length-o;if((void 0===i||i>u)&&(i=u),s.length>0&&(i<0||o<0)||o>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");let _=!1;for(;;)switch(a){case"hex":return hexWrite(this,s,o,i);case"utf8":case"utf-8":return utf8Write(this,s,o,i);case"ascii":case"latin1":case"binary":return asciiWrite(this,s,o,i);case"base64":return base64Write(this,s,o,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,s,o,i);default:if(_)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),_=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function asciiSlice(s,o,i){let a="";i=Math.min(s.length,i);for(let u=o;ua)&&(i=a);let u="";for(let a=o;ai)throw new RangeError("Trying to access beyond buffer length")}function checkInt(s,o,i,a,u,_){if(!Buffer.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(o>u||o<_)throw new RangeError('"value" argument is out of bounds');if(i+a>s.length)throw new RangeError("Index out of range")}function wrtBigUInt64LE(s,o,i,a,u){checkIntBI(o,a,u,s,i,7);let _=Number(o&BigInt(4294967295));s[i++]=_,_>>=8,s[i++]=_,_>>=8,s[i++]=_,_>>=8,s[i++]=_;let w=Number(o>>BigInt(32)&BigInt(4294967295));return s[i++]=w,w>>=8,s[i++]=w,w>>=8,s[i++]=w,w>>=8,s[i++]=w,i}function wrtBigUInt64BE(s,o,i,a,u){checkIntBI(o,a,u,s,i,7);let _=Number(o&BigInt(4294967295));s[i+7]=_,_>>=8,s[i+6]=_,_>>=8,s[i+5]=_,_>>=8,s[i+4]=_;let w=Number(o>>BigInt(32)&BigInt(4294967295));return s[i+3]=w,w>>=8,s[i+2]=w,w>>=8,s[i+1]=w,w>>=8,s[i]=w,i+8}function checkIEEE754(s,o,i,a,u,_){if(i+a>s.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function writeFloat(s,o,i,a,_){return o=+o,i>>>=0,_||checkIEEE754(s,0,i,4),u.write(s,o,i,a,23,4),i+4}function writeDouble(s,o,i,a,_){return o=+o,i>>>=0,_||checkIEEE754(s,0,i,8),u.write(s,o,i,a,52,8),i+8}Buffer.prototype.slice=function slice(s,o){const i=this.length;(s=~~s)<0?(s+=i)<0&&(s=0):s>i&&(s=i),(o=void 0===o?i:~~o)<0?(o+=i)<0&&(o=0):o>i&&(o=i),o>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s],u=1,_=0;for(;++_>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s+--o],u=1;for(;o>0&&(u*=256);)a+=this[s+--o]*u;return a},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(s,o){return s>>>=0,o||checkOffset(s,1,this.length),this[s]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(s,o){return s>>>=0,o||checkOffset(s,2,this.length),this[s]|this[s+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(s,o){return s>>>=0,o||checkOffset(s,2,this.length),this[s]<<8|this[s+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),(this[s]|this[s+1]<<8|this[s+2]<<16)+16777216*this[s+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),16777216*this[s]+(this[s+1]<<16|this[s+2]<<8|this[s+3])},Buffer.prototype.readBigUInt64LE=defineBigIntMethod((function readBigUInt64LE(s){validateNumber(s>>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=o+256*this[++s]+65536*this[++s]+this[++s]*2**24,u=this[++s]+256*this[++s]+65536*this[++s]+i*2**24;return BigInt(a)+(BigInt(u)<>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=o*2**24+65536*this[++s]+256*this[++s]+this[++s],u=this[++s]*2**24+65536*this[++s]+256*this[++s]+i;return(BigInt(a)<>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s],u=1,_=0;for(;++_=u&&(a-=Math.pow(2,8*o)),a},Buffer.prototype.readIntBE=function readIntBE(s,o,i){s>>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=o,u=1,_=this[s+--a];for(;a>0&&(u*=256);)_+=this[s+--a]*u;return u*=128,_>=u&&(_-=Math.pow(2,8*o)),_},Buffer.prototype.readInt8=function readInt8(s,o){return s>>>=0,o||checkOffset(s,1,this.length),128&this[s]?-1*(255-this[s]+1):this[s]},Buffer.prototype.readInt16LE=function readInt16LE(s,o){s>>>=0,o||checkOffset(s,2,this.length);const i=this[s]|this[s+1]<<8;return 32768&i?4294901760|i:i},Buffer.prototype.readInt16BE=function readInt16BE(s,o){s>>>=0,o||checkOffset(s,2,this.length);const i=this[s+1]|this[s]<<8;return 32768&i?4294901760|i:i},Buffer.prototype.readInt32LE=function readInt32LE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),this[s]|this[s+1]<<8|this[s+2]<<16|this[s+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),this[s]<<24|this[s+1]<<16|this[s+2]<<8|this[s+3]},Buffer.prototype.readBigInt64LE=defineBigIntMethod((function readBigInt64LE(s){validateNumber(s>>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=this[s+4]+256*this[s+5]+65536*this[s+6]+(i<<24);return(BigInt(a)<>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=(o<<24)+65536*this[++s]+256*this[++s]+this[++s];return(BigInt(a)<>>=0,o||checkOffset(s,4,this.length),u.read(this,s,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),u.read(this,s,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(s,o){return s>>>=0,o||checkOffset(s,8,this.length),u.read(this,s,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(s,o){return s>>>=0,o||checkOffset(s,8,this.length),u.read(this,s,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(s,o,i,a){if(s=+s,o>>>=0,i>>>=0,!a){checkInt(this,s,o,i,Math.pow(2,8*i)-1,0)}let u=1,_=0;for(this[o]=255&s;++_>>=0,i>>>=0,!a){checkInt(this,s,o,i,Math.pow(2,8*i)-1,0)}let u=i-1,_=1;for(this[o+u]=255&s;--u>=0&&(_*=256);)this[o+u]=s/_&255;return o+i},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,1,255,0),this[o]=255&s,o+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,65535,0),this[o]=255&s,this[o+1]=s>>>8,o+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,65535,0),this[o]=s>>>8,this[o+1]=255&s,o+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,4294967295,0),this[o+3]=s>>>24,this[o+2]=s>>>16,this[o+1]=s>>>8,this[o]=255&s,o+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,4294967295,0),this[o]=s>>>24,this[o+1]=s>>>16,this[o+2]=s>>>8,this[o+3]=255&s,o+4},Buffer.prototype.writeBigUInt64LE=defineBigIntMethod((function writeBigUInt64LE(s,o=0){return wrtBigUInt64LE(this,s,o,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeBigUInt64BE=defineBigIntMethod((function writeBigUInt64BE(s,o=0){return wrtBigUInt64BE(this,s,o,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeIntLE=function writeIntLE(s,o,i,a){if(s=+s,o>>>=0,!a){const a=Math.pow(2,8*i-1);checkInt(this,s,o,i,a-1,-a)}let u=0,_=1,w=0;for(this[o]=255&s;++u>>=0,!a){const a=Math.pow(2,8*i-1);checkInt(this,s,o,i,a-1,-a)}let u=i-1,_=1,w=0;for(this[o+u]=255&s;--u>=0&&(_*=256);)s<0&&0===w&&0!==this[o+u+1]&&(w=1),this[o+u]=(s/_|0)-w&255;return o+i},Buffer.prototype.writeInt8=function writeInt8(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,1,127,-128),s<0&&(s=255+s+1),this[o]=255&s,o+1},Buffer.prototype.writeInt16LE=function writeInt16LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,32767,-32768),this[o]=255&s,this[o+1]=s>>>8,o+2},Buffer.prototype.writeInt16BE=function writeInt16BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,32767,-32768),this[o]=s>>>8,this[o+1]=255&s,o+2},Buffer.prototype.writeInt32LE=function writeInt32LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,2147483647,-2147483648),this[o]=255&s,this[o+1]=s>>>8,this[o+2]=s>>>16,this[o+3]=s>>>24,o+4},Buffer.prototype.writeInt32BE=function writeInt32BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,2147483647,-2147483648),s<0&&(s=4294967295+s+1),this[o]=s>>>24,this[o+1]=s>>>16,this[o+2]=s>>>8,this[o+3]=255&s,o+4},Buffer.prototype.writeBigInt64LE=defineBigIntMethod((function writeBigInt64LE(s,o=0){return wrtBigUInt64LE(this,s,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeBigInt64BE=defineBigIntMethod((function writeBigInt64BE(s,o=0){return wrtBigUInt64BE(this,s,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeFloatLE=function writeFloatLE(s,o,i){return writeFloat(this,s,o,!0,i)},Buffer.prototype.writeFloatBE=function writeFloatBE(s,o,i){return writeFloat(this,s,o,!1,i)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(s,o,i){return writeDouble(this,s,o,!0,i)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(s,o,i){return writeDouble(this,s,o,!1,i)},Buffer.prototype.copy=function copy(s,o,i,a){if(!Buffer.isBuffer(s))throw new TypeError("argument should be a Buffer");if(i||(i=0),a||0===a||(a=this.length),o>=s.length&&(o=s.length),o||(o=0),a>0&&a=this.length)throw new RangeError("Index out of range");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),s.length-o>>=0,i=void 0===i?this.length:i>>>0,s||(s=0),"number"==typeof s)for(u=o;u=a+4;i-=3)o=`_${s.slice(i-3,i)}${o}`;return`${s.slice(0,i)}${o}`}function checkIntBI(s,o,i,a,u,_){if(s>i||s3?0===o||o===BigInt(0)?`>= 0${a} and < 2${a} ** ${8*(_+1)}${a}`:`>= -(2${a} ** ${8*(_+1)-1}${a}) and < 2 ** ${8*(_+1)-1}${a}`:`>= ${o}${a} and <= ${i}${a}`,new C.ERR_OUT_OF_RANGE("value",u,s)}!function checkBounds(s,o,i){validateNumber(o,"offset"),void 0!==s[o]&&void 0!==s[o+i]||boundsError(o,s.length-(i+1))}(a,u,_)}function validateNumber(s,o){if("number"!=typeof s)throw new C.ERR_INVALID_ARG_TYPE(o,"number",s)}function boundsError(s,o,i){if(Math.floor(s)!==s)throw validateNumber(s,i),new C.ERR_OUT_OF_RANGE(i||"offset","an integer",s);if(o<0)throw new C.ERR_BUFFER_OUT_OF_BOUNDS;throw new C.ERR_OUT_OF_RANGE(i||"offset",`>= ${i?1:0} and <= ${o}`,s)}E("ERR_BUFFER_OUT_OF_BOUNDS",(function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),E("ERR_INVALID_ARG_TYPE",(function(s,o){return`The "${s}" argument must be of type number. Received type ${typeof o}`}),TypeError),E("ERR_OUT_OF_RANGE",(function(s,o,i){let a=`The value of "${s}" is out of range.`,u=i;return Number.isInteger(i)&&Math.abs(i)>2**32?u=addNumericalSeparator(String(i)):"bigint"==typeof i&&(u=String(i),(i>BigInt(2)**BigInt(32)||i<-(BigInt(2)**BigInt(32)))&&(u=addNumericalSeparator(u)),u+="n"),a+=` It must be ${o}. Received ${u}`,a}),RangeError);const j=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(s,o){let i;o=o||1/0;const a=s.length;let u=null;const _=[];for(let w=0;w55295&&i<57344){if(!u){if(i>56319){(o-=3)>-1&&_.push(239,191,189);continue}if(w+1===a){(o-=3)>-1&&_.push(239,191,189);continue}u=i;continue}if(i<56320){(o-=3)>-1&&_.push(239,191,189),u=i;continue}i=65536+(u-55296<<10|i-56320)}else u&&(o-=3)>-1&&_.push(239,191,189);if(u=null,i<128){if((o-=1)<0)break;_.push(i)}else if(i<2048){if((o-=2)<0)break;_.push(i>>6|192,63&i|128)}else if(i<65536){if((o-=3)<0)break;_.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((o-=4)<0)break;_.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return _}function base64ToBytes(s){return a.toByteArray(function base64clean(s){if((s=(s=s.split("=")[0]).trim().replace(j,"")).length<2)return"";for(;s.length%4!=0;)s+="=";return s}(s))}function blitBuffer(s,o,i,a){let u;for(u=0;u=o.length||u>=s.length);++u)o[u+i]=s[u];return u}function isInstance(s,o){return s instanceof o||null!=s&&null!=s.constructor&&null!=s.constructor.name&&s.constructor.name===o.name}function numberIsNaN(s){return s!=s}const L=function(){const s="0123456789abcdef",o=new Array(256);for(let i=0;i<16;++i){const a=16*i;for(let u=0;u<16;++u)o[a+u]=s[i]+s[u]}return o}();function defineBigIntMethod(s){return"undefined"==typeof BigInt?BufferBigIntNotDefined:s}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}},13144(s,o,i){"use strict";var a=i(66743),u=i(11002),_=i(10076),w=i(47119);s.exports=w||a.call(_,u)},12205(s,o,i){"use strict";var a=i(66743),u=i(11002),_=i(13144);s.exports=function applyBind(){return _(a,u,arguments)}},11002(s){"use strict";s.exports=Function.prototype.apply},10076(s){"use strict";s.exports=Function.prototype.call},73126(s,o,i){"use strict";var a=i(66743),u=i(69675),_=i(10076),w=i(13144);s.exports=function callBindBasic(s){if(s.length<1||"function"!=typeof s[0])throw new u("a function is required");return w(a,_,s)}},47119(s){"use strict";s.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply},10487(s,o,i){"use strict";var a=i(96897),u=i(30655),_=i(73126),w=i(12205);s.exports=function callBind(s){var o=_(arguments),i=s.length-(arguments.length-1);return a(o,1+(i>0?i:0),!0)},u?u(s.exports,"apply",{value:w}):s.exports.apply=w},36556(s,o,i){"use strict";var a=i(70453),u=i(73126),_=u([a("%String.prototype.indexOf%")]);s.exports=function callBoundIntrinsic(s,o){var i=a(s,!!o);return"function"==typeof i&&_(s,".prototype.")>-1?u([i]):i}},17965(s,o,i){"use strict";var a=i(16426),u={"text/plain":"Text","text/html":"Url",default:"Text"};s.exports=function copy(s,o){var i,_,w,x,C,j,L=!1;o||(o={}),i=o.debug||!1;try{if(w=a(),x=document.createRange(),C=document.getSelection(),(j=document.createElement("span")).textContent=s,j.ariaHidden="true",j.style.all="unset",j.style.position="fixed",j.style.top=0,j.style.clip="rect(0, 0, 0, 0)",j.style.whiteSpace="pre",j.style.webkitUserSelect="text",j.style.MozUserSelect="text",j.style.msUserSelect="text",j.style.userSelect="text",j.addEventListener("copy",(function(a){if(a.stopPropagation(),o.format)if(a.preventDefault(),void 0===a.clipboardData){i&&console.warn("unable to use e.clipboardData"),i&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var _=u[o.format]||u.default;window.clipboardData.setData(_,s)}else a.clipboardData.clearData(),a.clipboardData.setData(o.format,s);o.onCopy&&(a.preventDefault(),o.onCopy(a.clipboardData))})),document.body.appendChild(j),x.selectNodeContents(j),C.addRange(x),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");L=!0}catch(a){i&&console.error("unable to copy using execCommand: ",a),i&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(o.format||"text",s),o.onCopy&&o.onCopy(window.clipboardData),L=!0}catch(a){i&&console.error("unable to copy using clipboardData: ",a),i&&console.error("falling back to prompt"),_=function format(s){var o=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return s.replace(/#{\s*key\s*}/g,o)}("message"in o?o.message:"Copy to clipboard: #{key}, Enter"),window.prompt(_,s)}}finally{C&&("function"==typeof C.removeRange?C.removeRange(x):C.removeAllRanges()),j&&document.body.removeChild(j),w()}return L}},2205(s,o,i){var a;a=void 0!==i.g?i.g:this,s.exports=function(s){if(s.CSS&&s.CSS.escape)return s.CSS.escape;var cssEscape=function(s){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var o,i=String(s),a=i.length,u=-1,_="",w=i.charCodeAt(0);++u=1&&o<=31||127==o||0==u&&o>=48&&o<=57||1==u&&o>=48&&o<=57&&45==w?"\\"+o.toString(16)+" ":0==u&&1==a&&45==o||!(o>=128||45==o||95==o||o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122)?"\\"+i.charAt(u):i.charAt(u):_+="�";return _};return s.CSS||(s.CSS={}),s.CSS.escape=cssEscape,cssEscape}(a)},81919(s,o,i){"use strict";var a=i(48287).Buffer;function isSpecificValue(s){return s instanceof a||s instanceof Date||s instanceof RegExp}function cloneSpecificValue(s){if(s instanceof a){var o=a.alloc?a.alloc(s.length):new a(s.length);return s.copy(o),o}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s);throw new Error("Unexpected situation")}function deepCloneArray(s){var o=[];return s.forEach((function(s,i){"object"==typeof s&&null!==s?Array.isArray(s)?o[i]=deepCloneArray(s):isSpecificValue(s)?o[i]=cloneSpecificValue(s):o[i]=u({},s):o[i]=s})),o}function safeGetProperty(s,o){return"__proto__"===o?void 0:s[o]}var u=s.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var s,o,i=arguments[0];return Array.prototype.slice.call(arguments,1).forEach((function(a){"object"!=typeof a||null===a||Array.isArray(a)||Object.keys(a).forEach((function(_){return o=safeGetProperty(i,_),(s=safeGetProperty(a,_))===i?void 0:"object"!=typeof s||null===s?void(i[_]=s):Array.isArray(s)?void(i[_]=deepCloneArray(s)):isSpecificValue(s)?void(i[_]=cloneSpecificValue(s)):"object"!=typeof o||null===o||Array.isArray(o)?void(i[_]=u({},s)):void(i[_]=u(o,s))}))})),i}},14744(s){"use strict";var o=function isMergeableObject(s){return function isNonNullObject(s){return!!s&&"object"==typeof s}(s)&&!function isSpecial(s){var o=Object.prototype.toString.call(s);return"[object RegExp]"===o||"[object Date]"===o||function isReactElement(s){return s.$$typeof===i}(s)}(s)};var i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function cloneUnlessOtherwiseSpecified(s,o){return!1!==o.clone&&o.isMergeableObject(s)?deepmerge(function emptyTarget(s){return Array.isArray(s)?[]:{}}(s),s,o):s}function defaultArrayMerge(s,o,i){return s.concat(o).map((function(s){return cloneUnlessOtherwiseSpecified(s,i)}))}function getKeys(s){return Object.keys(s).concat(function getEnumerableOwnPropertySymbols(s){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(s).filter((function(o){return Object.propertyIsEnumerable.call(s,o)})):[]}(s))}function propertyIsOnObject(s,o){try{return o in s}catch(s){return!1}}function mergeObject(s,o,i){var a={};return i.isMergeableObject(s)&&getKeys(s).forEach((function(o){a[o]=cloneUnlessOtherwiseSpecified(s[o],i)})),getKeys(o).forEach((function(u){(function propertyIsUnsafe(s,o){return propertyIsOnObject(s,o)&&!(Object.hasOwnProperty.call(s,o)&&Object.propertyIsEnumerable.call(s,o))})(s,u)||(propertyIsOnObject(s,u)&&i.isMergeableObject(o[u])?a[u]=function getMergeFunction(s,o){if(!o.customMerge)return deepmerge;var i=o.customMerge(s);return"function"==typeof i?i:deepmerge}(u,i)(s[u],o[u],i):a[u]=cloneUnlessOtherwiseSpecified(o[u],i))})),a}function deepmerge(s,i,a){(a=a||{}).arrayMerge=a.arrayMerge||defaultArrayMerge,a.isMergeableObject=a.isMergeableObject||o,a.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var u=Array.isArray(i);return u===Array.isArray(s)?u?a.arrayMerge(s,i,a):mergeObject(s,i,a):cloneUnlessOtherwiseSpecified(i,a)}deepmerge.all=function deepmergeAll(s,o){if(!Array.isArray(s))throw new Error("first argument should be an array");return s.reduce((function(s,i){return deepmerge(s,i,o)}),{})};var a=deepmerge;s.exports=a},30041(s,o,i){"use strict";var a=i(30655),u=i(58068),_=i(69675),w=i(75795);s.exports=function defineDataProperty(s,o,i){if(!s||"object"!=typeof s&&"function"!=typeof s)throw new _("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new _("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new _("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new _("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new _("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new _("`loose`, if provided, must be a boolean");var x=arguments.length>3?arguments[3]:null,C=arguments.length>4?arguments[4]:null,j=arguments.length>5?arguments[5]:null,L=arguments.length>6&&arguments[6],B=!!w&&w(s,o);if(a)a(s,o,{configurable:null===j&&B?B.configurable:!j,enumerable:null===x&&B?B.enumerable:!x,value:i,writable:null===C&&B?B.writable:!C});else{if(!L&&(x||C||j))throw new u("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");s[o]=i}}},78004(s){"use strict";class SubRange{constructor(s,o){this.low=s,this.high=o,this.length=1+o-s}overlaps(s){return!(this.highs.high)}touches(s){return!(this.high+1s.high)}add(s){return new SubRange(Math.min(this.low,s.low),Math.max(this.high,s.high))}subtract(s){return s.low<=this.low&&s.high>=this.high?[]:s.low>this.low&&s.highs+o.length),0)}add(s,o){var _add=s=>{for(var o=0;o{for(var o=0;o{for(var o=0;o{for(var i=o.low;i<=o.high;)s.push(i),i++;return s}),[])}subranges(){return this.ranges.map((s=>({low:s.low,high:s.high,length:1+s.high-s.low})))}}s.exports=DRange},7176(s,o,i){"use strict";var a,u=i(73126),_=i(75795);try{a=[].__proto__===Array.prototype}catch(s){if(!s||"object"!=typeof s||!("code"in s)||"ERR_PROTO_ACCESS"!==s.code)throw s}var w=!!a&&_&&_(Object.prototype,"__proto__"),x=Object,C=x.getPrototypeOf;s.exports=w&&"function"==typeof w.get?u([w.get]):"function"==typeof C&&function getDunder(s){return C(null==s?s:x(s))}},30655(s){"use strict";var o=Object.defineProperty||!1;if(o)try{o({},"a",{value:1})}catch(s){o=!1}s.exports=o},41237(s){"use strict";s.exports=EvalError},69383(s){"use strict";s.exports=Error},79290(s){"use strict";s.exports=RangeError},79538(s){"use strict";s.exports=ReferenceError},58068(s){"use strict";s.exports=SyntaxError},69675(s){"use strict";s.exports=TypeError},35345(s){"use strict";s.exports=URIError},79612(s){"use strict";s.exports=Object},37007(s){"use strict";var o,i="object"==typeof Reflect?Reflect:null,a=i&&"function"==typeof i.apply?i.apply:function ReflectApply(s,o,i){return Function.prototype.apply.call(s,o,i)};o=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s)};var u=Number.isNaN||function NumberIsNaN(s){return s!=s};function EventEmitter(){EventEmitter.init.call(this)}s.exports=EventEmitter,s.exports.once=function once(s,o){return new Promise((function(i,a){function errorListener(i){s.removeListener(o,resolver),a(i)}function resolver(){"function"==typeof s.removeListener&&s.removeListener("error",errorListener),i([].slice.call(arguments))}eventTargetAgnosticAddListener(s,o,resolver,{once:!0}),"error"!==o&&function addErrorHandlerIfEventEmitter(s,o,i){"function"==typeof s.on&&eventTargetAgnosticAddListener(s,"error",o,i)}(s,errorListener,{once:!0})}))},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var _=10;function checkListener(s){if("function"!=typeof s)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}function _getMaxListeners(s){return void 0===s._maxListeners?EventEmitter.defaultMaxListeners:s._maxListeners}function _addListener(s,o,i,a){var u,_,w;if(checkListener(i),void 0===(_=s._events)?(_=s._events=Object.create(null),s._eventsCount=0):(void 0!==_.newListener&&(s.emit("newListener",o,i.listener?i.listener:i),_=s._events),w=_[o]),void 0===w)w=_[o]=i,++s._eventsCount;else if("function"==typeof w?w=_[o]=a?[i,w]:[w,i]:a?w.unshift(i):w.push(i),(u=_getMaxListeners(s))>0&&w.length>u&&!w.warned){w.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+w.length+" "+String(o)+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=s,x.type=o,x.count=w.length,function ProcessEmitWarning(s){console&&console.warn&&console.warn(s)}(x)}return s}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(s,o,i){var a={fired:!1,wrapFn:void 0,target:s,type:o,listener:i},u=onceWrapper.bind(a);return u.listener=i,a.wrapFn=u,u}function _listeners(s,o,i){var a=s._events;if(void 0===a)return[];var u=a[o];return void 0===u?[]:"function"==typeof u?i?[u.listener||u]:[u]:i?function unwrapListeners(s){for(var o=new Array(s.length),i=0;i0&&(w=o[0]),w instanceof Error)throw w;var x=new Error("Unhandled error."+(w?" ("+w.message+")":""));throw x.context=w,x}var C=_[s];if(void 0===C)return!1;if("function"==typeof C)a(C,this,o);else{var j=C.length,L=arrayClone(C,j);for(i=0;i=0;_--)if(i[_]===o||i[_].listener===o){w=i[_].listener,u=_;break}if(u<0)return this;0===u?i.shift():function spliceOne(s,o){for(;o+1=0;a--)this.removeListener(s,o[a]);return this},EventEmitter.prototype.listeners=function listeners(s){return _listeners(this,s,!0)},EventEmitter.prototype.rawListeners=function rawListeners(s){return _listeners(this,s,!1)},EventEmitter.listenerCount=function(s,o){return"function"==typeof s.listenerCount?s.listenerCount(o):listenerCount.call(s,o)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?o(this._events):[]}},85587(s,o,i){"use strict";var a=i(26311),u=create(Error);function create(s){return FormattedError.displayName=s.displayName||s.name,FormattedError;function FormattedError(o){return o&&(o=a.apply(null,arguments)),new s(o)}}s.exports=u,u.eval=create(EvalError),u.range=create(RangeError),u.reference=create(ReferenceError),u.syntax=create(SyntaxError),u.type=create(TypeError),u.uri=create(URIError),u.create=create},82682(s,o,i){"use strict";var a=i(69600),u=Object.prototype.toString,_=Object.prototype.hasOwnProperty;s.exports=function forEach(s,o,i){if(!a(o))throw new TypeError("iterator must be a function");var w;arguments.length>=3&&(w=i),function isArray(s){return"[object Array]"===u.call(s)}(s)?function forEachArray(s,o,i){for(var a=0,u=s.length;a0?parseInt(i):null};x1&&"boolean"!=typeof o)throw new L('"allowMissing" argument must be a boolean');if(null===Xe(/^%?[^%]*%?$/,s))throw new j("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function stringToPath(s){var o=Ye(s,0,1),i=Ye(s,-1);if("%"===o&&"%"!==i)throw new j("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==o)throw new j("invalid intrinsic syntax, expected opening `%`");var a=[];return He(s,Qe,(function(s,o,i,u){a[a.length]=i?He(u,et,"$1"):o||s})),a}(s),a=i.length>0?i[0]:"",u=tt("%"+a+"%",o),_=u.name,w=u.value,x=!1,C=u.alias;C&&(a=C[0],We(i,ze([0,1],C)));for(var B=1,$=!0;B=i.length){var Y=ae(w,U);w=($=!!Y)&&"get"in Y&&!("originalValue"in Y.get)?Y.get:w[U]}else $=qe(w,U),w=w[U];$&&!x&&(xe[_]=w)}}return w}},71064(s,o,i){"use strict";var a=i(79612);s.exports=a.getPrototypeOf||null},48648(s){"use strict";s.exports="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null},93628(s,o,i){"use strict";var a=i(48648),u=i(71064),_=i(7176);s.exports=a?function getProto(s){return a(s)}:u?function getProto(s){if(!s||"object"!=typeof s&&"function"!=typeof s)throw new TypeError("getProto: not an object");return u(s)}:_?function getProto(s){return _(s)}:null},6549(s){"use strict";s.exports=Object.getOwnPropertyDescriptor},75795(s,o,i){"use strict";var a=i(6549);if(a)try{a([],"length")}catch(s){a=null}s.exports=a},30592(s,o,i){"use strict";var a=i(30655),u=function hasPropertyDescriptors(){return!!a};u.hasArrayLengthDefineBug=function hasArrayLengthDefineBug(){if(!a)return null;try{return 1!==a([],"length",{value:1}).length}catch(s){return!0}},s.exports=u},64039(s,o,i){"use strict";var a="undefined"!=typeof Symbol&&Symbol,u=i(41333);s.exports=function hasNativeSymbols(){return"function"==typeof a&&("function"==typeof Symbol&&("symbol"==typeof a("foo")&&("symbol"==typeof Symbol("bar")&&u())))}},41333(s){"use strict";s.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var s={},o=Symbol("test"),i=Object(o);if("string"==typeof o)return!1;if("[object Symbol]"!==Object.prototype.toString.call(o))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var a in s[o]=42,s)return!1;if("function"==typeof Object.keys&&0!==Object.keys(s).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(s).length)return!1;var u=Object.getOwnPropertySymbols(s);if(1!==u.length||u[0]!==o)return!1;if(!Object.prototype.propertyIsEnumerable.call(s,o))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var _=Object.getOwnPropertyDescriptor(s,o);if(42!==_.value||!0!==_.enumerable)return!1}return!0}},49092(s,o,i){"use strict";var a=i(41333);s.exports=function hasToStringTagShams(){return a()&&!!Symbol.toStringTag}},9957(s,o,i){"use strict";var a=Function.prototype.call,u=Object.prototype.hasOwnProperty,_=i(66743);s.exports=_.call(a,u)},45981(s){function deepFreeze(s){return s instanceof Map?s.clear=s.delete=s.set=function(){throw new Error("map is read-only")}:s instanceof Set&&(s.add=s.clear=s.delete=function(){throw new Error("set is read-only")}),Object.freeze(s),Object.getOwnPropertyNames(s).forEach((function(o){var i=s[o];"object"!=typeof i||Object.isFrozen(i)||deepFreeze(i)})),s}var o=deepFreeze,i=deepFreeze;o.default=i;class Response{constructor(s){void 0===s.data&&(s.data={}),this.data=s.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function escapeHTML(s){return s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function inherit(s,...o){const i=Object.create(null);for(const o in s)i[o]=s[o];return o.forEach((function(s){for(const o in s)i[o]=s[o]})),i}const emitsWrappingTags=s=>!!s.kind;class HTMLRenderer{constructor(s,o){this.buffer="",this.classPrefix=o.classPrefix,s.walk(this)}addText(s){this.buffer+=escapeHTML(s)}openNode(s){if(!emitsWrappingTags(s))return;let o=s.kind;s.sublanguage||(o=`${this.classPrefix}${o}`),this.span(o)}closeNode(s){emitsWrappingTags(s)&&(this.buffer+="")}value(){return this.buffer}span(s){this.buffer+=``}}class TokenTree{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(s){this.top.children.push(s)}openNode(s){const o={kind:s,children:[]};this.add(o),this.stack.push(o)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(s){return this.constructor._walk(s,this.rootNode)}static _walk(s,o){return"string"==typeof o?s.addText(o):o.children&&(s.openNode(o),o.children.forEach((o=>this._walk(s,o))),s.closeNode(o)),s}static _collapse(s){"string"!=typeof s&&s.children&&(s.children.every((s=>"string"==typeof s))?s.children=[s.children.join("")]:s.children.forEach((s=>{TokenTree._collapse(s)})))}}class TokenTreeEmitter extends TokenTree{constructor(s){super(),this.options=s}addKeyword(s,o){""!==s&&(this.openNode(o),this.addText(s),this.closeNode())}addText(s){""!==s&&this.add(s)}addSublanguage(s,o){const i=s.root;i.kind=o,i.sublanguage=!0,this.add(i)}toHTML(){return new HTMLRenderer(this,this.options).value()}finalize(){return!0}}function source(s){return s?"string"==typeof s?s:s.source:null}const a=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;const u="[a-zA-Z]\\w*",_="[a-zA-Z_]\\w*",w="\\b\\d+(\\.\\d+)?",x="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",C="\\b(0b[01]+)",j={begin:"\\\\[\\s\\S]",relevance:0},L={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[j]},B={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[j]},$={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},COMMENT=function(s,o,i={}){const a=inherit({className:"comment",begin:s,end:o,contains:[]},i);return a.contains.push($),a.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),a},U=COMMENT("//","$"),V=COMMENT("/\\*","\\*/"),z=COMMENT("#","$"),Y={className:"number",begin:w,relevance:0},Z={className:"number",begin:x,relevance:0},ee={className:"number",begin:C,relevance:0},ie={className:"number",begin:w+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},ae={begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[j,{begin:/\[/,end:/\]/,relevance:0,contains:[j]}]}]},ce={className:"title",begin:u,relevance:0},le={className:"title",begin:_,relevance:0},pe={begin:"\\.\\s*"+_,relevance:0};var de=Object.freeze({__proto__:null,MATCH_NOTHING_RE:/\b\B/,IDENT_RE:u,UNDERSCORE_IDENT_RE:_,NUMBER_RE:w,C_NUMBER_RE:x,BINARY_NUMBER_RE:C,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(s={})=>{const o=/^#![ ]*\//;return s.binary&&(s.begin=function concat(...s){return s.map((s=>source(s))).join("")}(o,/.*\b/,s.binary,/\b.*/)),inherit({className:"meta",begin:o,end:/$/,relevance:0,"on:begin":(s,o)=>{0!==s.index&&o.ignoreMatch()}},s)},BACKSLASH_ESCAPE:j,APOS_STRING_MODE:L,QUOTE_STRING_MODE:B,PHRASAL_WORDS_MODE:$,COMMENT,C_LINE_COMMENT_MODE:U,C_BLOCK_COMMENT_MODE:V,HASH_COMMENT_MODE:z,NUMBER_MODE:Y,C_NUMBER_MODE:Z,BINARY_NUMBER_MODE:ee,CSS_NUMBER_MODE:ie,REGEXP_MODE:ae,TITLE_MODE:ce,UNDERSCORE_TITLE_MODE:le,METHOD_GUARD:pe,END_SAME_AS_BEGIN:function(s){return Object.assign(s,{"on:begin":(s,o)=>{o.data._beginMatch=s[1]},"on:end":(s,o)=>{o.data._beginMatch!==s[1]&&o.ignoreMatch()}})}});function skipIfhasPrecedingDot(s,o){"."===s.input[s.index-1]&&o.ignoreMatch()}function beginKeywords(s,o){o&&s.beginKeywords&&(s.begin="\\b("+s.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",s.__beforeBegin=skipIfhasPrecedingDot,s.keywords=s.keywords||s.beginKeywords,delete s.beginKeywords,void 0===s.relevance&&(s.relevance=0))}function compileIllegal(s,o){Array.isArray(s.illegal)&&(s.illegal=function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}(...s.illegal))}function compileMatch(s,o){if(s.match){if(s.begin||s.end)throw new Error("begin & end are not supported with match");s.begin=s.match,delete s.match}}function compileRelevance(s,o){void 0===s.relevance&&(s.relevance=1)}const fe=["of","and","for","in","not","or","if","then","parent","list","value"];function compileKeywords(s,o,i="keyword"){const a={};return"string"==typeof s?compileList(i,s.split(" ")):Array.isArray(s)?compileList(i,s):Object.keys(s).forEach((function(i){Object.assign(a,compileKeywords(s[i],o,i))})),a;function compileList(s,i){o&&(i=i.map((s=>s.toLowerCase()))),i.forEach((function(o){const i=o.split("|");a[i[0]]=[s,scoreForKeyword(i[0],i[1])]}))}}function scoreForKeyword(s,o){return o?Number(o):function commonKeyword(s){return fe.includes(s.toLowerCase())}(s)?0:1}function compileLanguage(s,{plugins:o}){function langRe(o,i){return new RegExp(source(o),"m"+(s.case_insensitive?"i":"")+(i?"g":""))}class MultiRegex{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(s,o){o.position=this.position++,this.matchIndexes[this.matchAt]=o,this.regexes.push([o,s]),this.matchAt+=function countMatchGroups(s){return new RegExp(s.toString()+"|").exec("").length-1}(s)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const s=this.regexes.map((s=>s[1]));this.matcherRe=langRe(function join(s,o="|"){let i=0;return s.map((s=>{i+=1;const o=i;let u=source(s),_="";for(;u.length>0;){const s=a.exec(u);if(!s){_+=u;break}_+=u.substring(0,s.index),u=u.substring(s.index+s[0].length),"\\"===s[0][0]&&s[1]?_+="\\"+String(Number(s[1])+o):(_+=s[0],"("===s[0]&&i++)}return _})).map((s=>`(${s})`)).join(o)}(s),!0),this.lastIndex=0}exec(s){this.matcherRe.lastIndex=this.lastIndex;const o=this.matcherRe.exec(s);if(!o)return null;const i=o.findIndex(((s,o)=>o>0&&void 0!==s)),a=this.matchIndexes[i];return o.splice(0,i),Object.assign(o,a)}}class ResumableMultiRegex{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(s){if(this.multiRegexes[s])return this.multiRegexes[s];const o=new MultiRegex;return this.rules.slice(s).forEach((([s,i])=>o.addRule(s,i))),o.compile(),this.multiRegexes[s]=o,o}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(s,o){this.rules.push([s,o]),"begin"===o.type&&this.count++}exec(s){const o=this.getMatcher(this.regexIndex);o.lastIndex=this.lastIndex;let i=o.exec(s);if(this.resumingScanAtSamePosition())if(i&&i.index===this.lastIndex);else{const o=this.getMatcher(0);o.lastIndex=this.lastIndex+1,i=o.exec(s)}return i&&(this.regexIndex+=i.position+1,this.regexIndex===this.count&&this.considerAll()),i}}if(s.compilerExtensions||(s.compilerExtensions=[]),s.contains&&s.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return s.classNameAliases=inherit(s.classNameAliases||{}),function compileMode(o,i){const a=o;if(o.isCompiled)return a;[compileMatch].forEach((s=>s(o,i))),s.compilerExtensions.forEach((s=>s(o,i))),o.__beforeBegin=null,[beginKeywords,compileIllegal,compileRelevance].forEach((s=>s(o,i))),o.isCompiled=!0;let u=null;if("object"==typeof o.keywords&&(u=o.keywords.$pattern,delete o.keywords.$pattern),o.keywords&&(o.keywords=compileKeywords(o.keywords,s.case_insensitive)),o.lexemes&&u)throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return u=u||o.lexemes||/\w+/,a.keywordPatternRe=langRe(u,!0),i&&(o.begin||(o.begin=/\B|\b/),a.beginRe=langRe(o.begin),o.endSameAsBegin&&(o.end=o.begin),o.end||o.endsWithParent||(o.end=/\B|\b/),o.end&&(a.endRe=langRe(o.end)),a.terminatorEnd=source(o.end)||"",o.endsWithParent&&i.terminatorEnd&&(a.terminatorEnd+=(o.end?"|":"")+i.terminatorEnd)),o.illegal&&(a.illegalRe=langRe(o.illegal)),o.contains||(o.contains=[]),o.contains=[].concat(...o.contains.map((function(s){return function expandOrCloneMode(s){s.variants&&!s.cachedVariants&&(s.cachedVariants=s.variants.map((function(o){return inherit(s,{variants:null},o)})));if(s.cachedVariants)return s.cachedVariants;if(dependencyOnParent(s))return inherit(s,{starts:s.starts?inherit(s.starts):null});if(Object.isFrozen(s))return inherit(s);return s}("self"===s?o:s)}))),o.contains.forEach((function(s){compileMode(s,a)})),o.starts&&compileMode(o.starts,i),a.matcher=function buildModeRegex(s){const o=new ResumableMultiRegex;return s.contains.forEach((s=>o.addRule(s.begin,{rule:s,type:"begin"}))),s.terminatorEnd&&o.addRule(s.terminatorEnd,{type:"end"}),s.illegal&&o.addRule(s.illegal,{type:"illegal"}),o}(a),a}(s)}function dependencyOnParent(s){return!!s&&(s.endsWithParent||dependencyOnParent(s.starts))}function BuildVuePlugin(s){const o={props:["language","code","autodetect"],data:function(){return{detectedLanguage:"",unknownLanguage:!1}},computed:{className(){return this.unknownLanguage?"":"hljs "+this.detectedLanguage},highlighted(){if(!this.autoDetect&&!s.getLanguage(this.language))return console.warn(`The language "${this.language}" you specified could not be found.`),this.unknownLanguage=!0,escapeHTML(this.code);let o={};return this.autoDetect?(o=s.highlightAuto(this.code),this.detectedLanguage=o.language):(o=s.highlight(this.language,this.code,this.ignoreIllegals),this.detectedLanguage=this.language),o.value},autoDetect(){return!this.language||function hasValueOrEmptyAttribute(s){return Boolean(s||""===s)}(this.autodetect)},ignoreIllegals:()=>!0},render(s){return s("pre",{},[s("code",{class:this.className,domProps:{innerHTML:this.highlighted}})])}};return{Component:o,VuePlugin:{install(s){s.component("highlightjs",o)}}}}const ye={"after:highlightElement":({el:s,result:o,text:i})=>{const a=nodeStream(s);if(!a.length)return;const u=document.createElement("div");u.innerHTML=o.value,o.value=function mergeStreams(s,o,i){let a=0,u="";const _=[];function selectStream(){return s.length&&o.length?s[0].offset!==o[0].offset?s[0].offset"}function close(s){u+=""}function render(s){("start"===s.event?open:close)(s.node)}for(;s.length||o.length;){let o=selectStream();if(u+=escapeHTML(i.substring(a,o[0].offset)),a=o[0].offset,o===s){_.reverse().forEach(close);do{render(o.splice(0,1)[0]),o=selectStream()}while(o===s&&o.length&&o[0].offset===a);_.reverse().forEach(open)}else"start"===o[0].event?_.push(o[0].node):_.pop(),render(o.splice(0,1)[0])}return u+escapeHTML(i.substr(a))}(a,nodeStream(u),i)}};function tag(s){return s.nodeName.toLowerCase()}function nodeStream(s){const o=[];return function _nodeStream(s,i){for(let a=s.firstChild;a;a=a.nextSibling)3===a.nodeType?i+=a.nodeValue.length:1===a.nodeType&&(o.push({event:"start",offset:i,node:a}),i=_nodeStream(a,i),tag(a).match(/br|hr|img|input/)||o.push({event:"stop",offset:i,node:a}));return i}(s,0),o}const be={},error=s=>{console.error(s)},warn=(s,...o)=>{console.log(`WARN: ${s}`,...o)},deprecated=(s,o)=>{be[`${s}/${o}`]||(console.log(`Deprecated as of ${s}. ${o}`),be[`${s}/${o}`]=!0)},Se=escapeHTML,_e=inherit,we=Symbol("nomatch");var xe=function(s){const i=Object.create(null),a=Object.create(null),u=[];let _=!0;const w=/(^(<[^>]+>|\t|)+|\n)/gm,x="Could not find the language '{}', did you forget to load/include a language module?",C={disableAutodetect:!0,name:"Plain text",contains:[]};let j={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:TokenTreeEmitter};function shouldNotHighlight(s){return j.noHighlightRe.test(s)}function highlight(s,o,i,a){let u="",_="";"object"==typeof o?(u=s,i=o.ignoreIllegals,_=o.language,a=void 0):(deprecated("10.7.0","highlight(lang, code, ...args) has been deprecated."),deprecated("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),_=s,u=o);const w={code:u,language:_};fire("before:highlight",w);const x=w.result?w.result:_highlight(w.language,w.code,i,a);return x.code=w.code,fire("after:highlight",x),x}function _highlight(s,o,a,w){function keywordData(s,o){const i=L.case_insensitive?o[0].toLowerCase():o[0];return Object.prototype.hasOwnProperty.call(s.keywords,i)&&s.keywords[i]}function processBuffer(){null!=U.subLanguage?function processSubLanguage(){if(""===Y)return;let s=null;if("string"==typeof U.subLanguage){if(!i[U.subLanguage])return void z.addText(Y);s=_highlight(U.subLanguage,Y,!0,V[U.subLanguage]),V[U.subLanguage]=s.top}else s=highlightAuto(Y,U.subLanguage.length?U.subLanguage:null);U.relevance>0&&(Z+=s.relevance),z.addSublanguage(s.emitter,s.language)}():function processKeywords(){if(!U.keywords)return void z.addText(Y);let s=0;U.keywordPatternRe.lastIndex=0;let o=U.keywordPatternRe.exec(Y),i="";for(;o;){i+=Y.substring(s,o.index);const a=keywordData(U,o);if(a){const[s,u]=a;if(z.addText(i),i="",Z+=u,s.startsWith("_"))i+=o[0];else{const i=L.classNameAliases[s]||s;z.addKeyword(o[0],i)}}else i+=o[0];s=U.keywordPatternRe.lastIndex,o=U.keywordPatternRe.exec(Y)}i+=Y.substr(s),z.addText(i)}(),Y=""}function startNewMode(s){return s.className&&z.openNode(L.classNameAliases[s.className]||s.className),U=Object.create(s,{parent:{value:U}}),U}function endOfMode(s,o,i){let a=function startsWith(s,o){const i=s&&s.exec(o);return i&&0===i.index}(s.endRe,i);if(a){if(s["on:end"]){const i=new Response(s);s["on:end"](o,i),i.isMatchIgnored&&(a=!1)}if(a){for(;s.endsParent&&s.parent;)s=s.parent;return s}}if(s.endsWithParent)return endOfMode(s.parent,o,i)}function doIgnore(s){return 0===U.matcher.regexIndex?(Y+=s[0],1):(ae=!0,0)}function doBeginMatch(s){const o=s[0],i=s.rule,a=new Response(i),u=[i.__beforeBegin,i["on:begin"]];for(const i of u)if(i&&(i(s,a),a.isMatchIgnored))return doIgnore(o);return i&&i.endSameAsBegin&&(i.endRe=function escape(s){return new RegExp(s.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}(o)),i.skip?Y+=o:(i.excludeBegin&&(Y+=o),processBuffer(),i.returnBegin||i.excludeBegin||(Y=o)),startNewMode(i),i.returnBegin?0:o.length}function doEndMatch(s){const i=s[0],a=o.substr(s.index),u=endOfMode(U,s,a);if(!u)return we;const _=U;_.skip?Y+=i:(_.returnEnd||_.excludeEnd||(Y+=i),processBuffer(),_.excludeEnd&&(Y=i));do{U.className&&z.closeNode(),U.skip||U.subLanguage||(Z+=U.relevance),U=U.parent}while(U!==u.parent);return u.starts&&(u.endSameAsBegin&&(u.starts.endRe=u.endRe),startNewMode(u.starts)),_.returnEnd?0:i.length}let C={};function processLexeme(i,u){const w=u&&u[0];if(Y+=i,null==w)return processBuffer(),0;if("begin"===C.type&&"end"===u.type&&C.index===u.index&&""===w){if(Y+=o.slice(u.index,u.index+1),!_){const o=new Error("0 width match regex");throw o.languageName=s,o.badRule=C.rule,o}return 1}if(C=u,"begin"===u.type)return doBeginMatch(u);if("illegal"===u.type&&!a){const s=new Error('Illegal lexeme "'+w+'" for mode "'+(U.className||"")+'"');throw s.mode=U,s}if("end"===u.type){const s=doEndMatch(u);if(s!==we)return s}if("illegal"===u.type&&""===w)return 1;if(ie>1e5&&ie>3*u.index){throw new Error("potential infinite loop, way more iterations than matches")}return Y+=w,w.length}const L=getLanguage(s);if(!L)throw error(x.replace("{}",s)),new Error('Unknown language: "'+s+'"');const B=compileLanguage(L,{plugins:u});let $="",U=w||B;const V={},z=new j.__emitter(j);!function processContinuations(){const s=[];for(let o=U;o!==L;o=o.parent)o.className&&s.unshift(o.className);s.forEach((s=>z.openNode(s)))}();let Y="",Z=0,ee=0,ie=0,ae=!1;try{for(U.matcher.considerAll();;){ie++,ae?ae=!1:U.matcher.considerAll(),U.matcher.lastIndex=ee;const s=U.matcher.exec(o);if(!s)break;const i=processLexeme(o.substring(ee,s.index),s);ee=s.index+i}return processLexeme(o.substr(ee)),z.closeAllNodes(),z.finalize(),$=z.toHTML(),{relevance:Math.floor(Z),value:$,language:s,illegal:!1,emitter:z,top:U}}catch(i){if(i.message&&i.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:i.message,context:o.slice(ee-100,ee+100),mode:i.mode},sofar:$,relevance:0,value:Se(o),emitter:z};if(_)return{illegal:!1,relevance:0,value:Se(o),emitter:z,language:s,top:U,errorRaised:i};throw i}}function highlightAuto(s,o){o=o||j.languages||Object.keys(i);const a=function justTextHighlightResult(s){const o={relevance:0,emitter:new j.__emitter(j),value:Se(s),illegal:!1,top:C};return o.emitter.addText(s),o}(s),u=o.filter(getLanguage).filter(autoDetection).map((o=>_highlight(o,s,!1)));u.unshift(a);const _=u.sort(((s,o)=>{if(s.relevance!==o.relevance)return o.relevance-s.relevance;if(s.language&&o.language){if(getLanguage(s.language).supersetOf===o.language)return 1;if(getLanguage(o.language).supersetOf===s.language)return-1}return 0})),[w,x]=_,L=w;return L.second_best=x,L}const L={"before:highlightElement":({el:s})=>{j.useBR&&(s.innerHTML=s.innerHTML.replace(/\n/g,"").replace(//g,"\n"))},"after:highlightElement":({result:s})=>{j.useBR&&(s.value=s.value.replace(/\n/g,"
"))}},B=/^(<[^>]+>|\t)+/gm,$={"after:highlightElement":({result:s})=>{j.tabReplace&&(s.value=s.value.replace(B,(s=>s.replace(/\t/g,j.tabReplace))))}};function highlightElement(s){let o=null;const i=function blockLanguage(s){let o=s.className+" ";o+=s.parentNode?s.parentNode.className:"";const i=j.languageDetectRe.exec(o);if(i){const o=getLanguage(i[1]);return o||(warn(x.replace("{}",i[1])),warn("Falling back to no-highlight mode for this block.",s)),o?i[1]:"no-highlight"}return o.split(/\s+/).find((s=>shouldNotHighlight(s)||getLanguage(s)))}(s);if(shouldNotHighlight(i))return;fire("before:highlightElement",{el:s,language:i}),o=s;const u=o.textContent,_=i?highlight(u,{language:i,ignoreIllegals:!0}):highlightAuto(u);fire("after:highlightElement",{el:s,result:_,text:u}),s.innerHTML=_.value,function updateClassName(s,o,i){const u=o?a[o]:i;s.classList.add("hljs"),u&&s.classList.add(u)}(s,i,_.language),s.result={language:_.language,re:_.relevance,relavance:_.relevance},_.second_best&&(s.second_best={language:_.second_best.language,re:_.second_best.relevance,relavance:_.second_best.relevance})}const initHighlighting=()=>{if(initHighlighting.called)return;initHighlighting.called=!0,deprecated("10.6.0","initHighlighting() is deprecated. Use highlightAll() instead.");document.querySelectorAll("pre code").forEach(highlightElement)};let U=!1;function highlightAll(){if("loading"===document.readyState)return void(U=!0);document.querySelectorAll("pre code").forEach(highlightElement)}function getLanguage(s){return s=(s||"").toLowerCase(),i[s]||i[a[s]]}function registerAliases(s,{languageName:o}){"string"==typeof s&&(s=[s]),s.forEach((s=>{a[s.toLowerCase()]=o}))}function autoDetection(s){const o=getLanguage(s);return o&&!o.disableAutodetect}function fire(s,o){const i=s;u.forEach((function(s){s[i]&&s[i](o)}))}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(function boot(){U&&highlightAll()}),!1),Object.assign(s,{highlight,highlightAuto,highlightAll,fixMarkup:function deprecateFixMarkup(s){return deprecated("10.2.0","fixMarkup will be removed entirely in v11.0"),deprecated("10.2.0","Please see https://github.com/highlightjs/highlight.js/issues/2534"),function fixMarkup(s){return j.tabReplace||j.useBR?s.replace(w,(s=>"\n"===s?j.useBR?"
":s:j.tabReplace?s.replace(/\t/g,j.tabReplace):s)):s}(s)},highlightElement,highlightBlock:function deprecateHighlightBlock(s){return deprecated("10.7.0","highlightBlock will be removed entirely in v12.0"),deprecated("10.7.0","Please use highlightElement now."),highlightElement(s)},configure:function configure(s){s.useBR&&(deprecated("10.3.0","'useBR' will be removed entirely in v11.0"),deprecated("10.3.0","Please see https://github.com/highlightjs/highlight.js/issues/2559")),j=_e(j,s)},initHighlighting,initHighlightingOnLoad:function initHighlightingOnLoad(){deprecated("10.6.0","initHighlightingOnLoad() is deprecated. Use highlightAll() instead."),U=!0},registerLanguage:function registerLanguage(o,a){let u=null;try{u=a(s)}catch(s){if(error("Language definition for '{}' could not be registered.".replace("{}",o)),!_)throw s;error(s),u=C}u.name||(u.name=o),i[o]=u,u.rawDefinition=a.bind(null,s),u.aliases&®isterAliases(u.aliases,{languageName:o})},unregisterLanguage:function unregisterLanguage(s){delete i[s];for(const o of Object.keys(a))a[o]===s&&delete a[o]},listLanguages:function listLanguages(){return Object.keys(i)},getLanguage,registerAliases,requireLanguage:function requireLanguage(s){deprecated("10.4.0","requireLanguage will be removed entirely in v11."),deprecated("10.4.0","Please see https://github.com/highlightjs/highlight.js/pull/2844");const o=getLanguage(s);if(o)return o;throw new Error("The '{}' language is required, but not loaded.".replace("{}",s))},autoDetection,inherit:_e,addPlugin:function addPlugin(s){!function upgradePluginAPI(s){s["before:highlightBlock"]&&!s["before:highlightElement"]&&(s["before:highlightElement"]=o=>{s["before:highlightBlock"](Object.assign({block:o.el},o))}),s["after:highlightBlock"]&&!s["after:highlightElement"]&&(s["after:highlightElement"]=o=>{s["after:highlightBlock"](Object.assign({block:o.el},o))})}(s),u.push(s)},vuePlugin:BuildVuePlugin(s).VuePlugin}),s.debugMode=function(){_=!1},s.safeMode=function(){_=!0},s.versionString="10.7.3";for(const s in de)"object"==typeof de[s]&&o(de[s]);return Object.assign(s,de),s.addPlugin(L),s.addPlugin(ye),s.addPlugin($),s}({});s.exports=xe},35344(s){function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function bash(s){const o={},i={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[o]}]};Object.assign(o,{className:"variable",variants:[{begin:concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},i]});const a={className:"subst",begin:/\$\(/,end:/\)/,contains:[s.BACKSLASH_ESCAPE]},u={begin:/<<-?\s*(?=\w+)/,starts:{contains:[s.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},_={className:"string",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE,o,a]};a.contains.push(_);const w={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},s.NUMBER_MODE,o]},x=s.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),C={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[s.inherit(s.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z._-]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"},contains:[x,s.SHEBANG(),C,w,s.HASH_COMMENT_MODE,u,_,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},o]}}},73402(s){function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function http(s){const o="HTTP/(2|1\\.[01])",i={className:"attribute",begin:concat("^",/[A-Za-z][A-Za-z0-9-]*/,"(?=\\:\\s)"),starts:{contains:[{className:"punctuation",begin:/: /,relevance:0,starts:{end:"$",relevance:0}}]}},a=[i,{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}];return{name:"HTTP",aliases:["https"],illegal:/\S/,contains:[{begin:"^(?="+o+" \\d{3})",end:/$/,contains:[{className:"meta",begin:o},{className:"number",begin:"\\b\\d{3}\\b"}],starts:{end:/\b\B/,illegal:/\S/,contains:a}},{begin:"(?=^[A-Z]+ (.*?) "+o+"$)",end:/$/,contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{className:"meta",begin:o},{className:"keyword",begin:"[A-Z]+"}],starts:{end:/\b\B/,illegal:/\S/,contains:a}},s.inherit(i,{relevance:0})]}}},95089(s){const o="[A-Za-z$_][0-9A-Za-z$_]*",i=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],a=["true","false","null","undefined","NaN","Infinity"],u=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["arguments","this","super","console","window","document","localStorage","module","global"],["Intl","DataView","Number","Math","Date","String","RegExp","Object","Function","Boolean","Error","Symbol","Set","Map","WeakSet","WeakMap","Proxy","Reflect","JSON","Promise","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Float32Array","Array","Uint8Array","Uint8ClampedArray","ArrayBuffer","BigInt64Array","BigUint64Array","BigInt"],["EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function javascript(s){const _=o,w="<>",x="",C={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(s,o)=>{const i=s[0].length+s.index,a=s.input[i];"<"!==a?">"===a&&(((s,{after:o})=>{const i="",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:s.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:j,contains:ce}]}]},{begin:/,/,relevance:0},{className:"",begin:/\s/,end:/\s*/,skip:!0},{variants:[{begin:w,end:x},{begin:C.begin,"on:begin":C.isTrulyOpeningTag,end:C.end}],subLanguage:"xml",contains:[{begin:C.begin,end:C.end,skip:!0,contains:["self"]}]}],relevance:0},{className:"function",beginKeywords:"function",end:/[{;]/,excludeEnd:!0,keywords:j,contains:["self",s.inherit(s.TITLE_MODE,{begin:_}),le],illegal:/%/},{beginKeywords:"while if switch catch for"},{className:"function",begin:s.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,contains:[le,s.inherit(s.TITLE_MODE,{begin:_})]},{variants:[{begin:"\\."+_},{begin:"\\$"+_}],relevance:0},{className:"class",beginKeywords:"class",end:/[{;=]/,excludeEnd:!0,illegal:/[:"[\]]/,contains:[{beginKeywords:"extends"},s.UNDERSCORE_TITLE_MODE]},{begin:/\b(?=constructor)/,end:/[{;]/,excludeEnd:!0,contains:[s.inherit(s.TITLE_MODE,{begin:_}),"self",le]},{begin:"(get|set)\\s+(?="+_+"\\()",end:/\{/,keywords:"get set",contains:[s.inherit(s.TITLE_MODE,{begin:_}),{begin:/\(\)/},le]},{begin:/\$[(.]/}]}}},65772(s){s.exports=function json(s){const o={literal:"true false null"},i=[s.C_LINE_COMMENT_MODE,s.C_BLOCK_COMMENT_MODE],a=[s.QUOTE_STRING_MODE,s.C_NUMBER_MODE],u={end:",",endsWithParent:!0,excludeEnd:!0,contains:a,keywords:o},_={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE],illegal:"\\n"},s.inherit(u,{begin:/:/})].concat(i),illegal:"\\S"},w={begin:"\\[",end:"\\]",contains:[s.inherit(u)],illegal:"\\S"};return a.push(_,w),i.forEach((function(s){a.push(s)})),{name:"JSON",contains:a,keywords:o,illegal:"\\S"}}},26571(s){s.exports=function powershell(s){const o={$pattern:/-?[A-z\.\-]+\b/,keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",built_in:"ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"},i={begin:"`[\\s\\S]",relevance:0},a={className:"variable",variants:[{begin:/\$\B/},{className:"keyword",begin:/\$this/},{begin:/\$[\w\d][\w\d_:]*/}]},u={className:"string",variants:[{begin:/"/,end:/"/},{begin:/@"/,end:/^"@/}],contains:[i,a,{className:"variable",begin:/\$[A-z]/,end:/[^A-z]/}]},_={className:"string",variants:[{begin:/'/,end:/'/},{begin:/@'/,end:/^'@/}]},w=s.inherit(s.COMMENT(null,null),{variants:[{begin:/#/,end:/$/},{begin:/<#/,end:/#>/}],contains:[{className:"doctag",variants:[{begin:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{begin:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),x={className:"built_in",variants:[{begin:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},C={className:"class",beginKeywords:"class enum",end:/\s*[{]/,excludeEnd:!0,relevance:0,contains:[s.TITLE_MODE]},j={className:"function",begin:/function\s+/,end:/\s*\{|$/,excludeEnd:!0,returnBegin:!0,relevance:0,contains:[{begin:"function",relevance:0,className:"keyword"},{className:"title",begin:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{begin:/\(/,end:/\)/,className:"params",relevance:0,contains:[a]}]},L={begin:/using\s/,end:/$/,returnBegin:!0,contains:[u,_,{className:"keyword",begin:/(using|assembly|command|module|namespace|type)/}]},B={variants:[{className:"operator",begin:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{className:"literal",begin:/(-)[\w\d]+/,relevance:0}]},$={className:"function",begin:/\[.*\]\s*[\w]+[ ]??\(/,end:/$/,returnBegin:!0,relevance:0,contains:[{className:"keyword",begin:"(".concat(o.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},s.inherit(s.TITLE_MODE,{endsParent:!0})]},U=[$,w,i,s.NUMBER_MODE,u,_,x,a,{className:"literal",begin:/\$(null|true|false)\b/},{className:"selector-tag",begin:/@\B/,relevance:0}],V={begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[].concat("self",U,{begin:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",className:"built_in",relevance:0},{className:"type",begin:/[\.\w\d]+/,relevance:0})};return $.contains.unshift(V),{name:"PowerShell",aliases:["ps","ps1"],case_insensitive:!0,keywords:o,contains:U.concat(C,j,L,B,V)}}},17285(s){function source(s){return s?"string"==typeof s?s:s.source:null}function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>source(s))).join("")}function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}s.exports=function xml(s){const o=concat(/[A-Z_]/,function optional(s){return concat("(",s,")?")}(/[A-Z0-9_.-]*:/),/[A-Z0-9_.-]*/),i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:"meta-keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},u=s.inherit(a,{begin:/\(/,end:/\)/}),_=s.inherit(s.APOS_STRING_MODE,{className:"meta-string"}),w=s.inherit(s.QUOTE_STRING_MODE,{className:"meta-string"}),x={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin://,relevance:10,contains:[a,w,_,u,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[a,u,w,_]}]}]},s.COMMENT(//,{relevance:10}),{begin://,relevance:10},i,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[x],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[x],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:o,relevance:0,starts:x}]},{className:"tag",begin:concat(/<\//,lookahead(concat(o,/>/))),contains:[{className:"name",begin:o,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}},17533(s){s.exports=function yaml(s){var o="true false yes no null",i="[\\w#;/?:@&=+$,.~*'()[\\]]+",a={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[s.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},u=s.inherit(a,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),_={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},w={end:",",endsWithParent:!0,excludeEnd:!0,keywords:o,relevance:0},x={begin:/\{/,end:/\}/,contains:[w],illegal:"\\n",relevance:0},C={begin:"\\[",end:"\\]",contains:[w],illegal:"\\n",relevance:0},j=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+i},{className:"type",begin:"!<"+i+">"},{className:"type",begin:"!"+i},{className:"type",begin:"!!"+i},{className:"meta",begin:"&"+s.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+s.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},s.HASH_COMMENT_MODE,{beginKeywords:o,keywords:{literal:o}},_,{className:"number",begin:s.C_NUMBER_RE+"\\b",relevance:0},x,C,a],L=[...j];return L.pop(),L.push(u),w.contains=L,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:j}}},251(s,o){o.read=function(s,o,i,a,u){var _,w,x=8*u-a-1,C=(1<>1,L=-7,B=i?u-1:0,$=i?-1:1,U=s[o+B];for(B+=$,_=U&(1<<-L)-1,U>>=-L,L+=x;L>0;_=256*_+s[o+B],B+=$,L-=8);for(w=_&(1<<-L)-1,_>>=-L,L+=a;L>0;w=256*w+s[o+B],B+=$,L-=8);if(0===_)_=1-j;else{if(_===C)return w?NaN:1/0*(U?-1:1);w+=Math.pow(2,a),_-=j}return(U?-1:1)*w*Math.pow(2,_-a)},o.write=function(s,o,i,a,u,_){var w,x,C,j=8*_-u-1,L=(1<>1,$=23===u?Math.pow(2,-24)-Math.pow(2,-77):0,U=a?0:_-1,V=a?1:-1,z=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(x=isNaN(o)?1:0,w=L):(w=Math.floor(Math.log(o)/Math.LN2),o*(C=Math.pow(2,-w))<1&&(w--,C*=2),(o+=w+B>=1?$/C:$*Math.pow(2,1-B))*C>=2&&(w++,C/=2),w+B>=L?(x=0,w=L):w+B>=1?(x=(o*C-1)*Math.pow(2,u),w+=B):(x=o*Math.pow(2,B-1)*Math.pow(2,u),w=0));u>=8;s[i+U]=255&x,U+=V,x/=256,u-=8);for(w=w<0;s[i+U]=255&w,U+=V,w/=256,j-=8);s[i+U-V]|=128*z}},9404(s){s.exports=function(){"use strict";var s=Array.prototype.slice;function createClass(s,o){o&&(s.prototype=Object.create(o.prototype)),s.prototype.constructor=s}function Iterable(s){return isIterable(s)?s:Seq(s)}function KeyedIterable(s){return isKeyed(s)?s:KeyedSeq(s)}function IndexedIterable(s){return isIndexed(s)?s:IndexedSeq(s)}function SetIterable(s){return isIterable(s)&&!isAssociative(s)?s:SetSeq(s)}function isIterable(s){return!(!s||!s[o])}function isKeyed(s){return!(!s||!s[i])}function isIndexed(s){return!(!s||!s[a])}function isAssociative(s){return isKeyed(s)||isIndexed(s)}function isOrdered(s){return!(!s||!s[u])}createClass(KeyedIterable,Iterable),createClass(IndexedIterable,Iterable),createClass(SetIterable,Iterable),Iterable.isIterable=isIterable,Iterable.isKeyed=isKeyed,Iterable.isIndexed=isIndexed,Iterable.isAssociative=isAssociative,Iterable.isOrdered=isOrdered,Iterable.Keyed=KeyedIterable,Iterable.Indexed=IndexedIterable,Iterable.Set=SetIterable;var o="@@__IMMUTABLE_ITERABLE__@@",i="@@__IMMUTABLE_KEYED__@@",a="@@__IMMUTABLE_INDEXED__@@",u="@@__IMMUTABLE_ORDERED__@@",_="delete",w=5,x=1<>>0;if(""+i!==o||4294967295===i)return NaN;o=i}return o<0?ensureSize(s)+o:o}function returnTrue(){return!0}function wholeSlice(s,o,i){return(0===s||void 0!==i&&s<=-i)&&(void 0===o||void 0!==i&&o>=i)}function resolveBegin(s,o){return resolveIndex(s,o,0)}function resolveEnd(s,o){return resolveIndex(s,o,o)}function resolveIndex(s,o,i){return void 0===s?i:s<0?Math.max(0,o+s):void 0===o?s:Math.min(o,s)}var $=0,U=1,V=2,z="function"==typeof Symbol&&Symbol.iterator,Y="@@iterator",Z=z||Y;function Iterator(s){this.next=s}function iteratorValue(s,o,i,a){var u=0===s?o:1===s?i:[o,i];return a?a.value=u:a={value:u,done:!1},a}function iteratorDone(){return{value:void 0,done:!0}}function hasIterator(s){return!!getIteratorFn(s)}function isIterator(s){return s&&"function"==typeof s.next}function getIterator(s){var o=getIteratorFn(s);return o&&o.call(s)}function getIteratorFn(s){var o=s&&(z&&s[z]||s[Y]);if("function"==typeof o)return o}function isArrayLike(s){return s&&"number"==typeof s.length}function Seq(s){return null==s?emptySequence():isIterable(s)?s.toSeq():seqFromValue(s)}function KeyedSeq(s){return null==s?emptySequence().toKeyedSeq():isIterable(s)?isKeyed(s)?s.toSeq():s.fromEntrySeq():keyedSeqFromValue(s)}function IndexedSeq(s){return null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s.toIndexedSeq():indexedSeqFromValue(s)}function SetSeq(s){return(null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s:indexedSeqFromValue(s)).toSetSeq()}Iterator.prototype.toString=function(){return"[Iterator]"},Iterator.KEYS=$,Iterator.VALUES=U,Iterator.ENTRIES=V,Iterator.prototype.inspect=Iterator.prototype.toSource=function(){return this.toString()},Iterator.prototype[Z]=function(){return this},createClass(Seq,Iterable),Seq.of=function(){return Seq(arguments)},Seq.prototype.toSeq=function(){return this},Seq.prototype.toString=function(){return this.__toString("Seq {","}")},Seq.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},Seq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!0)},Seq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!0)},createClass(KeyedSeq,Seq),KeyedSeq.prototype.toKeyedSeq=function(){return this},createClass(IndexedSeq,Seq),IndexedSeq.of=function(){return IndexedSeq(arguments)},IndexedSeq.prototype.toIndexedSeq=function(){return this},IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")},IndexedSeq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!1)},IndexedSeq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!1)},createClass(SetSeq,Seq),SetSeq.of=function(){return SetSeq(arguments)},SetSeq.prototype.toSetSeq=function(){return this},Seq.isSeq=isSeq,Seq.Keyed=KeyedSeq,Seq.Set=SetSeq,Seq.Indexed=IndexedSeq;var ee,ie,ae,ce="@@__IMMUTABLE_SEQ__@@";function ArraySeq(s){this._array=s,this.size=s.length}function ObjectSeq(s){var o=Object.keys(s);this._object=s,this._keys=o,this.size=o.length}function IterableSeq(s){this._iterable=s,this.size=s.length||s.size}function IteratorSeq(s){this._iterator=s,this._iteratorCache=[]}function isSeq(s){return!(!s||!s[ce])}function emptySequence(){return ee||(ee=new ArraySeq([]))}function keyedSeqFromValue(s){var o=Array.isArray(s)?new ArraySeq(s).fromEntrySeq():isIterator(s)?new IteratorSeq(s).fromEntrySeq():hasIterator(s)?new IterableSeq(s).fromEntrySeq():"object"==typeof s?new ObjectSeq(s):void 0;if(!o)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+s);return o}function indexedSeqFromValue(s){var o=maybeIndexedSeqFromValue(s);if(!o)throw new TypeError("Expected Array or iterable object of values: "+s);return o}function seqFromValue(s){var o=maybeIndexedSeqFromValue(s)||"object"==typeof s&&new ObjectSeq(s);if(!o)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+s);return o}function maybeIndexedSeqFromValue(s){return isArrayLike(s)?new ArraySeq(s):isIterator(s)?new IteratorSeq(s):hasIterator(s)?new IterableSeq(s):void 0}function seqIterate(s,o,i,a){var u=s._cache;if(u){for(var _=u.length-1,w=0;w<=_;w++){var x=u[i?_-w:w];if(!1===o(x[1],a?x[0]:w,s))return w+1}return w}return s.__iterateUncached(o,i)}function seqIterator(s,o,i,a){var u=s._cache;if(u){var _=u.length-1,w=0;return new Iterator((function(){var s=u[i?_-w:w];return w++>_?iteratorDone():iteratorValue(o,a?s[0]:w-1,s[1])}))}return s.__iteratorUncached(o,i)}function fromJS(s,o){return o?fromJSWith(o,s,"",{"":s}):fromJSDefault(s)}function fromJSWith(s,o,i,a){return Array.isArray(o)?s.call(a,i,IndexedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):isPlainObj(o)?s.call(a,i,KeyedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):o}function fromJSDefault(s){return Array.isArray(s)?IndexedSeq(s).map(fromJSDefault).toList():isPlainObj(s)?KeyedSeq(s).map(fromJSDefault).toMap():s}function isPlainObj(s){return s&&(s.constructor===Object||void 0===s.constructor)}function is(s,o){if(s===o||s!=s&&o!=o)return!0;if(!s||!o)return!1;if("function"==typeof s.valueOf&&"function"==typeof o.valueOf){if((s=s.valueOf())===(o=o.valueOf())||s!=s&&o!=o)return!0;if(!s||!o)return!1}return!("function"!=typeof s.equals||"function"!=typeof o.equals||!s.equals(o))}function deepEqual(s,o){if(s===o)return!0;if(!isIterable(o)||void 0!==s.size&&void 0!==o.size&&s.size!==o.size||void 0!==s.__hash&&void 0!==o.__hash&&s.__hash!==o.__hash||isKeyed(s)!==isKeyed(o)||isIndexed(s)!==isIndexed(o)||isOrdered(s)!==isOrdered(o))return!1;if(0===s.size&&0===o.size)return!0;var i=!isAssociative(s);if(isOrdered(s)){var a=s.entries();return o.every((function(s,o){var u=a.next().value;return u&&is(u[1],s)&&(i||is(u[0],o))}))&&a.next().done}var u=!1;if(void 0===s.size)if(void 0===o.size)"function"==typeof s.cacheResult&&s.cacheResult();else{u=!0;var _=s;s=o,o=_}var w=!0,x=o.__iterate((function(o,a){if(i?!s.has(o):u?!is(o,s.get(a,j)):!is(s.get(a,j),o))return w=!1,!1}));return w&&s.size===x}function Repeat(s,o){if(!(this instanceof Repeat))return new Repeat(s,o);if(this._value=s,this.size=void 0===o?1/0:Math.max(0,o),0===this.size){if(ie)return ie;ie=this}}function invariant(s,o){if(!s)throw new Error(o)}function Range(s,o,i){if(!(this instanceof Range))return new Range(s,o,i);if(invariant(0!==i,"Cannot step a Range by 0"),s=s||0,void 0===o&&(o=1/0),i=void 0===i?1:Math.abs(i),oa?iteratorDone():iteratorValue(s,u,i[o?a-u++:u++])}))},createClass(ObjectSeq,KeyedSeq),ObjectSeq.prototype.get=function(s,o){return void 0===o||this.has(s)?this._object[s]:o},ObjectSeq.prototype.has=function(s){return this._object.hasOwnProperty(s)},ObjectSeq.prototype.__iterate=function(s,o){for(var i=this._object,a=this._keys,u=a.length-1,_=0;_<=u;_++){var w=a[o?u-_:_];if(!1===s(i[w],w,this))return _+1}return _},ObjectSeq.prototype.__iterator=function(s,o){var i=this._object,a=this._keys,u=a.length-1,_=0;return new Iterator((function(){var w=a[o?u-_:_];return _++>u?iteratorDone():iteratorValue(s,w,i[w])}))},ObjectSeq.prototype[u]=!0,createClass(IterableSeq,IndexedSeq),IterableSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);var i=getIterator(this._iterable),a=0;if(isIterator(i))for(var u;!(u=i.next()).done&&!1!==s(u.value,a++,this););return a},IterableSeq.prototype.__iteratorUncached=function(s,o){if(o)return this.cacheResult().__iterator(s,o);var i=getIterator(this._iterable);if(!isIterator(i))return new Iterator(iteratorDone);var a=0;return new Iterator((function(){var o=i.next();return o.done?o:iteratorValue(s,a++,o.value)}))},createClass(IteratorSeq,IndexedSeq),IteratorSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);for(var i,a=this._iterator,u=this._iteratorCache,_=0;_=a.length){var o=i.next();if(o.done)return o;a[u]=o.value}return iteratorValue(s,u,a[u++])}))},createClass(Repeat,IndexedSeq),Repeat.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Repeat.prototype.get=function(s,o){return this.has(s)?this._value:o},Repeat.prototype.includes=function(s){return is(this._value,s)},Repeat.prototype.slice=function(s,o){var i=this.size;return wholeSlice(s,o,i)?this:new Repeat(this._value,resolveEnd(o,i)-resolveBegin(s,i))},Repeat.prototype.reverse=function(){return this},Repeat.prototype.indexOf=function(s){return is(this._value,s)?0:-1},Repeat.prototype.lastIndexOf=function(s){return is(this._value,s)?this.size:-1},Repeat.prototype.__iterate=function(s,o){for(var i=0;i=0&&o=0&&ii?iteratorDone():iteratorValue(s,_++,w)}))},Range.prototype.equals=function(s){return s instanceof Range?this._start===s._start&&this._end===s._end&&this._step===s._step:deepEqual(this,s)},createClass(Collection,Iterable),createClass(KeyedCollection,Collection),createClass(IndexedCollection,Collection),createClass(SetCollection,Collection),Collection.Keyed=KeyedCollection,Collection.Indexed=IndexedCollection,Collection.Set=SetCollection;var le="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function imul(s,o){var i=65535&(s|=0),a=65535&(o|=0);return i*a+((s>>>16)*a+i*(o>>>16)<<16>>>0)|0};function smi(s){return s>>>1&1073741824|3221225471&s}function hash(s){if(!1===s||null==s)return 0;if("function"==typeof s.valueOf&&(!1===(s=s.valueOf())||null==s))return 0;if(!0===s)return 1;var o=typeof s;if("number"===o){if(s!=s||s===1/0)return 0;var i=0|s;for(i!==s&&(i^=4294967295*s);s>4294967295;)i^=s/=4294967295;return smi(i)}if("string"===o)return s.length>_e?cachedHashString(s):hashString(s);if("function"==typeof s.hashCode)return s.hashCode();if("object"===o)return hashJSObj(s);if("function"==typeof s.toString)return hashString(s.toString());throw new Error("Value type "+o+" cannot be hashed.")}function cachedHashString(s){var o=Pe[s];return void 0===o&&(o=hashString(s),xe===we&&(xe=0,Pe={}),xe++,Pe[s]=o),o}function hashString(s){for(var o=0,i=0;i0)switch(s.nodeType){case 1:return s.uniqueID;case 9:return s.documentElement&&s.documentElement.uniqueID}}var fe,ye="function"==typeof WeakMap;ye&&(fe=new WeakMap);var be=0,Se="__immutablehash__";"function"==typeof Symbol&&(Se=Symbol(Se));var _e=16,we=255,xe=0,Pe={};function assertNotInfinite(s){invariant(s!==1/0,"Cannot perform this action with an infinite size.")}function Map(s){return null==s?emptyMap():isMap(s)&&!isOrdered(s)?s:emptyMap().withMutations((function(o){var i=KeyedIterable(s);assertNotInfinite(i.size),i.forEach((function(s,i){return o.set(i,s)}))}))}function isMap(s){return!(!s||!s[Re])}createClass(Map,KeyedCollection),Map.of=function(){var o=s.call(arguments,0);return emptyMap().withMutations((function(s){for(var i=0;i=o.length)throw new Error("Missing value for key: "+o[i]);s.set(o[i],o[i+1])}}))},Map.prototype.toString=function(){return this.__toString("Map {","}")},Map.prototype.get=function(s,o){return this._root?this._root.get(0,void 0,s,o):o},Map.prototype.set=function(s,o){return updateMap(this,s,o)},Map.prototype.setIn=function(s,o){return this.updateIn(s,j,(function(){return o}))},Map.prototype.remove=function(s){return updateMap(this,s,j)},Map.prototype.deleteIn=function(s){return this.updateIn(s,(function(){return j}))},Map.prototype.update=function(s,o,i){return 1===arguments.length?s(this):this.updateIn([s],o,i)},Map.prototype.updateIn=function(s,o,i){i||(i=o,o=void 0);var a=updateInDeepMap(this,forceIterator(s),o,i);return a===j?void 0:a},Map.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()},Map.prototype.merge=function(){return mergeIntoMapWith(this,void 0,arguments)},Map.prototype.mergeWith=function(o){return mergeIntoMapWith(this,o,s.call(arguments,1))},Map.prototype.mergeIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.merge?s.merge.apply(s,i):i[i.length-1]}))},Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger,arguments)},Map.prototype.mergeDeepWith=function(o){var i=s.call(arguments,1);return mergeIntoMapWith(this,deepMergerWith(o),i)},Map.prototype.mergeDeepIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.mergeDeep?s.mergeDeep.apply(s,i):i[i.length-1]}))},Map.prototype.sort=function(s){return OrderedMap(sortFactory(this,s))},Map.prototype.sortBy=function(s,o){return OrderedMap(sortFactory(this,o,s))},Map.prototype.withMutations=function(s){var o=this.asMutable();return s(o),o.wasAltered()?o.__ensureOwner(this.__ownerID):this},Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)},Map.prototype.asImmutable=function(){return this.__ensureOwner()},Map.prototype.wasAltered=function(){return this.__altered},Map.prototype.__iterator=function(s,o){return new MapIterator(this,s,o)},Map.prototype.__iterate=function(s,o){var i=this,a=0;return this._root&&this._root.iterate((function(o){return a++,s(o[1],o[0],i)}),o),a},Map.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeMap(this.size,this._root,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Map.isMap=isMap;var Te,Re="@@__IMMUTABLE_MAP__@@",$e=Map.prototype;function ArrayMapNode(s,o){this.ownerID=s,this.entries=o}function BitmapIndexedNode(s,o,i){this.ownerID=s,this.bitmap=o,this.nodes=i}function HashArrayMapNode(s,o,i){this.ownerID=s,this.count=o,this.nodes=i}function HashCollisionNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entries=i}function ValueNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entry=i}function MapIterator(s,o,i){this._type=o,this._reverse=i,this._stack=s._root&&mapIteratorFrame(s._root)}function mapIteratorValue(s,o){return iteratorValue(s,o[0],o[1])}function mapIteratorFrame(s,o){return{node:s,index:0,__prev:o}}function makeMap(s,o,i,a){var u=Object.create($e);return u.size=s,u._root=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyMap(){return Te||(Te=makeMap(0))}function updateMap(s,o,i){var a,u;if(s._root){var _=MakeRef(L),w=MakeRef(B);if(a=updateNode(s._root,s.__ownerID,0,void 0,o,i,_,w),!w.value)return s;u=s.size+(_.value?i===j?-1:1:0)}else{if(i===j)return s;u=1,a=new ArrayMapNode(s.__ownerID,[[o,i]])}return s.__ownerID?(s.size=u,s._root=a,s.__hash=void 0,s.__altered=!0,s):a?makeMap(u,a):emptyMap()}function updateNode(s,o,i,a,u,_,w,x){return s?s.update(o,i,a,u,_,w,x):_===j?s:(SetRef(x),SetRef(w),new ValueNode(o,a,[u,_]))}function isLeafNode(s){return s.constructor===ValueNode||s.constructor===HashCollisionNode}function mergeIntoNode(s,o,i,a,u){if(s.keyHash===a)return new HashCollisionNode(o,a,[s.entry,u]);var _,x=(0===i?s.keyHash:s.keyHash>>>i)&C,j=(0===i?a:a>>>i)&C;return new BitmapIndexedNode(o,1<>>=1)w[C]=1&i?o[_++]:void 0;return w[a]=u,new HashArrayMapNode(s,_+1,w)}function mergeIntoMapWith(s,o,i){for(var a=[],u=0;u>1&1431655765))+(s>>2&858993459))+(s>>4)&252645135,s+=s>>8,127&(s+=s>>16)}function setIn(s,o,i,a){var u=a?s:arrCopy(s);return u[o]=i,u}function spliceIn(s,o,i,a){var u=s.length+1;if(a&&o+1===u)return s[o]=i,s;for(var _=new Array(u),w=0,x=0;x=qe)return createNodes(s,C,a,u);var U=s&&s===this.ownerID,V=U?C:arrCopy(C);return $?x?L===B-1?V.pop():V[L]=V.pop():V[L]=[a,u]:V.push([a,u]),U?(this.entries=V,this):new ArrayMapNode(s,V)}},BitmapIndexedNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=1<<((0===s?o:o>>>s)&C),_=this.bitmap;return _&u?this.nodes[popCount(_&u-1)].get(s+w,o,i,a):a},BitmapIndexedNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=1<=ze)return expandNodes(s,z,$,L,Z);if(U&&!Z&&2===z.length&&isLeafNode(z[1^V]))return z[1^V];if(U&&Z&&1===z.length&&isLeafNode(Z))return Z;var ee=s&&s===this.ownerID,ie=U?Z?$:$^B:$|B,ae=U?Z?setIn(z,V,Z,ee):spliceOut(z,V,ee):spliceIn(z,V,Z,ee);return ee?(this.bitmap=ie,this.nodes=ae,this):new BitmapIndexedNode(s,ie,ae)},HashArrayMapNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=(0===s?o:o>>>s)&C,_=this.nodes[u];return _?_.get(s+w,o,i,a):a},HashArrayMapNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=u===j,$=this.nodes,U=$[L];if(B&&!U)return this;var V=updateNode(U,s,o+w,i,a,u,_,x);if(V===U)return this;var z=this.count;if(U){if(!V&&--z0&&a=0&&s>>o&C;if(a>=this.array.length)return new VNode([],s);var u,_=0===a;if(o>0){var x=this.array[a];if((u=x&&x.removeBefore(s,o-w,i))===x&&_)return this}if(_&&!u)return this;var j=editableVNode(this,s);if(!_)for(var L=0;L>>o&C;if(u>=this.array.length)return this;if(o>0){var _=this.array[u];if((a=_&&_.removeAfter(s,o-w,i))===_&&u===this.array.length-1)return this}var x=editableVNode(this,s);return x.array.splice(u+1),a&&(x.array[u]=a),x};var Xe,Qe,et={};function iterateList(s,o){var i=s._origin,a=s._capacity,u=getTailOffset(a),_=s._tail;return iterateNodeOrLeaf(s._root,s._level,0);function iterateNodeOrLeaf(s,o,i){return 0===o?iterateLeaf(s,i):iterateNode(s,o,i)}function iterateLeaf(s,w){var C=w===u?_&&_.array:s&&s.array,j=w>i?0:i-w,L=a-w;return L>x&&(L=x),function(){if(j===L)return et;var s=o?--L:j++;return C&&C[s]}}function iterateNode(s,u,_){var C,j=s&&s.array,L=_>i?0:i-_>>u,B=1+(a-_>>u);return B>x&&(B=x),function(){for(;;){if(C){var s=C();if(s!==et)return s;C=null}if(L===B)return et;var i=o?--B:L++;C=iterateNodeOrLeaf(j&&j[i],u-w,_+(i<=s.size||o<0)return s.withMutations((function(s){o<0?setListBounds(s,o).set(0,i):setListBounds(s,0,o+1).set(o,i)}));o+=s._origin;var a=s._tail,u=s._root,_=MakeRef(B);return o>=getTailOffset(s._capacity)?a=updateVNode(a,s.__ownerID,0,o,i,_):u=updateVNode(u,s.__ownerID,s._level,o,i,_),_.value?s.__ownerID?(s._root=u,s._tail=a,s.__hash=void 0,s.__altered=!0,s):makeList(s._origin,s._capacity,s._level,u,a):s}function updateVNode(s,o,i,a,u,_){var x,j=a>>>i&C,L=s&&j0){var B=s&&s.array[j],$=updateVNode(B,o,i-w,a,u,_);return $===B?s:((x=editableVNode(s,o)).array[j]=$,x)}return L&&s.array[j]===u?s:(SetRef(_),x=editableVNode(s,o),void 0===u&&j===x.array.length-1?x.array.pop():x.array[j]=u,x)}function editableVNode(s,o){return o&&s&&o===s.ownerID?s:new VNode(s?s.array.slice():[],o)}function listNodeFor(s,o){if(o>=getTailOffset(s._capacity))return s._tail;if(o<1<0;)i=i.array[o>>>a&C],a-=w;return i}}function setListBounds(s,o,i){void 0!==o&&(o|=0),void 0!==i&&(i|=0);var a=s.__ownerID||new OwnerID,u=s._origin,_=s._capacity,x=u+o,j=void 0===i?_:i<0?_+i:u+i;if(x===u&&j===_)return s;if(x>=j)return s.clear();for(var L=s._level,B=s._root,$=0;x+$<0;)B=new VNode(B&&B.array.length?[void 0,B]:[],a),$+=1<<(L+=w);$&&(x+=$,u+=$,j+=$,_+=$);for(var U=getTailOffset(_),V=getTailOffset(j);V>=1<U?new VNode([],a):z;if(z&&V>U&&x<_&&z.array.length){for(var Z=B=editableVNode(B,a),ee=L;ee>w;ee-=w){var ie=U>>>ee&C;Z=Z.array[ie]=editableVNode(Z.array[ie],a)}Z.array[U>>>w&C]=z}if(j<_&&(Y=Y&&Y.removeAfter(a,0,j)),x>=V)x-=V,j-=V,L=w,B=null,Y=Y&&Y.removeBefore(a,0,x);else if(x>u||V>>L&C;if(ae!==V>>>L&C)break;ae&&($+=(1<u&&(B=B.removeBefore(a,L,x-$)),B&&Vu&&(u=x.size),isIterable(w)||(x=x.map((function(s){return fromJS(s)}))),a.push(x)}return u>s.size&&(s=s.setSize(u)),mergeIntoCollectionWith(s,o,a)}function getTailOffset(s){return s>>w<=x&&w.size>=2*_.size?(a=(u=w.filter((function(s,o){return void 0!==s&&C!==o}))).toKeyedSeq().map((function(s){return s[0]})).flip().toMap(),s.__ownerID&&(a.__ownerID=u.__ownerID=s.__ownerID)):(a=_.remove(o),u=C===w.size-1?w.pop():w.set(C,void 0))}else if(L){if(i===w.get(C)[1])return s;a=_,u=w.set(C,[o,i])}else a=_.set(o,w.size),u=w.set(w.size,[o,i]);return s.__ownerID?(s.size=a.size,s._map=a,s._list=u,s.__hash=void 0,s):makeOrderedMap(a,u)}function ToKeyedSequence(s,o){this._iter=s,this._useKeys=o,this.size=s.size}function ToIndexedSequence(s){this._iter=s,this.size=s.size}function ToSetSequence(s){this._iter=s,this.size=s.size}function FromEntriesSequence(s){this._iter=s,this.size=s.size}function flipFactory(s){var o=makeSequence(s);return o._iter=s,o.size=s.size,o.flip=function(){return s},o.reverse=function(){var o=s.reverse.apply(this);return o.flip=function(){return s.reverse()},o},o.has=function(o){return s.includes(o)},o.includes=function(o){return s.has(o)},o.cacheResult=cacheResultThrough,o.__iterateUncached=function(o,i){var a=this;return s.__iterate((function(s,i){return!1!==o(i,s,a)}),i)},o.__iteratorUncached=function(o,i){if(o===V){var a=s.__iterator(o,i);return new Iterator((function(){var s=a.next();if(!s.done){var o=s.value[0];s.value[0]=s.value[1],s.value[1]=o}return s}))}return s.__iterator(o===U?$:U,i)},o}function mapFactory(s,o,i){var a=makeSequence(s);return a.size=s.size,a.has=function(o){return s.has(o)},a.get=function(a,u){var _=s.get(a,j);return _===j?u:o.call(i,_,a,s)},a.__iterateUncached=function(a,u){var _=this;return s.__iterate((function(s,u,w){return!1!==a(o.call(i,s,u,w),u,_)}),u)},a.__iteratorUncached=function(a,u){var _=s.__iterator(V,u);return new Iterator((function(){var u=_.next();if(u.done)return u;var w=u.value,x=w[0];return iteratorValue(a,x,o.call(i,w[1],x,s),u)}))},a}function reverseFactory(s,o){var i=makeSequence(s);return i._iter=s,i.size=s.size,i.reverse=function(){return s},s.flip&&(i.flip=function(){var o=flipFactory(s);return o.reverse=function(){return s.flip()},o}),i.get=function(i,a){return s.get(o?i:-1-i,a)},i.has=function(i){return s.has(o?i:-1-i)},i.includes=function(o){return s.includes(o)},i.cacheResult=cacheResultThrough,i.__iterate=function(o,i){var a=this;return s.__iterate((function(s,i){return o(s,i,a)}),!i)},i.__iterator=function(o,i){return s.__iterator(o,!i)},i}function filterFactory(s,o,i,a){var u=makeSequence(s);return a&&(u.has=function(a){var u=s.get(a,j);return u!==j&&!!o.call(i,u,a,s)},u.get=function(a,u){var _=s.get(a,j);return _!==j&&o.call(i,_,a,s)?_:u}),u.__iterateUncached=function(u,_){var w=this,x=0;return s.__iterate((function(s,_,C){if(o.call(i,s,_,C))return x++,u(s,a?_:x-1,w)}),_),x},u.__iteratorUncached=function(u,_){var w=s.__iterator(V,_),x=0;return new Iterator((function(){for(;;){var _=w.next();if(_.done)return _;var C=_.value,j=C[0],L=C[1];if(o.call(i,L,j,s))return iteratorValue(u,a?j:x++,L,_)}}))},u}function countByFactory(s,o,i){var a=Map().asMutable();return s.__iterate((function(u,_){a.update(o.call(i,u,_,s),0,(function(s){return s+1}))})),a.asImmutable()}function groupByFactory(s,o,i){var a=isKeyed(s),u=(isOrdered(s)?OrderedMap():Map()).asMutable();s.__iterate((function(_,w){u.update(o.call(i,_,w,s),(function(s){return(s=s||[]).push(a?[w,_]:_),s}))}));var _=iterableClass(s);return u.map((function(o){return reify(s,_(o))}))}function sliceFactory(s,o,i,a){var u=s.size;if(void 0!==o&&(o|=0),void 0!==i&&(i===1/0?i=u:i|=0),wholeSlice(o,i,u))return s;var _=resolveBegin(o,u),w=resolveEnd(i,u);if(_!=_||w!=w)return sliceFactory(s.toSeq().cacheResult(),o,i,a);var x,C=w-_;C==C&&(x=C<0?0:C);var j=makeSequence(s);return j.size=0===x?x:s.size&&x||void 0,!a&&isSeq(s)&&x>=0&&(j.get=function(o,i){return(o=wrapIndex(this,o))>=0&&ox)return iteratorDone();var s=u.next();return a||o===U?s:iteratorValue(o,C-1,o===$?void 0:s.value[1],s)}))},j}function takeWhileFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterate(a,u);var w=0;return s.__iterate((function(s,u,x){return o.call(i,s,u,x)&&++w&&a(s,u,_)})),w},a.__iteratorUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterator(a,u);var w=s.__iterator(V,u),x=!0;return new Iterator((function(){if(!x)return iteratorDone();var s=w.next();if(s.done)return s;var u=s.value,C=u[0],j=u[1];return o.call(i,j,C,_)?a===V?s:iteratorValue(a,C,j,s):(x=!1,iteratorDone())}))},a}function skipWhileFactory(s,o,i,a){var u=makeSequence(s);return u.__iterateUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterate(u,_);var x=!0,C=0;return s.__iterate((function(s,_,j){if(!x||!(x=o.call(i,s,_,j)))return C++,u(s,a?_:C-1,w)})),C},u.__iteratorUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterator(u,_);var x=s.__iterator(V,_),C=!0,j=0;return new Iterator((function(){var s,_,L;do{if((s=x.next()).done)return a||u===U?s:iteratorValue(u,j++,u===$?void 0:s.value[1],s);var B=s.value;_=B[0],L=B[1],C&&(C=o.call(i,L,_,w))}while(C);return u===V?s:iteratorValue(u,_,L,s)}))},u}function concatFactory(s,o){var i=isKeyed(s),a=[s].concat(o).map((function(s){return isIterable(s)?i&&(s=KeyedIterable(s)):s=i?keyedSeqFromValue(s):indexedSeqFromValue(Array.isArray(s)?s:[s]),s})).filter((function(s){return 0!==s.size}));if(0===a.length)return s;if(1===a.length){var u=a[0];if(u===s||i&&isKeyed(u)||isIndexed(s)&&isIndexed(u))return u}var _=new ArraySeq(a);return i?_=_.toKeyedSeq():isIndexed(s)||(_=_.toSetSeq()),(_=_.flatten(!0)).size=a.reduce((function(s,o){if(void 0!==s){var i=o.size;if(void 0!==i)return s+i}}),0),_}function flattenFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=0,w=!1;function flatDeep(s,x){var C=this;s.__iterate((function(s,u){return(!o||x0}function zipWithFactory(s,o,i){var a=makeSequence(s);return a.size=new ArraySeq(i).map((function(s){return s.size})).min(),a.__iterate=function(s,o){for(var i,a=this.__iterator(U,o),u=0;!(i=a.next()).done&&!1!==s(i.value,u++,this););return u},a.__iteratorUncached=function(s,a){var u=i.map((function(s){return s=Iterable(s),getIterator(a?s.reverse():s)})),_=0,w=!1;return new Iterator((function(){var i;return w||(i=u.map((function(s){return s.next()})),w=i.some((function(s){return s.done}))),w?iteratorDone():iteratorValue(s,_++,o.apply(null,i.map((function(s){return s.value}))))}))},a}function reify(s,o){return isSeq(s)?o:s.constructor(o)}function validateEntry(s){if(s!==Object(s))throw new TypeError("Expected [K, V] tuple: "+s)}function resolveSize(s){return assertNotInfinite(s.size),ensureSize(s)}function iterableClass(s){return isKeyed(s)?KeyedIterable:isIndexed(s)?IndexedIterable:SetIterable}function makeSequence(s){return Object.create((isKeyed(s)?KeyedSeq:isIndexed(s)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Seq.prototype.cacheResult.call(this)}function defaultComparator(s,o){return s>o?1:s=0;i--)o={value:arguments[i],next:o};return this.__ownerID?(this.size=s,this._head=o,this.__hash=void 0,this.__altered=!0,this):makeStack(s,o)},Stack.prototype.pushAll=function(s){if(0===(s=IndexedIterable(s)).size)return this;assertNotInfinite(s.size);var o=this.size,i=this._head;return s.reverse().forEach((function(s){o++,i={value:s,next:i}})),this.__ownerID?(this.size=o,this._head=i,this.__hash=void 0,this.__altered=!0,this):makeStack(o,i)},Stack.prototype.pop=function(){return this.slice(1)},Stack.prototype.unshift=function(){return this.push.apply(this,arguments)},Stack.prototype.unshiftAll=function(s){return this.pushAll(s)},Stack.prototype.shift=function(){return this.pop.apply(this,arguments)},Stack.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()},Stack.prototype.slice=function(s,o){if(wholeSlice(s,o,this.size))return this;var i=resolveBegin(s,this.size);if(resolveEnd(o,this.size)!==this.size)return IndexedCollection.prototype.slice.call(this,s,o);for(var a=this.size-i,u=this._head;i--;)u=u.next;return this.__ownerID?(this.size=a,this._head=u,this.__hash=void 0,this.__altered=!0,this):makeStack(a,u)},Stack.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeStack(this.size,this._head,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Stack.prototype.__iterate=function(s,o){if(o)return this.reverse().__iterate(s);for(var i=0,a=this._head;a&&!1!==s(a.value,i++,this);)a=a.next;return i},Stack.prototype.__iterator=function(s,o){if(o)return this.reverse().__iterator(s);var i=0,a=this._head;return new Iterator((function(){if(a){var o=a.value;return a=a.next,iteratorValue(s,i++,o)}return iteratorDone()}))},Stack.isStack=isStack;var at,ct="@@__IMMUTABLE_STACK__@@",lt=Stack.prototype;function makeStack(s,o,i,a){var u=Object.create(lt);return u.size=s,u._head=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyStack(){return at||(at=makeStack(0))}function mixin(s,o){var keyCopier=function(i){s.prototype[i]=o[i]};return Object.keys(o).forEach(keyCopier),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(o).forEach(keyCopier),s}function isProtoKey(s){return"string"==typeof s&&("__proto__"===s||"constructor"===s)}lt[ct]=!0,lt.withMutations=$e.withMutations,lt.asMutable=$e.asMutable,lt.asImmutable=$e.asImmutable,lt.wasAltered=$e.wasAltered,Iterable.Iterator=Iterator,mixin(Iterable,{toArray:function(){assertNotInfinite(this.size);var s=new Array(this.size||0);return this.valueSeq().__iterate((function(o,i){s[i]=o})),s},toIndexedSeq:function(){return new ToIndexedSequence(this)},toJS:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJS?s.toJS():s})).__toJS()},toJSON:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJSON?s.toJSON():s})).__toJS()},toKeyedSeq:function(){return new ToKeyedSequence(this,!0)},toMap:function(){return Map(this.toKeyedSeq())},toObject:function(){assertNotInfinite(this.size);var s={};return this.__iterate((function(o,i){isProtoKey(i)||(s[i]=o)})),s},toOrderedMap:function(){return OrderedMap(this.toKeyedSeq())},toOrderedSet:function(){return OrderedSet(isKeyed(this)?this.valueSeq():this)},toSet:function(){return Set(isKeyed(this)?this.valueSeq():this)},toSetSeq:function(){return new ToSetSequence(this)},toSeq:function(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Stack(isKeyed(this)?this.valueSeq():this)},toList:function(){return List(isKeyed(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(s,o){return 0===this.size?s+o:s+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+o},concat:function(){return reify(this,concatFactory(this,s.call(arguments,0)))},includes:function(s){return this.some((function(o){return is(o,s)}))},entries:function(){return this.__iterator(V)},every:function(s,o){assertNotInfinite(this.size);var i=!0;return this.__iterate((function(a,u,_){if(!s.call(o,a,u,_))return i=!1,!1})),i},filter:function(s,o){return reify(this,filterFactory(this,s,o,!0))},find:function(s,o,i){var a=this.findEntry(s,o);return a?a[1]:i},forEach:function(s,o){return assertNotInfinite(this.size),this.__iterate(o?s.bind(o):s)},join:function(s){assertNotInfinite(this.size),s=void 0!==s?""+s:",";var o="",i=!0;return this.__iterate((function(a){i?i=!1:o+=s,o+=null!=a?a.toString():""})),o},keys:function(){return this.__iterator($)},map:function(s,o){return reify(this,mapFactory(this,s,o))},reduce:function(s,o,i){var a,u;return assertNotInfinite(this.size),arguments.length<2?u=!0:a=o,this.__iterate((function(o,_,w){u?(u=!1,a=o):a=s.call(i,a,o,_,w)})),a},reduceRight:function(s,o,i){var a=this.toKeyedSeq().reverse();return a.reduce.apply(a,arguments)},reverse:function(){return reify(this,reverseFactory(this,!0))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!0))},some:function(s,o){return!this.every(not(s),o)},sort:function(s){return reify(this,sortFactory(this,s))},values:function(){return this.__iterator(U)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(s,o){return ensureSize(s?this.toSeq().filter(s,o):this)},countBy:function(s,o){return countByFactory(this,s,o)},equals:function(s){return deepEqual(this,s)},entrySeq:function(){var s=this;if(s._cache)return new ArraySeq(s._cache);var o=s.toSeq().map(entryMapper).toIndexedSeq();return o.fromEntrySeq=function(){return s.toSeq()},o},filterNot:function(s,o){return this.filter(not(s),o)},findEntry:function(s,o,i){var a=i;return this.__iterate((function(i,u,_){if(s.call(o,i,u,_))return a=[u,i],!1})),a},findKey:function(s,o){var i=this.findEntry(s,o);return i&&i[0]},findLast:function(s,o,i){return this.toKeyedSeq().reverse().find(s,o,i)},findLastEntry:function(s,o,i){return this.toKeyedSeq().reverse().findEntry(s,o,i)},findLastKey:function(s,o){return this.toKeyedSeq().reverse().findKey(s,o)},first:function(){return this.find(returnTrue)},flatMap:function(s,o){return reify(this,flatMapFactory(this,s,o))},flatten:function(s){return reify(this,flattenFactory(this,s,!0))},fromEntrySeq:function(){return new FromEntriesSequence(this)},get:function(s,o){return this.find((function(o,i){return is(i,s)}),void 0,o)},getIn:function(s,o){for(var i,a=this,u=forceIterator(s);!(i=u.next()).done;){var _=i.value;if((a=a&&a.get?a.get(_,j):j)===j)return o}return a},groupBy:function(s,o){return groupByFactory(this,s,o)},has:function(s){return this.get(s,j)!==j},hasIn:function(s){return this.getIn(s,j)!==j},isSubset:function(s){return s="function"==typeof s.includes?s:Iterable(s),this.every((function(o){return s.includes(o)}))},isSuperset:function(s){return(s="function"==typeof s.isSubset?s:Iterable(s)).isSubset(this)},keyOf:function(s){return this.findKey((function(o){return is(o,s)}))},keySeq:function(){return this.toSeq().map(keyMapper).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(s){return this.toKeyedSeq().reverse().keyOf(s)},max:function(s){return maxFactory(this,s)},maxBy:function(s,o){return maxFactory(this,o,s)},min:function(s){return maxFactory(this,s?neg(s):defaultNegComparator)},minBy:function(s,o){return maxFactory(this,o?neg(o):defaultNegComparator,s)},rest:function(){return this.slice(1)},skip:function(s){return this.slice(Math.max(0,s))},skipLast:function(s){return reify(this,this.toSeq().reverse().skip(s).reverse())},skipWhile:function(s,o){return reify(this,skipWhileFactory(this,s,o,!0))},skipUntil:function(s,o){return this.skipWhile(not(s),o)},sortBy:function(s,o){return reify(this,sortFactory(this,o,s))},take:function(s){return this.slice(0,Math.max(0,s))},takeLast:function(s){return reify(this,this.toSeq().reverse().take(s).reverse())},takeWhile:function(s,o){return reify(this,takeWhileFactory(this,s,o))},takeUntil:function(s,o){return this.takeWhile(not(s),o)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=hashIterable(this))}});var ut=Iterable.prototype;ut[o]=!0,ut[Z]=ut.values,ut.__toJS=ut.toArray,ut.__toStringMapper=quoteString,ut.inspect=ut.toSource=function(){return this.toString()},ut.chain=ut.flatMap,ut.contains=ut.includes,mixin(KeyedIterable,{flip:function(){return reify(this,flipFactory(this))},mapEntries:function(s,o){var i=this,a=0;return reify(this,this.toSeq().map((function(u,_){return s.call(o,[_,u],a++,i)})).fromEntrySeq())},mapKeys:function(s,o){var i=this;return reify(this,this.toSeq().flip().map((function(a,u){return s.call(o,a,u,i)})).flip())}});var pt=KeyedIterable.prototype;function keyMapper(s,o){return o}function entryMapper(s,o){return[o,s]}function not(s){return function(){return!s.apply(this,arguments)}}function neg(s){return function(){return-s.apply(this,arguments)}}function quoteString(s){return"string"==typeof s?JSON.stringify(s):String(s)}function defaultZipper(){return arrCopy(arguments)}function defaultNegComparator(s,o){return so?-1:0}function hashIterable(s){if(s.size===1/0)return 0;var o=isOrdered(s),i=isKeyed(s),a=o?1:0;return murmurHashOfSize(s.__iterate(i?o?function(s,o){a=31*a+hashMerge(hash(s),hash(o))|0}:function(s,o){a=a+hashMerge(hash(s),hash(o))|0}:o?function(s){a=31*a+hash(s)|0}:function(s){a=a+hash(s)|0}),a)}function murmurHashOfSize(s,o){return o=le(o,3432918353),o=le(o<<15|o>>>-15,461845907),o=le(o<<13|o>>>-13,5),o=le((o=o+3864292196^s)^o>>>16,2246822507),o=smi((o=le(o^o>>>13,3266489909))^o>>>16)}function hashMerge(s,o){return s^o+2654435769+(s<<6)+(s>>2)}return pt[i]=!0,pt[Z]=ut.entries,pt.__toJS=ut.toObject,pt.__toStringMapper=function(s,o){return JSON.stringify(o)+": "+quoteString(s)},mixin(IndexedIterable,{toKeyedSeq:function(){return new ToKeyedSequence(this,!1)},filter:function(s,o){return reify(this,filterFactory(this,s,o,!1))},findIndex:function(s,o){var i=this.findEntry(s,o);return i?i[0]:-1},indexOf:function(s){var o=this.keyOf(s);return void 0===o?-1:o},lastIndexOf:function(s){var o=this.lastKeyOf(s);return void 0===o?-1:o},reverse:function(){return reify(this,reverseFactory(this,!1))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!1))},splice:function(s,o){var i=arguments.length;if(o=Math.max(0|o,0),0===i||2===i&&!o)return this;s=resolveBegin(s,s<0?this.count():this.size);var a=this.slice(0,s);return reify(this,1===i?a:a.concat(arrCopy(arguments,2),this.slice(s+o)))},findLastIndex:function(s,o){var i=this.findLastEntry(s,o);return i?i[0]:-1},first:function(){return this.get(0)},flatten:function(s){return reify(this,flattenFactory(this,s,!1))},get:function(s,o){return(s=wrapIndex(this,s))<0||this.size===1/0||void 0!==this.size&&s>this.size?o:this.find((function(o,i){return i===s}),void 0,o)},has:function(s){return(s=wrapIndex(this,s))>=0&&(void 0!==this.size?this.size===1/0||s=o||i<0||B&&s-j>=_}function timerExpired(){var s=now();if(shouldInvoke(s))return trailingEdge(s);x=setTimeout(timerExpired,function remainingWait(s){var i=o-(s-C);return B?U(i,_-(s-j)):i}(s))}function trailingEdge(s){return x=void 0,V&&a?invokeFunc(s):(a=u=void 0,w)}function debounced(){var s=now(),i=shouldInvoke(s);if(a=arguments,u=this,C=s,i){if(void 0===x)return function leadingEdge(s){return j=s,x=setTimeout(timerExpired,o),L?invokeFunc(s):w}(C);if(B)return x=setTimeout(timerExpired,o),invokeFunc(C)}return void 0===x&&(x=setTimeout(timerExpired,o)),w}return o=toNumber(o)||0,isObject(i)&&(L=!!i.leading,_=(B="maxWait"in i)?$(toNumber(i.maxWait)||0,o):_,V="trailing"in i?!!i.trailing:V),debounced.cancel=function cancel(){void 0!==x&&clearTimeout(x),j=0,a=C=u=x=void 0},debounced.flush=function flush(){return void 0===x?w:trailingEdge(now())},debounced}},55580(s,o,i){var a=i(56110)(i(9325),"DataView");s.exports=a},21549(s,o,i){var a=i(22032),u=i(63862),_=i(66721),w=i(12749),x=i(35749);function Hash(s){var o=-1,i=null==s?0:s.length;for(this.clear();++o-1}},70695(s,o,i){var a=i(78096),u=i(72428),_=i(56449),w=i(3656),x=i(30361),C=i(37167),j=Object.prototype.hasOwnProperty;s.exports=function arrayLikeKeys(s,o){var i=_(s),L=!i&&u(s),B=!i&&!L&&w(s),$=!i&&!L&&!B&&C(s),U=i||L||B||$,V=U?a(s.length,String):[],z=V.length;for(var Y in s)!o&&!j.call(s,Y)||U&&("length"==Y||B&&("offset"==Y||"parent"==Y)||$&&("buffer"==Y||"byteLength"==Y||"byteOffset"==Y)||x(Y,z))||V.push(Y);return V}},34932(s){s.exports=function arrayMap(s,o){for(var i=-1,a=null==s?0:s.length,u=Array(a);++i0&&i(j)?o>1?baseFlatten(j,o-1,i,_,w):a(w,j):_||(w[w.length]=j)}return w}},86649(s,o,i){var a=i(83221)();s.exports=a},30641(s,o,i){var a=i(86649),u=i(95950);s.exports=function baseForOwn(s,o){return s&&a(s,o,u)}},47422(s,o,i){var a=i(31769),u=i(77797);s.exports=function baseGet(s,o){for(var i=0,_=(o=a(o,s)).length;null!=s&&i<_;)s=s[u(o[i++])];return i&&i==_?s:void 0}},82199(s,o,i){var a=i(14528),u=i(56449);s.exports=function baseGetAllKeys(s,o,i){var _=o(s);return u(s)?_:a(_,i(s))}},72552(s,o,i){var a=i(51873),u=i(659),_=i(59350),w=a?a.toStringTag:void 0;s.exports=function baseGetTag(s){return null==s?void 0===s?"[object Undefined]":"[object Null]":w&&w in Object(s)?u(s):_(s)}},20426(s){var o=Object.prototype.hasOwnProperty;s.exports=function baseHas(s,i){return null!=s&&o.call(s,i)}},28077(s){s.exports=function baseHasIn(s,o){return null!=s&&o in Object(s)}},96131(s,o,i){var a=i(2523),u=i(85463),_=i(76959);s.exports=function baseIndexOf(s,o,i){return o==o?_(s,o,i):a(s,u,i)}},27534(s,o,i){var a=i(72552),u=i(40346);s.exports=function baseIsArguments(s){return u(s)&&"[object Arguments]"==a(s)}},60270(s,o,i){var a=i(87068),u=i(40346);s.exports=function baseIsEqual(s,o,i,_,w){return s===o||(null==s||null==o||!u(s)&&!u(o)?s!=s&&o!=o:a(s,o,i,_,baseIsEqual,w))}},87068(s,o,i){var a=i(37217),u=i(25911),_=i(21986),w=i(50689),x=i(5861),C=i(56449),j=i(3656),L=i(37167),B="[object Arguments]",$="[object Array]",U="[object Object]",V=Object.prototype.hasOwnProperty;s.exports=function baseIsEqualDeep(s,o,i,z,Y,Z){var ee=C(s),ie=C(o),ae=ee?$:x(s),ce=ie?$:x(o),le=(ae=ae==B?U:ae)==U,pe=(ce=ce==B?U:ce)==U,de=ae==ce;if(de&&j(s)){if(!j(o))return!1;ee=!0,le=!1}if(de&&!le)return Z||(Z=new a),ee||L(s)?u(s,o,i,z,Y,Z):_(s,o,ae,i,z,Y,Z);if(!(1&i)){var fe=le&&V.call(s,"__wrapped__"),ye=pe&&V.call(o,"__wrapped__");if(fe||ye){var be=fe?s.value():s,Se=ye?o.value():o;return Z||(Z=new a),Y(be,Se,i,z,Z)}}return!!de&&(Z||(Z=new a),w(s,o,i,z,Y,Z))}},29172(s,o,i){var a=i(5861),u=i(40346);s.exports=function baseIsMap(s){return u(s)&&"[object Map]"==a(s)}},41799(s,o,i){var a=i(37217),u=i(60270);s.exports=function baseIsMatch(s,o,i,_){var w=i.length,x=w,C=!_;if(null==s)return!x;for(s=Object(s);w--;){var j=i[w];if(C&&j[2]?j[1]!==s[j[0]]:!(j[0]in s))return!1}for(;++wu?0:u+o),(i=i>u?u:i)<0&&(i+=u),u=o>i?0:i-o>>>0,o>>>=0;for(var _=Array(u);++a=u?s:a(s,o,i)}},49653(s,o,i){var a=i(37828);s.exports=function cloneArrayBuffer(s){var o=new s.constructor(s.byteLength);return new a(o).set(new a(s)),o}},93290(s,o,i){s=i.nmd(s);var a=i(9325),u=o&&!o.nodeType&&o,_=u&&s&&!s.nodeType&&s,w=_&&_.exports===u?a.Buffer:void 0,x=w?w.allocUnsafe:void 0;s.exports=function cloneBuffer(s,o){if(o)return s.slice();var i=s.length,a=x?x(i):new s.constructor(i);return s.copy(a),a}},76169(s,o,i){var a=i(49653);s.exports=function cloneDataView(s,o){var i=o?a(s.buffer):s.buffer;return new s.constructor(i,s.byteOffset,s.byteLength)}},73201(s){var o=/\w*$/;s.exports=function cloneRegExp(s){var i=new s.constructor(s.source,o.exec(s));return i.lastIndex=s.lastIndex,i}},93736(s,o,i){var a=i(51873),u=a?a.prototype:void 0,_=u?u.valueOf:void 0;s.exports=function cloneSymbol(s){return _?Object(_.call(s)):{}}},71961(s,o,i){var a=i(49653);s.exports=function cloneTypedArray(s,o){var i=o?a(s.buffer):s.buffer;return new s.constructor(i,s.byteOffset,s.length)}},91596(s){var o=Math.max;s.exports=function composeArgs(s,i,a,u){for(var _=-1,w=s.length,x=a.length,C=-1,j=i.length,L=o(w-x,0),B=Array(j+L),$=!u;++C1?i[_-1]:void 0,x=_>2?i[2]:void 0;for(w=s.length>3&&"function"==typeof w?(_--,w):void 0,x&&u(i[0],i[1],x)&&(w=_<3?void 0:w,_=1),o=Object(o);++a<_;){var C=i[a];C&&s(o,C,a,w)}return o}))}},38329(s,o,i){var a=i(64894);s.exports=function createBaseEach(s,o){return function(i,u){if(null==i)return i;if(!a(i))return s(i,u);for(var _=i.length,w=o?_:-1,x=Object(i);(o?w--:++w<_)&&!1!==u(x[w],w,x););return i}}},83221(s){s.exports=function createBaseFor(s){return function(o,i,a){for(var u=-1,_=Object(o),w=a(o),x=w.length;x--;){var C=w[s?x:++u];if(!1===i(_[C],C,_))break}return o}}},11842(s,o,i){var a=i(82819),u=i(9325);s.exports=function createBind(s,o,i){var _=1&o,w=a(s);return function wrapper(){return(this&&this!==u&&this instanceof wrapper?w:s).apply(_?i:this,arguments)}}},12507(s,o,i){var a=i(28754),u=i(49698),_=i(63912),w=i(13222);s.exports=function createCaseFirst(s){return function(o){o=w(o);var i=u(o)?_(o):void 0,x=i?i[0]:o.charAt(0),C=i?a(i,1).join(""):o.slice(1);return x[s]()+C}}},45539(s,o,i){var a=i(40882),u=i(50828),_=i(66645),w=RegExp("['’]","g");s.exports=function createCompounder(s){return function(o){return a(_(u(o).replace(w,"")),s,"")}}},82819(s,o,i){var a=i(39344),u=i(23805);s.exports=function createCtor(s){return function(){var o=arguments;switch(o.length){case 0:return new s;case 1:return new s(o[0]);case 2:return new s(o[0],o[1]);case 3:return new s(o[0],o[1],o[2]);case 4:return new s(o[0],o[1],o[2],o[3]);case 5:return new s(o[0],o[1],o[2],o[3],o[4]);case 6:return new s(o[0],o[1],o[2],o[3],o[4],o[5]);case 7:return new s(o[0],o[1],o[2],o[3],o[4],o[5],o[6])}var i=a(s.prototype),_=s.apply(i,o);return u(_)?_:i}}},77078(s,o,i){var a=i(91033),u=i(82819),_=i(37471),w=i(18073),x=i(11287),C=i(36306),j=i(9325);s.exports=function createCurry(s,o,i){var L=u(s);return function wrapper(){for(var u=arguments.length,B=Array(u),$=u,U=x(wrapper);$--;)B[$]=arguments[$];var V=u<3&&B[0]!==U&&B[u-1]!==U?[]:C(B,U);return(u-=V.length)-1?x[C?o[j]:j]:void 0}}},37471(s,o,i){var a=i(91596),u=i(53320),_=i(58523),w=i(82819),x=i(18073),C=i(11287),j=i(68294),L=i(36306),B=i(9325);s.exports=function createHybrid(s,o,i,$,U,V,z,Y,Z,ee){var ie=128&o,ae=1&o,ce=2&o,le=24&o,pe=512&o,de=ce?void 0:w(s);return function wrapper(){for(var fe=arguments.length,ye=Array(fe),be=fe;be--;)ye[be]=arguments[be];if(le)var Se=C(wrapper),_e=_(ye,Se);if($&&(ye=a(ye,$,U,le)),V&&(ye=u(ye,V,z,le)),fe-=_e,le&&fe1&&ye.reverse(),ie&&ZL))return!1;var $=C.get(s),U=C.get(o);if($&&U)return $==o&&U==s;var V=-1,z=!0,Y=2&i?new a:void 0;for(C.set(s,o),C.set(o,s);++V1?"& ":"")+i[u],i=i.join(a>2?", ":" "),s.replace(o,"{\n/* [wrapped with "+i+"] */\n")}},45891(s,o,i){var a=i(51873),u=i(72428),_=i(56449),w=a?a.isConcatSpreadable:void 0;s.exports=function isFlattenable(s){return _(s)||u(s)||!!(w&&s&&s[w])}},30361(s){var o=/^(?:0|[1-9]\d*)$/;s.exports=function isIndex(s,i){var a=typeof s;return!!(i=null==i?9007199254740991:i)&&("number"==a||"symbol"!=a&&o.test(s))&&s>-1&&s%1==0&&s-1}},31175(s,o,i){var a=i(26025);s.exports=function listCacheSet(s,o){var i=this.__data__,u=a(i,s);return u<0?(++this.size,i.push([s,o])):i[u][1]=o,this}},63040(s,o,i){var a=i(21549),u=i(80079),_=i(68223);s.exports=function mapCacheClear(){this.size=0,this.__data__={hash:new a,map:new(_||u),string:new a}}},17670(s,o,i){var a=i(12651);s.exports=function mapCacheDelete(s){var o=a(this,s).delete(s);return this.size-=o?1:0,o}},90289(s,o,i){var a=i(12651);s.exports=function mapCacheGet(s){return a(this,s).get(s)}},4509(s,o,i){var a=i(12651);s.exports=function mapCacheHas(s){return a(this,s).has(s)}},72949(s,o,i){var a=i(12651);s.exports=function mapCacheSet(s,o){var i=a(this,s),u=i.size;return i.set(s,o),this.size+=i.size==u?0:1,this}},20317(s){s.exports=function mapToArray(s){var o=-1,i=Array(s.size);return s.forEach((function(s,a){i[++o]=[a,s]})),i}},67197(s){s.exports=function matchesStrictComparable(s,o){return function(i){return null!=i&&(i[s]===o&&(void 0!==o||s in Object(i)))}}},62224(s,o,i){var a=i(50104);s.exports=function memoizeCapped(s){var o=a(s,(function(s){return 500===i.size&&i.clear(),s})),i=o.cache;return o}},3209(s,o,i){var a=i(91596),u=i(53320),_=i(36306),w="__lodash_placeholder__",x=128,C=Math.min;s.exports=function mergeData(s,o){var i=s[1],j=o[1],L=i|j,B=L<131,$=j==x&&8==i||j==x&&256==i&&s[7].length<=o[8]||384==j&&o[7].length<=o[8]&&8==i;if(!B&&!$)return s;1&j&&(s[2]=o[2],L|=1&i?0:4);var U=o[3];if(U){var V=s[3];s[3]=V?a(V,U,o[4]):U,s[4]=V?_(s[3],w):o[4]}return(U=o[5])&&(V=s[5],s[5]=V?u(V,U,o[6]):U,s[6]=V?_(s[5],w):o[6]),(U=o[7])&&(s[7]=U),j&x&&(s[8]=null==s[8]?o[8]:C(s[8],o[8])),null==s[9]&&(s[9]=o[9]),s[0]=o[0],s[1]=L,s}},48152(s,o,i){var a=i(28303),u=a&&new a;s.exports=u},81042(s,o,i){var a=i(56110)(Object,"create");s.exports=a},3650(s,o,i){var a=i(74335)(Object.keys,Object);s.exports=a},90181(s){s.exports=function nativeKeysIn(s){var o=[];if(null!=s)for(var i in Object(s))o.push(i);return o}},86009(s,o,i){s=i.nmd(s);var a=i(34840),u=o&&!o.nodeType&&o,_=u&&s&&!s.nodeType&&s,w=_&&_.exports===u&&a.process,x=function(){try{var s=_&&_.require&&_.require("util").types;return s||w&&w.binding&&w.binding("util")}catch(s){}}();s.exports=x},59350(s){var o=Object.prototype.toString;s.exports=function objectToString(s){return o.call(s)}},74335(s){s.exports=function overArg(s,o){return function(i){return s(o(i))}}},56757(s,o,i){var a=i(91033),u=Math.max;s.exports=function overRest(s,o,i){return o=u(void 0===o?s.length-1:o,0),function(){for(var _=arguments,w=-1,x=u(_.length-o,0),C=Array(x);++w0){if(++i>=800)return arguments[0]}else i=0;return s.apply(void 0,arguments)}}},51420(s,o,i){var a=i(80079);s.exports=function stackClear(){this.__data__=new a,this.size=0}},90938(s){s.exports=function stackDelete(s){var o=this.__data__,i=o.delete(s);return this.size=o.size,i}},63605(s){s.exports=function stackGet(s){return this.__data__.get(s)}},29817(s){s.exports=function stackHas(s){return this.__data__.has(s)}},80945(s,o,i){var a=i(80079),u=i(68223),_=i(53661);s.exports=function stackSet(s,o){var i=this.__data__;if(i instanceof a){var w=i.__data__;if(!u||w.length<199)return w.push([s,o]),this.size=++i.size,this;i=this.__data__=new _(w)}return i.set(s,o),this.size=i.size,this}},76959(s){s.exports=function strictIndexOf(s,o,i){for(var a=i-1,u=s.length;++a=o||i<0||Y&&s-V>=L}function timerExpired(){var s=u();if(shouldInvoke(s))return trailingEdge(s);$=setTimeout(timerExpired,function remainingWait(s){var i=o-(s-U);return Y?x(i,L-(s-V)):i}(s))}function trailingEdge(s){return $=void 0,Z&&C?invokeFunc(s):(C=j=void 0,B)}function debounced(){var s=u(),i=shouldInvoke(s);if(C=arguments,j=this,U=s,i){if(void 0===$)return function leadingEdge(s){return V=s,$=setTimeout(timerExpired,o),z?invokeFunc(s):B}(U);if(Y)return clearTimeout($),$=setTimeout(timerExpired,o),invokeFunc(U)}return void 0===$&&($=setTimeout(timerExpired,o)),B}return o=_(o)||0,a(i)&&(z=!!i.leading,L=(Y="maxWait"in i)?w(_(i.maxWait)||0,o):L,Z="trailing"in i?!!i.trailing:Z),debounced.cancel=function cancel(){void 0!==$&&clearTimeout($),V=0,C=U=j=$=void 0},debounced.flush=function flush(){return void 0===$?B:trailingEdge(u())},debounced}},50828(s,o,i){var a=i(24647),u=i(13222),_=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,w=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");s.exports=function deburr(s){return(s=u(s))&&s.replace(_,a).replace(w,"")}},75288(s){s.exports=function eq(s,o){return s===o||s!=s&&o!=o}},60680(s,o,i){var a=i(13222),u=/[\\^$.*+?()[\]{}|]/g,_=RegExp(u.source);s.exports=function escapeRegExp(s){return(s=a(s))&&_.test(s)?s.replace(u,"\\$&"):s}},7309(s,o,i){var a=i(62006)(i(24713));s.exports=a},24713(s,o,i){var a=i(2523),u=i(15389),_=i(61489),w=Math.max;s.exports=function findIndex(s,o,i){var x=null==s?0:s.length;if(!x)return-1;var C=null==i?0:_(i);return C<0&&(C=w(x+C,0)),a(s,u(o,3),C)}},35970(s,o,i){var a=i(83120);s.exports=function flatten(s){return(null==s?0:s.length)?a(s,1):[]}},73424(s,o,i){var a=i(16962),u=i(2874),_=Array.prototype.push;function baseAry(s,o){return 2==o?function(o,i){return s(o,i)}:function(o){return s(o)}}function cloneArray(s){for(var o=s?s.length:0,i=Array(o);o--;)i[o]=s[o];return i}function wrapImmutable(s,o){return function(){var i=arguments.length;if(i){for(var a=Array(i);i--;)a[i]=arguments[i];var u=a[0]=o.apply(void 0,a);return s.apply(void 0,a),u}}}s.exports=function baseConvert(s,o,i,w){var x="function"==typeof o,C=o===Object(o);if(C&&(w=i,i=o,o=void 0),null==i)throw new TypeError;w||(w={});var j=!("cap"in w)||w.cap,L=!("curry"in w)||w.curry,B=!("fixed"in w)||w.fixed,$=!("immutable"in w)||w.immutable,U=!("rearg"in w)||w.rearg,V=x?i:u,z="curry"in w&&w.curry,Y="fixed"in w&&w.fixed,Z="rearg"in w&&w.rearg,ee=x?i.runInContext():void 0,ie=x?i:{ary:s.ary,assign:s.assign,clone:s.clone,curry:s.curry,forEach:s.forEach,isArray:s.isArray,isError:s.isError,isFunction:s.isFunction,isWeakMap:s.isWeakMap,iteratee:s.iteratee,keys:s.keys,rearg:s.rearg,toInteger:s.toInteger,toPath:s.toPath},ae=ie.ary,ce=ie.assign,le=ie.clone,pe=ie.curry,de=ie.forEach,fe=ie.isArray,ye=ie.isError,be=ie.isFunction,Se=ie.isWeakMap,_e=ie.keys,we=ie.rearg,xe=ie.toInteger,Pe=ie.toPath,Te=_e(a.aryMethod),Re={castArray:function(s){return function(){var o=arguments[0];return fe(o)?s(cloneArray(o)):s.apply(void 0,arguments)}},iteratee:function(s){return function(){var o=arguments[1],i=s(arguments[0],o),a=i.length;return j&&"number"==typeof o?(o=o>2?o-2:1,a&&a<=o?i:baseAry(i,o)):i}},mixin:function(s){return function(o){var i=this;if(!be(i))return s(i,Object(o));var a=[];return de(_e(o),(function(s){be(o[s])&&a.push([s,i.prototype[s]])})),s(i,Object(o)),de(a,(function(s){var o=s[1];be(o)?i.prototype[s[0]]=o:delete i.prototype[s[0]]})),i}},nthArg:function(s){return function(o){var i=o<0?1:xe(o)+1;return pe(s(o),i)}},rearg:function(s){return function(o,i){var a=i?i.length:0;return pe(s(o,i),a)}},runInContext:function(o){return function(i){return baseConvert(s,o(i),w)}}};function castCap(s,o){if(j){var i=a.iterateeRearg[s];if(i)return function iterateeRearg(s,o){return overArg(s,(function(s){var i=o.length;return function baseArity(s,o){return 2==o?function(o,i){return s.apply(void 0,arguments)}:function(o){return s.apply(void 0,arguments)}}(we(baseAry(s,i),o),i)}))}(o,i);var u=!x&&a.iterateeAry[s];if(u)return function iterateeAry(s,o){return overArg(s,(function(s){return"function"==typeof s?baseAry(s,o):s}))}(o,u)}return o}function castFixed(s,o,i){if(B&&(Y||!a.skipFixed[s])){var u=a.methodSpread[s],w=u&&u.start;return void 0===w?ae(o,i):function flatSpread(s,o){return function(){for(var i=arguments.length,a=i-1,u=Array(i);i--;)u[i]=arguments[i];var w=u[o],x=u.slice(0,o);return w&&_.apply(x,w),o!=a&&_.apply(x,u.slice(o+1)),s.apply(this,x)}}(o,w)}return o}function castRearg(s,o,i){return U&&i>1&&(Z||!a.skipRearg[s])?we(o,a.methodRearg[s]||a.aryRearg[i]):o}function cloneByPath(s,o){for(var i=-1,a=(o=Pe(o)).length,u=a-1,_=le(Object(s)),w=_;null!=w&&++i1?pe(o,i):o}(0,u=castCap(_,u),s),!1}})),!u})),u||(u=w),u==o&&(u=z?pe(u,1):function(){return o.apply(this,arguments)}),u.convert=createConverter(_,o),u.placeholder=o.placeholder=i,u}if(!C)return wrap(o,i,V);var $e=i,qe=[];return de(Te,(function(s){de(a.aryMethod[s],(function(s){var o=$e[a.remap[s]||s];o&&qe.push([s,wrap(s,o,$e)])}))})),de(_e($e),(function(s){var o=$e[s];if("function"==typeof o){for(var i=qe.length;i--;)if(qe[i][0]==s)return;o.convert=createConverter(s,o),qe.push([s,o])}})),de(qe,(function(s){$e[s[0]]=s[1]})),$e.convert=function convertLib(s){return $e.runInContext.convert(s)(void 0)},$e.placeholder=$e,de(_e($e),(function(s){de(a.realToAlias[s]||[],(function(o){$e[o]=$e[s]}))})),$e}},16962(s,o){o.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},o.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},o.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},o.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},o.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},o.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},o.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},o.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},o.realToAlias=function(){var s=Object.prototype.hasOwnProperty,i=o.aliasToReal,a={};for(var u in i){var _=i[u];s.call(a,_)?a[_].push(u):a[_]=[u]}return a}(),o.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},o.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},o.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},47934(s,o,i){s.exports={ary:i(64626),assign:i(74733),clone:i(32629),curry:i(49747),forEach:i(83729),isArray:i(56449),isError:i(23546),isFunction:i(1882),isWeakMap:i(47886),iteratee:i(33855),keys:i(88984),rearg:i(84195),toInteger:i(61489),toPath:i(42072)}},56367(s,o,i){s.exports=i(77731)},79920(s,o,i){var a=i(73424),u=i(47934);s.exports=function convert(s,o,i){return a(u,s,o,i)}},2874(s){s.exports={}},77731(s,o,i){var a=i(79920)("set",i(63560));a.placeholder=i(2874),s.exports=a},58156(s,o,i){var a=i(47422);s.exports=function get(s,o,i){var u=null==s?void 0:a(s,o);return void 0===u?i:u}},61448(s,o,i){var a=i(20426),u=i(49326);s.exports=function has(s,o){return null!=s&&u(s,o,a)}},80631(s,o,i){var a=i(28077),u=i(49326);s.exports=function hasIn(s,o){return null!=s&&u(s,o,a)}},83488(s){s.exports=function identity(s){return s}},72428(s,o,i){var a=i(27534),u=i(40346),_=Object.prototype,w=_.hasOwnProperty,x=_.propertyIsEnumerable,C=a(function(){return arguments}())?a:function(s){return u(s)&&w.call(s,"callee")&&!x.call(s,"callee")};s.exports=C},56449(s){var o=Array.isArray;s.exports=o},64894(s,o,i){var a=i(1882),u=i(30294);s.exports=function isArrayLike(s){return null!=s&&u(s.length)&&!a(s)}},83693(s,o,i){var a=i(64894),u=i(40346);s.exports=function isArrayLikeObject(s){return u(s)&&a(s)}},53812(s,o,i){var a=i(72552),u=i(40346);s.exports=function isBoolean(s){return!0===s||!1===s||u(s)&&"[object Boolean]"==a(s)}},3656(s,o,i){s=i.nmd(s);var a=i(9325),u=i(89935),_=o&&!o.nodeType&&o,w=_&&s&&!s.nodeType&&s,x=w&&w.exports===_?a.Buffer:void 0,C=(x?x.isBuffer:void 0)||u;s.exports=C},62193(s,o,i){var a=i(88984),u=i(5861),_=i(72428),w=i(56449),x=i(64894),C=i(3656),j=i(55527),L=i(37167),B=Object.prototype.hasOwnProperty;s.exports=function isEmpty(s){if(null==s)return!0;if(x(s)&&(w(s)||"string"==typeof s||"function"==typeof s.splice||C(s)||L(s)||_(s)))return!s.length;var o=u(s);if("[object Map]"==o||"[object Set]"==o)return!s.size;if(j(s))return!a(s).length;for(var i in s)if(B.call(s,i))return!1;return!0}},2404(s,o,i){var a=i(60270);s.exports=function isEqual(s,o){return a(s,o)}},23546(s,o,i){var a=i(72552),u=i(40346),_=i(11331);s.exports=function isError(s){if(!u(s))return!1;var o=a(s);return"[object Error]"==o||"[object DOMException]"==o||"string"==typeof s.message&&"string"==typeof s.name&&!_(s)}},1882(s,o,i){var a=i(72552),u=i(23805);s.exports=function isFunction(s){if(!u(s))return!1;var o=a(s);return"[object Function]"==o||"[object GeneratorFunction]"==o||"[object AsyncFunction]"==o||"[object Proxy]"==o}},30294(s){s.exports=function isLength(s){return"number"==typeof s&&s>-1&&s%1==0&&s<=9007199254740991}},87730(s,o,i){var a=i(29172),u=i(27301),_=i(86009),w=_&&_.isMap,x=w?u(w):a;s.exports=x},5187(s){s.exports=function isNull(s){return null===s}},98023(s,o,i){var a=i(72552),u=i(40346);s.exports=function isNumber(s){return"number"==typeof s||u(s)&&"[object Number]"==a(s)}},23805(s){s.exports=function isObject(s){var o=typeof s;return null!=s&&("object"==o||"function"==o)}},40346(s){s.exports=function isObjectLike(s){return null!=s&&"object"==typeof s}},11331(s,o,i){var a=i(72552),u=i(28879),_=i(40346),w=Function.prototype,x=Object.prototype,C=w.toString,j=x.hasOwnProperty,L=C.call(Object);s.exports=function isPlainObject(s){if(!_(s)||"[object Object]"!=a(s))return!1;var o=u(s);if(null===o)return!0;var i=j.call(o,"constructor")&&o.constructor;return"function"==typeof i&&i instanceof i&&C.call(i)==L}},38440(s,o,i){var a=i(16038),u=i(27301),_=i(86009),w=_&&_.isSet,x=w?u(w):a;s.exports=x},85015(s,o,i){var a=i(72552),u=i(56449),_=i(40346);s.exports=function isString(s){return"string"==typeof s||!u(s)&&_(s)&&"[object String]"==a(s)}},44394(s,o,i){var a=i(72552),u=i(40346);s.exports=function isSymbol(s){return"symbol"==typeof s||u(s)&&"[object Symbol]"==a(s)}},37167(s,o,i){var a=i(4901),u=i(27301),_=i(86009),w=_&&_.isTypedArray,x=w?u(w):a;s.exports=x},47886(s,o,i){var a=i(5861),u=i(40346);s.exports=function isWeakMap(s){return u(s)&&"[object WeakMap]"==a(s)}},33855(s,o,i){var a=i(9999),u=i(15389);s.exports=function iteratee(s){return u("function"==typeof s?s:a(s,1))}},95950(s,o,i){var a=i(70695),u=i(88984),_=i(64894);s.exports=function keys(s){return _(s)?a(s):u(s)}},37241(s,o,i){var a=i(70695),u=i(72903),_=i(64894);s.exports=function keysIn(s){return _(s)?a(s,!0):u(s)}},68090(s){s.exports=function last(s){var o=null==s?0:s.length;return o?s[o-1]:void 0}},50104(s,o,i){var a=i(53661);function memoize(s,o){if("function"!=typeof s||null!=o&&"function"!=typeof o)throw new TypeError("Expected a function");var memoized=function(){var i=arguments,a=o?o.apply(this,i):i[0],u=memoized.cache;if(u.has(a))return u.get(a);var _=s.apply(this,i);return memoized.cache=u.set(a,_)||u,_};return memoized.cache=new(memoize.Cache||a),memoized}memoize.Cache=a,s.exports=memoize},55364(s,o,i){var a=i(85250),u=i(20999)((function(s,o,i){a(s,o,i)}));s.exports=u},6048(s){s.exports=function negate(s){if("function"!=typeof s)throw new TypeError("Expected a function");return function(){var o=arguments;switch(o.length){case 0:return!s.call(this);case 1:return!s.call(this,o[0]);case 2:return!s.call(this,o[0],o[1]);case 3:return!s.call(this,o[0],o[1],o[2])}return!s.apply(this,o)}}},63950(s){s.exports=function noop(){}},10124(s,o,i){var a=i(9325);s.exports=function(){return a.Date.now()}},90179(s,o,i){var a=i(34932),u=i(9999),_=i(19931),w=i(31769),x=i(21791),C=i(53138),j=i(38816),L=i(83349),B=j((function(s,o){var i={};if(null==s)return i;var j=!1;o=a(o,(function(o){return o=w(o,s),j||(j=o.length>1),o})),x(s,L(s),i),j&&(i=u(i,7,C));for(var B=o.length;B--;)_(i,o[B]);return i}));s.exports=B},50583(s,o,i){var a=i(47237),u=i(17255),_=i(28586),w=i(77797);s.exports=function property(s){return _(s)?a(w(s)):u(s)}},84195(s,o,i){var a=i(66977),u=i(38816),_=u((function(s,o){return a(s,256,void 0,void 0,void 0,o)}));s.exports=_},40860(s,o,i){var a=i(40882),u=i(80909),_=i(15389),w=i(85558),x=i(56449);s.exports=function reduce(s,o,i){var C=x(s)?a:w,j=arguments.length<3;return C(s,_(o,4),i,j,u)}},63560(s,o,i){var a=i(73170);s.exports=function set(s,o,i){return null==s?s:a(s,o,i)}},42426(s,o,i){var a=i(14248),u=i(15389),_=i(90916),w=i(56449),x=i(36800);s.exports=function some(s,o,i){var C=w(s)?a:_;return i&&x(s,o,i)&&(o=void 0),C(s,u(o,3))}},63345(s){s.exports=function stubArray(){return[]}},89935(s){s.exports=function stubFalse(){return!1}},17400(s,o,i){var a=i(99374),u=1/0;s.exports=function toFinite(s){return s?(s=a(s))===u||s===-1/0?17976931348623157e292*(s<0?-1:1):s==s?s:0:0===s?s:0}},61489(s,o,i){var a=i(17400);s.exports=function toInteger(s){var o=a(s),i=o%1;return o==o?i?o-i:o:0}},80218(s,o,i){var a=i(13222);s.exports=function toLower(s){return a(s).toLowerCase()}},99374(s,o,i){var a=i(54128),u=i(23805),_=i(44394),w=/^[-+]0x[0-9a-f]+$/i,x=/^0b[01]+$/i,C=/^0o[0-7]+$/i,j=parseInt;s.exports=function toNumber(s){if("number"==typeof s)return s;if(_(s))return NaN;if(u(s)){var o="function"==typeof s.valueOf?s.valueOf():s;s=u(o)?o+"":o}if("string"!=typeof s)return 0===s?s:+s;s=a(s);var i=x.test(s);return i||C.test(s)?j(s.slice(2),i?2:8):w.test(s)?NaN:+s}},42072(s,o,i){var a=i(34932),u=i(23007),_=i(56449),w=i(44394),x=i(61802),C=i(77797),j=i(13222);s.exports=function toPath(s){return _(s)?a(s,C):w(s)?[s]:u(x(j(s)))}},69884(s,o,i){var a=i(21791),u=i(37241);s.exports=function toPlainObject(s){return a(s,u(s))}},13222(s,o,i){var a=i(77556);s.exports=function toString(s){return null==s?"":a(s)}},55808(s,o,i){var a=i(12507)("toUpperCase");s.exports=a},66645(s,o,i){var a=i(1733),u=i(45434),_=i(13222),w=i(22225);s.exports=function words(s,o,i){return s=_(s),void 0===(o=i?void 0:o)?u(s)?w(s):a(s):s.match(o)||[]}},53758(s,o,i){var a=i(30980),u=i(56017),_=i(94033),w=i(56449),x=i(40346),C=i(80257),j=Object.prototype.hasOwnProperty;function lodash(s){if(x(s)&&!w(s)&&!(s instanceof a)){if(s instanceof u)return s;if(j.call(s,"__wrapped__"))return C(s)}return new u(s)}lodash.prototype=_.prototype,lodash.prototype.constructor=lodash,s.exports=lodash},47248(s,o,i){var a=i(16547),u=i(51234);s.exports=function zipObject(s,o){return u(s||[],o||[],a)}},43768(s,o,i){"use strict";var a=i(45981),u=i(85587);o.highlight=highlight,o.highlightAuto=function highlightAuto(s,o){var i,w,x,C,j=o||{},L=j.subset||a.listLanguages(),B=j.prefix,$=L.length,U=-1;null==B&&(B=_);if("string"!=typeof s)throw u("Expected `string` for value, got `%s`",s);w={relevance:0,language:null,value:[]},i={relevance:0,language:null,value:[]};for(;++U<$;)C=L[U],a.getLanguage(C)&&((x=highlight(C,s,o)).language=C,x.relevance>w.relevance&&(w=x),x.relevance>i.relevance&&(w=i,i=x));w.language&&(i.secondBest=w);return i},o.registerLanguage=function registerLanguage(s,o){a.registerLanguage(s,o)},o.listLanguages=function listLanguages(){return a.listLanguages()},o.registerAlias=function registerAlias(s,o){var i,u=s;o&&((u={})[s]=o);for(i in u)a.registerAliases(u[i],{languageName:i})},Emitter.prototype.addText=function text(s){var o,i,a=this.stack;if(""===s)return;o=a[a.length-1],(i=o.children[o.children.length-1])&&"text"===i.type?i.value+=s:o.children.push({type:"text",value:s})},Emitter.prototype.addKeyword=function addKeyword(s,o){this.openNode(o),this.addText(s),this.closeNode()},Emitter.prototype.addSublanguage=function addSublanguage(s,o){var i=this.stack,a=i[i.length-1],u=s.rootNode.children,_=o?{type:"element",tagName:"span",properties:{className:[o]},children:u}:u;a.children=a.children.concat(_)},Emitter.prototype.openNode=function open(s){var o=this.stack,i=this.options.classPrefix+s,a=o[o.length-1],u={type:"element",tagName:"span",properties:{className:[i]},children:[]};a.children.push(u),o.push(u)},Emitter.prototype.closeNode=function close(){this.stack.pop()},Emitter.prototype.closeAllNodes=noop,Emitter.prototype.finalize=noop,Emitter.prototype.toHTML=function toHtmlNoop(){return""};var _="hljs-";function highlight(s,o,i){var w,x=a.configure({}),C=(i||{}).prefix;if("string"!=typeof s)throw u("Expected `string` for name, got `%s`",s);if(!a.getLanguage(s))throw u("Unknown language: `%s` is not registered",s);if("string"!=typeof o)throw u("Expected `string` for value, got `%s`",o);if(null==C&&(C=_),a.configure({__emitter:Emitter,classPrefix:C}),w=a.highlight(o,{language:s,ignoreIllegals:!0}),a.configure(x||{}),w.errorRaised)throw w.errorRaised;return{relevance:w.relevance,language:w.language,value:w.emitter.rootNode.children}}function Emitter(s){this.options=s,this.rootNode={children:[]},this.stack=[this.rootNode]}function noop(){}},71514(s){"use strict";s.exports=Math.abs},58968(s){"use strict";s.exports=Math.floor},94459(s){"use strict";s.exports=Number.isNaN||function isNaN(s){return s!=s}},6188(s){"use strict";s.exports=Math.max},68002(s){"use strict";s.exports=Math.min},75880(s){"use strict";s.exports=Math.pow},70414(s){"use strict";s.exports=Math.round},73093(s,o,i){"use strict";var a=i(94459);s.exports=function sign(s){return a(s)||0===s?s:s<0?-1:1}},92340(s,o,i){const a=i(6048);function coerceElementMatchingCallback(s){return"string"==typeof s?o=>o.element===s:s.constructor&&s.extend?o=>o instanceof s:s}class ArraySlice{constructor(s){this.elements=s||[]}toValue(){return this.elements.map((s=>s.toValue()))}map(s,o){return this.elements.map(s,o)}flatMap(s,o){return this.map(s,o).reduce(((s,o)=>s.concat(o)),[])}compactMap(s,o){const i=[];return this.forEach((a=>{const u=s.bind(o)(a);u&&i.push(u)})),i}filter(s,o){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(s,o))}reject(s,o){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(a(s),o))}find(s,o){return s=coerceElementMatchingCallback(s),this.elements.find(s,o)}forEach(s,o){this.elements.forEach(s,o)}reduce(s,o){return this.elements.reduce(s,o)}includes(s){return this.elements.some((o=>o.equals(s)))}shift(){return this.elements.shift()}unshift(s){this.elements.unshift(this.refract(s))}push(s){return this.elements.push(this.refract(s)),this}add(s){this.push(s)}get(s){return this.elements[s]}getValue(s){const o=this.elements[s];if(o)return o.toValue()}get length(){return this.elements.length}get isEmpty(){return 0===this.elements.length}get first(){return this.elements[0]}}"undefined"!=typeof Symbol&&(ArraySlice.prototype[Symbol.iterator]=function symbol(){return this.elements[Symbol.iterator]()}),s.exports=ArraySlice},55973(s){class KeyValuePair{constructor(s,o){this.key=s,this.value=o}clone(){const s=new KeyValuePair;return this.key&&(s.key=this.key.clone()),this.value&&(s.value=this.value.clone()),s}}s.exports=KeyValuePair},3110(s,o,i){const a=i(5187),u=i(85015),_=i(98023),w=i(53812),x=i(23805),C=i(85105),j=i(86804);class Namespace{constructor(s){this.elementMap={},this.elementDetection=[],this.Element=j.Element,this.KeyValuePair=j.KeyValuePair,s&&s.noDefault||this.useDefault(),this._attributeElementKeys=[],this._attributeElementArrayKeys=[]}use(s){return s.namespace&&s.namespace({base:this}),s.load&&s.load({base:this}),this}useDefault(){return this.register("null",j.NullElement).register("string",j.StringElement).register("number",j.NumberElement).register("boolean",j.BooleanElement).register("array",j.ArrayElement).register("object",j.ObjectElement).register("member",j.MemberElement).register("ref",j.RefElement).register("link",j.LinkElement),this.detect(a,j.NullElement,!1).detect(u,j.StringElement,!1).detect(_,j.NumberElement,!1).detect(w,j.BooleanElement,!1).detect(Array.isArray,j.ArrayElement,!1).detect(x,j.ObjectElement,!1),this}register(s,o){return this._elements=void 0,this.elementMap[s]=o,this}unregister(s){return this._elements=void 0,delete this.elementMap[s],this}detect(s,o,i){return void 0===i||i?this.elementDetection.unshift([s,o]):this.elementDetection.push([s,o]),this}toElement(s){if(s instanceof this.Element)return s;let o;for(let i=0;i{const o=s[0].toUpperCase()+s.substr(1);this._elements[o]=this.elementMap[s]}))),this._elements}get serialiser(){return new C(this)}}C.prototype.Namespace=Namespace,s.exports=Namespace},10866(s,o,i){const a=i(6048),u=i(92340);class ObjectSlice extends u{map(s,o){return this.elements.map((i=>s.bind(o)(i.value,i.key,i)))}filter(s,o){return new ObjectSlice(this.elements.filter((i=>s.bind(o)(i.value,i.key,i))))}reject(s,o){return this.filter(a(s.bind(o)))}forEach(s,o){return this.elements.forEach(((i,a)=>{s.bind(o)(i.value,i.key,i,a)}))}keys(){return this.map(((s,o)=>o.toValue()))}values(){return this.map((s=>s.toValue()))}}s.exports=ObjectSlice},86804(s,o,i){const a=i(10316),u=i(41067),_=i(71167),w=i(40239),x=i(12242),C=i(6233),j=i(87726),L=i(61045),B=i(86303),$=i(14540),U=i(92340),V=i(10866),z=i(55973);function refract(s){if(s instanceof a)return s;if("string"==typeof s)return new _(s);if("number"==typeof s)return new w(s);if("boolean"==typeof s)return new x(s);if(null===s)return new u;if(Array.isArray(s))return new C(s.map(refract));if("object"==typeof s){return new L(s)}return s}a.prototype.ObjectElement=L,a.prototype.RefElement=$,a.prototype.MemberElement=j,a.prototype.refract=refract,U.prototype.refract=refract,s.exports={Element:a,NullElement:u,StringElement:_,NumberElement:w,BooleanElement:x,ArrayElement:C,MemberElement:j,ObjectElement:L,LinkElement:B,RefElement:$,refract,ArraySlice:U,ObjectSlice:V,KeyValuePair:z}},86303(s,o,i){const a=i(10316);s.exports=class LinkElement extends a{constructor(s,o,i){super(s||[],o,i),this.element="link"}get relation(){return this.attributes.get("relation")}set relation(s){this.attributes.set("relation",s)}get href(){return this.attributes.get("href")}set href(s){this.attributes.set("href",s)}}},14540(s,o,i){const a=i(10316);s.exports=class RefElement extends a{constructor(s,o,i){super(s||[],o,i),this.element="ref",this.path||(this.path="element")}get path(){return this.attributes.get("path")}set path(s){this.attributes.set("path",s)}}},34035(s,o,i){const a=i(3110),u=i(86804);o.g$=a,o.KeyValuePair=i(55973),o.G6=u.ArraySlice,o.ot=u.ObjectSlice,o.Hg=u.Element,o.Om=u.StringElement,o.kT=u.NumberElement,o.bd=u.BooleanElement,o.Os=u.NullElement,o.wE=u.ArrayElement,o.Sh=u.ObjectElement,o.Pr=u.MemberElement,o.sI=u.RefElement,o.Ft=u.LinkElement,o.e=u.refract,i(85105),i(75147)},6233(s,o,i){const a=i(6048),u=i(10316),_=i(92340);class ArrayElement extends u{constructor(s,o,i){super(s||[],o,i),this.element="array"}primitive(){return"array"}get(s){return this.content[s]}getValue(s){const o=this.get(s);if(o)return o.toValue()}getIndex(s){return this.content[s]}set(s,o){return this.content[s]=this.refract(o),this}remove(s){const o=this.content.splice(s,1);return o.length?o[0]:null}map(s,o){return this.content.map(s,o)}flatMap(s,o){return this.map(s,o).reduce(((s,o)=>s.concat(o)),[])}compactMap(s,o){const i=[];return this.forEach((a=>{const u=s.bind(o)(a);u&&i.push(u)})),i}filter(s,o){return new _(this.content.filter(s,o))}reject(s,o){return this.filter(a(s),o)}reduce(s,o){let i,a;void 0!==o?(i=0,a=this.refract(o)):(i=1,a="object"===this.primitive()?this.first.value:this.first);for(let o=i;o{s.bind(o)(i,this.refract(a))}))}shift(){return this.content.shift()}unshift(s){this.content.unshift(this.refract(s))}push(s){return this.content.push(this.refract(s)),this}add(s){this.push(s)}findElements(s,o){const i=o||{},a=!!i.recursive,u=void 0===i.results?[]:i.results;return this.forEach(((o,i,_)=>{a&&void 0!==o.findElements&&o.findElements(s,{results:u,recursive:a}),s(o,i,_)&&u.push(o)})),u}find(s){return new _(this.findElements(s,{recursive:!0}))}findByElement(s){return this.find((o=>o.element===s))}findByClass(s){return this.find((o=>o.classes.includes(s)))}getById(s){return this.find((o=>o.id.toValue()===s)).first}includes(s){return this.content.some((o=>o.equals(s)))}contains(s){return this.includes(s)}empty(){return new this.constructor([])}"fantasy-land/empty"(){return this.empty()}concat(s){return new this.constructor(this.content.concat(s.content))}"fantasy-land/concat"(s){return this.concat(s)}"fantasy-land/map"(s){return new this.constructor(this.map(s))}"fantasy-land/chain"(s){return this.map((o=>s(o)),this).reduce(((s,o)=>s.concat(o)),this.empty())}"fantasy-land/filter"(s){return new this.constructor(this.content.filter(s))}"fantasy-land/reduce"(s,o){return this.content.reduce(s,o)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}get first(){return this.getIndex(0)}get second(){return this.getIndex(1)}get last(){return this.getIndex(this.length-1)}}ArrayElement.empty=function empty(){return new this},ArrayElement["fantasy-land/empty"]=ArrayElement.empty,"undefined"!=typeof Symbol&&(ArrayElement.prototype[Symbol.iterator]=function symbol(){return this.content[Symbol.iterator]()}),s.exports=ArrayElement},12242(s,o,i){const a=i(10316);s.exports=class BooleanElement extends a{constructor(s,o,i){super(s,o,i),this.element="boolean"}primitive(){return"boolean"}}},10316(s,o,i){const a=i(2404),u=i(55973),_=i(92340);class Element{constructor(s,o,i){o&&(this.meta=o),i&&(this.attributes=i),this.content=s}freeze(){Object.isFrozen(this)||(this._meta&&(this.meta.parent=this,this.meta.freeze()),this._attributes&&(this.attributes.parent=this,this.attributes.freeze()),this.children.forEach((s=>{s.parent=this,s.freeze()}),this),this.content&&Array.isArray(this.content)&&Object.freeze(this.content),Object.freeze(this))}primitive(){}clone(){const s=new this.constructor;return s.element=this.element,this.meta.length&&(s._meta=this.meta.clone()),this.attributes.length&&(s._attributes=this.attributes.clone()),this.content?this.content.clone?s.content=this.content.clone():Array.isArray(this.content)?s.content=this.content.map((s=>s.clone())):s.content=this.content:s.content=this.content,s}toValue(){return this.content instanceof Element?this.content.toValue():this.content instanceof u?{key:this.content.key.toValue(),value:this.content.value?this.content.value.toValue():void 0}:this.content&&this.content.map?this.content.map((s=>s.toValue()),this):this.content}toRef(s){if(""===this.id.toValue())throw Error("Cannot create reference to an element that does not contain an ID");const o=new this.RefElement(this.id.toValue());return s&&(o.path=s),o}findRecursive(...s){if(arguments.length>1&&!this.isFrozen)throw new Error("Cannot find recursive with multiple element names without first freezing the element. Call `element.freeze()`");const o=s.pop();let i=new _;const append=(s,o)=>(s.push(o),s),checkElement=(s,i)=>{i.element===o&&s.push(i);const a=i.findRecursive(o);return a&&a.reduce(append,s),i.content instanceof u&&(i.content.key&&checkElement(s,i.content.key),i.content.value&&checkElement(s,i.content.value)),s};return this.content&&(this.content.element&&checkElement(i,this.content),Array.isArray(this.content)&&this.content.reduce(checkElement,i)),s.isEmpty||(i=i.filter((o=>{let i=o.parents.map((s=>s.element));for(const o in s){const a=s[o],u=i.indexOf(a);if(-1===u)return!1;i=i.splice(0,u)}return!0}))),i}set(s){return this.content=s,this}equals(s){return a(this.toValue(),s)}getMetaProperty(s,o){if(!this.meta.hasKey(s)){if(this.isFrozen){const s=this.refract(o);return s.freeze(),s}this.meta.set(s,o)}return this.meta.get(s)}setMetaProperty(s,o){this.meta.set(s,o)}get element(){return this._storedElement||"element"}set element(s){this._storedElement=s}get content(){return this._content}set content(s){if(s instanceof Element)this._content=s;else if(s instanceof _)this.content=s.elements;else if("string"==typeof s||"number"==typeof s||"boolean"==typeof s||"null"===s||null==s)this._content=s;else if(s instanceof u)this._content=s;else if(Array.isArray(s))this._content=s.map(this.refract);else{if("object"!=typeof s)throw new Error("Cannot set content to given value");this._content=Object.keys(s).map((o=>new this.MemberElement(o,s[o])))}}get meta(){if(!this._meta){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._meta=new this.ObjectElement}return this._meta}set meta(s){s instanceof this.ObjectElement?this._meta=s:this.meta.set(s||{})}get attributes(){if(!this._attributes){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._attributes=new this.ObjectElement}return this._attributes}set attributes(s){s instanceof this.ObjectElement?this._attributes=s:this.attributes.set(s||{})}get id(){return this.getMetaProperty("id","")}set id(s){this.setMetaProperty("id",s)}get classes(){return this.getMetaProperty("classes",[])}set classes(s){this.setMetaProperty("classes",s)}get title(){return this.getMetaProperty("title","")}set title(s){this.setMetaProperty("title",s)}get description(){return this.getMetaProperty("description","")}set description(s){this.setMetaProperty("description",s)}get links(){return this.getMetaProperty("links",[])}set links(s){this.setMetaProperty("links",s)}get isFrozen(){return Object.isFrozen(this)}get parents(){let{parent:s}=this;const o=new _;for(;s;)o.push(s),s=s.parent;return o}get children(){if(Array.isArray(this.content))return new _(this.content);if(this.content instanceof u){const s=new _([this.content.key]);return this.content.value&&s.push(this.content.value),s}return this.content instanceof Element?new _([this.content]):new _}get recursiveChildren(){const s=new _;return this.children.forEach((o=>{s.push(o),o.recursiveChildren.forEach((o=>{s.push(o)}))})),s}}s.exports=Element},87726(s,o,i){const a=i(55973),u=i(10316);s.exports=class MemberElement extends u{constructor(s,o,i,u){super(new a,i,u),this.element="member",this.key=s,this.value=o}get key(){return this.content.key}set key(s){this.content.key=this.refract(s)}get value(){return this.content.value}set value(s){this.content.value=this.refract(s)}}},41067(s,o,i){const a=i(10316);s.exports=class NullElement extends a{constructor(s,o,i){super(s||null,o,i),this.element="null"}primitive(){return"null"}set(){return new Error("Cannot set the value of null")}}},40239(s,o,i){const a=i(10316);s.exports=class NumberElement extends a{constructor(s,o,i){super(s,o,i),this.element="number"}primitive(){return"number"}}},61045(s,o,i){const a=i(6048),u=i(23805),_=i(6233),w=i(87726),x=i(10866);s.exports=class ObjectElement extends _{constructor(s,o,i){super(s||[],o,i),this.element="object"}primitive(){return"object"}toValue(){return this.content.reduce(((s,o)=>(s[o.key.toValue()]=o.value?o.value.toValue():void 0,s)),{})}get(s){const o=this.getMember(s);if(o)return o.value}getMember(s){if(void 0!==s)return this.content.find((o=>o.key.toValue()===s))}remove(s){let o=null;return this.content=this.content.filter((i=>i.key.toValue()!==s||(o=i,!1))),o}getKey(s){const o=this.getMember(s);if(o)return o.key}set(s,o){if(u(s))return Object.keys(s).forEach((o=>{this.set(o,s[o])})),this;const i=s,a=this.getMember(i);return a?a.value=o:this.content.push(new w(i,o)),this}keys(){return this.content.map((s=>s.key.toValue()))}values(){return this.content.map((s=>s.value.toValue()))}hasKey(s){return this.content.some((o=>o.key.equals(s)))}items(){return this.content.map((s=>[s.key.toValue(),s.value.toValue()]))}map(s,o){return this.content.map((i=>s.bind(o)(i.value,i.key,i)))}compactMap(s,o){const i=[];return this.forEach(((a,u,_)=>{const w=s.bind(o)(a,u,_);w&&i.push(w)})),i}filter(s,o){return new x(this.content).filter(s,o)}reject(s,o){return this.filter(a(s),o)}forEach(s,o){return this.content.forEach((i=>s.bind(o)(i.value,i.key,i)))}}},71167(s,o,i){const a=i(10316);s.exports=class StringElement extends a{constructor(s,o,i){super(s,o,i),this.element="string"}primitive(){return"string"}get length(){return this.content.length}}},75147(s,o,i){const a=i(85105);s.exports=class JSON06Serialiser extends a{serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);let o;s._attributes&&s.attributes.get("variable")&&(o=s.attributes.get("variable"));const i={element:s.element};s._meta&&s._meta.length>0&&(i.meta=this.serialiseObject(s.meta));const a="enum"===s.element||-1!==s.attributes.keys().indexOf("enumerations");if(a){const o=this.enumSerialiseAttributes(s);o&&(i.attributes=o)}else if(s._attributes&&s._attributes.length>0){let{attributes:a}=s;a.get("metadata")&&(a=a.clone(),a.set("meta",a.get("metadata")),a.remove("metadata")),"member"===s.element&&o&&(a=a.clone(),a.remove("variable")),a.length>0&&(i.attributes=this.serialiseObject(a))}if(a)i.content=this.enumSerialiseContent(s,i);else if(this[`${s.element}SerialiseContent`])i.content=this[`${s.element}SerialiseContent`](s,i);else if(void 0!==s.content){let a;o&&s.content.key?(a=s.content.clone(),a.key.attributes.set("variable",o),a=this.serialiseContent(a)):a=this.serialiseContent(s.content),this.shouldSerialiseContent(s,a)&&(i.content=a)}else this.shouldSerialiseContent(s,s.content)&&s instanceof this.namespace.elements.Array&&(i.content=[]);return i}shouldSerialiseContent(s,o){return"parseResult"===s.element||"httpRequest"===s.element||"httpResponse"===s.element||"category"===s.element||"link"===s.element||void 0!==o&&(!Array.isArray(o)||0!==o.length)}refSerialiseContent(s,o){return delete o.attributes,{href:s.toValue(),path:s.path.toValue()}}sourceMapSerialiseContent(s){return s.toValue()}dataStructureSerialiseContent(s){return[this.serialiseContent(s.content)]}enumSerialiseAttributes(s){const o=s.attributes.clone(),i=o.remove("enumerations")||new this.namespace.elements.Array([]),a=o.get("default");let u=o.get("samples")||new this.namespace.elements.Array([]);if(a&&a.content&&(a.content.attributes&&a.content.attributes.remove("typeAttributes"),o.set("default",new this.namespace.elements.Array([a.content]))),u.forEach((s=>{s.content&&s.content.element&&s.content.attributes.remove("typeAttributes")})),s.content&&0!==i.length&&u.unshift(s.content),u=u.map((s=>s instanceof this.namespace.elements.Array?[s]:new this.namespace.elements.Array([s.content]))),u.length&&o.set("samples",u),o.length>0)return this.serialiseObject(o)}enumSerialiseContent(s){if(s._attributes){const o=s.attributes.get("enumerations");if(o&&o.length>0)return o.content.map((s=>{const o=s.clone();return o.attributes.remove("typeAttributes"),this.serialise(o)}))}if(s.content){const o=s.content.clone();return o.attributes.remove("typeAttributes"),[this.serialise(o)]}return[]}deserialise(s){if("string"==typeof s)return new this.namespace.elements.String(s);if("number"==typeof s)return new this.namespace.elements.Number(s);if("boolean"==typeof s)return new this.namespace.elements.Boolean(s);if(null===s)return new this.namespace.elements.Null;if(Array.isArray(s))return new this.namespace.elements.Array(s.map(this.deserialise,this));const o=this.namespace.getElementClass(s.element),i=new o;i.element!==s.element&&(i.element=s.element),s.meta&&this.deserialiseObject(s.meta,i.meta),s.attributes&&this.deserialiseObject(s.attributes,i.attributes);const a=this.deserialiseContent(s.content);if(void 0===a&&null!==i.content||(i.content=a),"enum"===i.element){i.content&&i.attributes.set("enumerations",i.content);let s=i.attributes.get("samples");if(i.attributes.remove("samples"),s){const a=s;s=new this.namespace.elements.Array,a.forEach((a=>{a.forEach((a=>{const u=new o(a);u.element=i.element,s.push(u)}))}));const u=s.shift();i.content=u?u.content:void 0,i.attributes.set("samples",s)}else i.content=void 0;let a=i.attributes.get("default");if(a&&a.length>0){a=a.get(0);const s=new o(a);s.element=i.element,i.attributes.set("default",s)}}else if("dataStructure"===i.element&&Array.isArray(i.content))[i.content]=i.content;else if("category"===i.element){const s=i.attributes.get("meta");s&&(i.attributes.set("metadata",s),i.attributes.remove("meta"))}else"member"===i.element&&i.key&&i.key._attributes&&i.key._attributes.getValue("variable")&&(i.attributes.set("variable",i.key.attributes.get("variable")),i.key.attributes.remove("variable"));return i}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const o={key:this.serialise(s.key)};return s.value&&(o.value=this.serialise(s.value)),o}return s&&s.map?s.map(this.serialise,this):s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const o=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(o.value=this.deserialise(s.value)),o}if(s.map)return s.map(this.deserialise,this)}return s}shouldRefract(s){return!!(s._attributes&&s.attributes.keys().length||s._meta&&s.meta.keys().length)||"enum"!==s.element&&(s.element!==s.primitive()||"member"===s.element)}convertKeyToRefract(s,o){return this.shouldRefract(o)?this.serialise(o):"enum"===o.element?this.serialiseEnum(o):"array"===o.element?o.map((o=>this.shouldRefract(o)||"default"===s?this.serialise(o):"array"===o.element||"object"===o.element||"enum"===o.element?o.children.map((s=>this.serialise(s))):o.toValue())):"object"===o.element?(o.content||[]).map(this.serialise,this):o.toValue()}serialiseEnum(s){return s.children.map((s=>this.serialise(s)))}serialiseObject(s){const o={};return s.forEach(((s,i)=>{if(s){const a=i.toValue();o[a]=this.convertKeyToRefract(a,s)}})),o}deserialiseObject(s,o){Object.keys(s).forEach((i=>{o.set(i,this.deserialise(s[i]))}))}}},85105(s){s.exports=class JSONSerialiser{constructor(s){this.namespace=s||new this.Namespace}serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);const o={element:s.element};s._meta&&s._meta.length>0&&(o.meta=this.serialiseObject(s.meta)),s._attributes&&s._attributes.length>0&&(o.attributes=this.serialiseObject(s.attributes));const i=this.serialiseContent(s.content);return void 0!==i&&(o.content=i),o}deserialise(s){if(!s.element)throw new Error("Given value is not an object containing an element name");const o=new(this.namespace.getElementClass(s.element));o.element!==s.element&&(o.element=s.element),s.meta&&this.deserialiseObject(s.meta,o.meta),s.attributes&&this.deserialiseObject(s.attributes,o.attributes);const i=this.deserialiseContent(s.content);return void 0===i&&null!==o.content||(o.content=i),o}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const o={key:this.serialise(s.key)};return s.value&&(o.value=this.serialise(s.value)),o}if(s&&s.map){if(0===s.length)return;return s.map(this.serialise,this)}return s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const o=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(o.value=this.deserialise(s.value)),o}if(s.map)return s.map(this.deserialise,this)}return s}serialiseObject(s){const o={};if(s.forEach(((s,i)=>{s&&(o[i.toValue()]=this.serialise(s))})),0!==Object.keys(o).length)return o}deserialiseObject(s,o){Object.keys(s).forEach((i=>{o.set(i,this.deserialise(s[i]))}))}}},76578(s){"use strict";s.exports=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]},65606(s){var o,i,a=s.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(s){if(o===setTimeout)return setTimeout(s,0);if((o===defaultSetTimout||!o)&&setTimeout)return o=setTimeout,setTimeout(s,0);try{return o(s,0)}catch(i){try{return o.call(null,s,0)}catch(i){return o.call(this,s,0)}}}!function(){try{o="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(s){o=defaultSetTimout}try{i="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(s){i=defaultClearTimeout}}();var u,_=[],w=!1,x=-1;function cleanUpNextTick(){w&&u&&(w=!1,u.length?_=u.concat(_):x=-1,_.length&&drainQueue())}function drainQueue(){if(!w){var s=runTimeout(cleanUpNextTick);w=!0;for(var o=_.length;o;){for(u=_,_=[];++x1)for(var i=1;i_)throw new RangeError("requested too many random bytes");var i=w.allocUnsafe(s);if(s>0)if(s>u)for(var C=0;C=0||(u[i]=s[i]);return u}(s,o);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);for(a=0;a<_.length;a++)i=_[a],o.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(s,i)&&(u[i]=s[i])}return u}function _defineProperties(s,o){for(var i=0;i=0||(u[i]=s[i]);return u}(s,o);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);for(a=0;a<_.length;a++)i=_[a],o.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(s,i)&&(u[i]=s[i])}return u}function ownKeys(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter((function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable}))),i.push.apply(i,a)}return i}function _objectSpread(s){for(var o=1;o=a?i.notify(s):o.length>u.length&&i.notify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:""})}))}))})),_defineProperty(_assertThisInitialized(i),"onKeyDown",(function(s){"Enter"===s.key&&i.forceNotify(s);var o=i.props.onKeyDown;o&&(s.persist(),o(s))})),_defineProperty(_assertThisInitialized(i),"onBlur",(function(s){i.forceNotify(s);var o=i.props.onBlur;o&&(s.persist(),o(s))})),_defineProperty(_assertThisInitialized(i),"createNotifier",(function(s){if(s<0)i.notify=function(){return null};else if(0===s)i.notify=i.doNotify;else{var o=(0,u.default)((function(s){i.isDebouncing=!1,i.doNotify(s)}),s);i.notify=function(s){i.isDebouncing=!0,o(s)},i.flush=function(){return o.flush()},i.cancel=function(){i.isDebouncing=!1,o.cancel()}}})),_defineProperty(_assertThisInitialized(i),"doNotify",(function(){i.props.onChange.apply(void 0,arguments)})),_defineProperty(_assertThisInitialized(i),"forceNotify",(function(s){var o=i.props.debounceTimeout;if(i.isDebouncing||!(o>0)){i.cancel&&i.cancel();var a=i.state.value,u=i.props.minLength;a.length>=u?i.doNotify(s):i.doNotify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:a})}))}})),i.isDebouncing=!1,i.state={value:void 0===s.value||null===s.value?"":s.value};var a=i.props.debounceTimeout;return i.createNotifier(a),i}return function _createClass(s,o,i){return o&&_defineProperties(s.prototype,o),i&&_defineProperties(s,i),Object.defineProperty(s,"prototype",{writable:!1}),s}(DebounceInput,[{key:"componentDidUpdate",value:function componentDidUpdate(s){if(!this.isDebouncing){var o=this.props,i=o.value,a=o.debounceTimeout,u=s.debounceTimeout,_=s.value,w=this.state.value;void 0!==i&&_!==i&&w!==i&&this.setState({value:i}),a!==u&&this.createNotifier(a)}}},{key:"componentWillUnmount",value:function componentWillUnmount(){this.flush&&this.flush()}},{key:"render",value:function render(){var s,o,i=this.props,u=i.element,w=(i.onChange,i.value,i.minLength,i.debounceTimeout,i.forceNotifyByEnter),x=i.forceNotifyOnBlur,C=i.onKeyDown,j=i.onBlur,L=i.inputRef,B=_objectWithoutProperties(i,_),$=this.state.value;s=w?{onKeyDown:this.onKeyDown}:C?{onKeyDown:C}:{},o=x?{onBlur:this.onBlur}:j?{onBlur:j}:{};var U=L?{ref:L}:{};return a.default.createElement(u,_objectSpread(_objectSpread(_objectSpread(_objectSpread({},B),{},{onChange:this.onChange,value:$},s),o),U))}}]),DebounceInput}(a.default.PureComponent);o.DebounceInput=w,_defineProperty(w,"defaultProps",{element:"input",type:"text",onKeyDown:void 0,onBlur:void 0,value:void 0,minLength:0,debounceTimeout:100,forceNotifyByEnter:!0,forceNotifyOnBlur:!0,inputRef:void 0})},24677(s,o,i){"use strict";var a=i(81214).DebounceInput;a.DebounceInput=a,s.exports=a},22551(s,o,i){"use strict";var a=i(96540),u=i(69982);function p(s){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+s,i=1;i