## Problem and outcome / 问题与结果 Browser sharing can remain connected to a local encoding transport that never becomes usable, leaving viewers without frames. This phase bounds that startup at eight seconds and restores ordinary encoding through the existing failure path. It also keeps ready App services running after a browser-open failure, preserves user presentation/playback choices, and aligns room feedback, illustrated hints, metrics and documentation. 部分环境下,本机编码连接一直无法建立会让观众收不到画面。本轮在八秒后进入现有降级流程,同时修复客户端启动移交、播放状态和前端反馈的一致性问题,并更新官网与中英文教程。 Closes #399. Related: #396. The release contains relevant startup/error-handling repairs, but the reporting machine has not been retested. Keep this issue open for a current-build result. #401 (optional Windows capture-border hiding) remains deferred. Release / 发布版本:**v1.3.1**. ## Release notes ### 中文 - 客户端记住上次确认的启动模式;启动移交保留已保存的语言、纯视觉模式和主题选择。 - 系统浏览器未能自动打开时,客户端继续运行,并在终端保留页面地址、重试入口和具体错误。 - 改善浏览器共享画面的启动兜底,避免 App 媒体因短暂信令中断被误判为失败。 - 音轨变化保持现有视频与观众的本机暂停状态;连接恢复和暂停恢复不再重复播放电视开机动画。 - 修复昵称编辑及长昵称查看,减少重复的角色提示,统一人物选择和连接状态的区别。 - 完善房间准入、密码和邀请说明;复制反馈对应当前链接及当前操作,避免迟到结果覆盖新反馈。 - 修正采集参数、统计单位与采样区间的展示,未知参数不再用配置上限代替。 - 统一提示漫画、状态图标与动效,改善选源器还焦、键盘操作、剧场布局和触控目标尺寸。 - 服务端默认支持 20 位观众,可在配置中设为 1–20 位,房主不占观众名额。 - 更新官网、教程入口和中英文说明,清理过时预览及失用代码。 兼容说明:使用旧版 App 连接更新后的站点时,站点会优先保留自己的显示偏好。如需更改语言或主题,请在进入后的页面调整。 ### English - Remember the last confirmed App launch mode and preserve saved language, visual-mode and theme choices during launch handoff. - Keep the App running if the system browser fails to open, with the page address, retry action and error details available in the terminal. - Improve the browser sharing startup fallback and avoid treating brief signaling outages as App media failures. - Keep existing video and local pause state when audio tracks change. Reconnecting and resuming no longer replay the television startup animation over the picture. - Fix nickname editing and full-name access, remove redundant role hints, and distinguish participant selection from connection state. - Clarify room access, passwords and invitations. Copy feedback now belongs to the current link and operation, so late results cannot replace newer feedback. - Correct capture details, metric units and observation intervals. Unknown capture values are no longer replaced with configured ceilings. - Align illustrated hints, status icons and motion. Improve source-picker focus, keyboard operation, theater layout and touch targets. - Default the Server to 20 viewers, configurable from 1 to 20. The host does not count toward that limit. - Update the website, guide links and bilingual instructions, and remove obsolete previews and unused code. Compatibility: when an older App connects to an updated Site, the Site keeps its saved presentation preferences. Change language or theme on the destination page when using an older launcher. ## Verification / 验证 Non-publishing [CI candidate run 34919320511](https://github.com/TNTcraftHIM/Piik/actions/runs/34919320511) passed Go core, race, Web checks, Server/container verification and all three native App package checks at source 188376e8. Subsequent commits only update deployment documentation, status and TODO; documentation/hygiene checks passed. Product inputs are unchanged. - `npm run check`: TypeScript, 64 test files / 854 tests, and the Web production build passed. - `npm run check:client-core`: final Go source passed tests, formatting, vet and core target builds. Windows capture compilation and geometry checks passed earlier in this phase; later edits did not change native capture. - Website build, documentation checks, repository hygiene and diff checks passed. Existing documentation-size and bundle-size warnings remain. - Actual browser flows covered sharing, source changes, pause/resume, late audio, brief signaling loss, invitation/copy feedback, entry preferences, source-picker focus, and narrow layouts. - A local three-viewer P2P relay check covered quality-report expiry, recovery and cleanup without interrupting video. A controlled browser-helper failure returning `0xc0000005` left the real App launcher and Local service available. - Homepage checks covered Chinese/English, light/dark preferences and inline-film open/close after removing the separate-page entry. Limits: no new reporter-machine confirmation for #396 or the Windows URL-handler crash; physical Safari/mobile, macOS/Linux capture and wider public-network/endurance coverage remain deferred. Formal release artifacts will be built from the approved squash-merge revision. Hero-loop controls and video-adjacent tooltip placement remain open design items in TODO. ## Impact / 影响 Compatible patch; signaling, Native control and capture contracts are unchanged. Older App launch handoff keeps the updated Site's saved presentation preferences. The Server's default viewer limit is corrected to 20; an explicit 1–20 configuration remains valid. Service updates retain persisted room authority but restart active media sessions. Deploy the verified immutable Server artifact through the existing bounded health/recovery process. Public Demo remains open and P2P-only; deployment does not enable SFU or change infrastructure/configuration.
471 lines
15 KiB
Go
471 lines
15 KiB
Go
// Package config owns Hosted and App Local configuration and ICE discovery.
|
|
// Callers provide configuration inputs; loading opens no runtime resources.
|
|
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"net/netip"
|
|
"net/url"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
|
|
)
|
|
|
|
// Environment selects development-only behavior. A stale unit file must fail
|
|
// closed rather than fall back to development.
|
|
type Environment string
|
|
|
|
// The two accepted PIIK_ENV values.
|
|
const (
|
|
EnvironmentDevelopment Environment = "development"
|
|
EnvironmentProduction Environment = "production"
|
|
)
|
|
|
|
// Bounds and defaults for Hosted configuration.
|
|
const (
|
|
defaultMaxViewersPerRoom = protocol.MaxViewersPerRoomLimit
|
|
defaultPort = 8787
|
|
maxPort = 65_535
|
|
)
|
|
|
|
const removedTurnReason = "ordinary ICE accepts STUN_URLS only"
|
|
|
|
// removedEnvironmentVariables names settings with no current equivalent. An
|
|
// empty reason takes the TURN default.
|
|
// The order is the report order when several removed names are present.
|
|
var removedEnvironmentVariables = []struct{ name, reason string }{
|
|
{"TURN_URLS", ""},
|
|
{"TURN_SHARED_SECRET", ""},
|
|
{"TURN_CREDENTIAL_TTL_SECONDS", ""},
|
|
{"PEER_ICE_TURN_URLS", ""},
|
|
{"PEER_ICE_TURN_SHARED_SECRET", ""},
|
|
{"PEER_ICE_TURN_CREDENTIAL_TTL_SECONDS", ""},
|
|
{"SELECTED_EDGE_TURN_URLS", ""},
|
|
{"SELECTED_EDGE_TURN_SHARED_SECRET", ""},
|
|
{"SELECTED_EDGE_TURN_CREDENTIAL_TTL_SECONDS", ""},
|
|
{"SELECTED_EDGE_TURN_ALLOCATION_CAPACITY", ""},
|
|
{"PEER_ASSISTED_ROOM_IDS", "peer-assisted media applies to every room"},
|
|
{"PEER_ASSISTED_MEDIA", "peer-assisted media is always enabled"},
|
|
{"HOST_ADMISSION_PASSWORD", "use SITE_ACCESS_PASSWORD"},
|
|
{"MAX_PEER_RELAY_DOWNSTREAM_EDGES", "use ENDPOINT_MEDIA_COPY_CAPACITY"},
|
|
{"ROOM_TTL_SECONDS", "rooms do not expire"},
|
|
{"ROOM_LEASE_SECONDS", "rooms do not expire"},
|
|
{"ACCESS_PASSWORD", "use SITE_ACCESS_PASSWORD"},
|
|
{"NODE_ENV", "use PIIK_ENV"},
|
|
}
|
|
|
|
// SFUConfig enables the embedded UDP media listener.
|
|
type SFUConfig struct {
|
|
ListenHost string
|
|
Port int
|
|
PublicIP string
|
|
}
|
|
|
|
// Config describes runtime configuration. Zero values mean open site
|
|
// access, process-memory rooms, and no SFU fallback.
|
|
type Config struct {
|
|
Env Environment
|
|
Port int
|
|
ListenHost string
|
|
PublicBaseURL *url.URL
|
|
// AllowedOrigins is a membership test only; map order is not observable.
|
|
AllowedOrigins map[string]struct{}
|
|
SiteAccessPassword string
|
|
RoomDatabasePath string
|
|
MaxViewersPerRoom int
|
|
EndpointMediaCopyCapacity int
|
|
SFU *SFUConfig
|
|
STUNURLs []string
|
|
// STUNListenAddresses is populated only by Hosted configuration. Local
|
|
// discovery URLs do not make the Client an externally reachable STUN server.
|
|
STUNListenAddresses []string
|
|
NATPredictionEnabled bool
|
|
// NATPredictionSTUNURLs is nil when unset, which IceConfig distinguishes
|
|
// from a configured empty list.
|
|
NATPredictionSTUNURLs []string
|
|
}
|
|
|
|
// Load validates the whole process environment. Presence, not emptiness,
|
|
// distinguishes an explicit value from an unset value where that distinction
|
|
// is part of the contract.
|
|
func Load(env map[string]string) (Config, error) {
|
|
for _, removed := range removedEnvironmentVariables {
|
|
if _, present := env[removed.name]; present {
|
|
reason := removed.reason
|
|
if reason == "" {
|
|
reason = removedTurnReason
|
|
}
|
|
return Config{}, fmt.Errorf("%s is no longer supported; %s", removed.name, reason)
|
|
}
|
|
}
|
|
|
|
environment, err := parseEnvironment(env)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
port, err := parsePositiveInteger(env["PORT"], defaultPort, "PORT")
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
if port > maxPort {
|
|
return Config{}, fmt.Errorf("PORT must be at most %d", maxPort)
|
|
}
|
|
listenHost := strings.TrimFunc(env["LISTEN_HOST"], protocol.IsJSWhitespace)
|
|
if listenHost == "" {
|
|
listenHost = "0.0.0.0"
|
|
}
|
|
|
|
// Only an absent variable takes the default; an explicit empty value is
|
|
// invalid below.
|
|
rawPublicBaseURL, present := env["PUBLIC_BASE_URL"]
|
|
if !present {
|
|
rawPublicBaseURL = fmt.Sprintf("http://localhost:%d", port)
|
|
}
|
|
publicBaseURL, err := parseOriginURL(rawPublicBaseURL, "PUBLIC_BASE_URL", "http", "https")
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
if environment == EnvironmentProduction && publicBaseURL.Scheme != "https" {
|
|
return Config{}, errors.New("PUBLIC_BASE_URL must use https in production")
|
|
}
|
|
|
|
siteAccessPassword := env["SITE_ACCESS_PASSWORD"]
|
|
roomDatabasePath, err := parseRoomDatabasePath(env["ROOM_DATABASE_PATH"])
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
stunURLs, err := parseStunURLList(env["STUN_URLS"], "STUN_URLS")
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
natPredictionEnabled, err := parseBoolean(env["NAT_PREDICTION_ENABLED"], "NAT_PREDICTION_ENABLED")
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
if natPredictionEnabled && len(NATPredictionStunURLs(stunURLs)) == 0 {
|
|
return Config{}, errors.New("NAT_PREDICTION_ENABLED requires a STUN_URLS entry on UDP 3478")
|
|
}
|
|
if natPredictionEnabled &&
|
|
len(stunURLs)+protocol.MaxNatPredictionAuxiliaryStunURLs > protocol.MaxIceServerURLs {
|
|
return Config{}, fmt.Errorf(
|
|
"STUN_URLS must contain at most %d URLs when NAT_PREDICTION_ENABLED=true",
|
|
protocol.MaxIceServerURLs-protocol.MaxNatPredictionAuxiliaryStunURLs)
|
|
}
|
|
var stunListeners []string
|
|
if len(stunURLs) > 0 {
|
|
stunListeners, err = stunListenAddresses(env["STUN_LISTEN_HOST"], natPredictionEnabled)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
}
|
|
maxViewersPerRoom, err := parseBoundedInteger(env["MAX_VIEWERS_PER_ROOM"],
|
|
defaultMaxViewersPerRoom, "MAX_VIEWERS_PER_ROOM", 1, protocol.MaxViewersPerRoomLimit)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
endpointMediaCopyCapacity, err := parseBoundedInteger(env["ENDPOINT_MEDIA_COPY_CAPACITY"],
|
|
protocol.DefaultEndpointMediaCopyCapacity, "ENDPOINT_MEDIA_COPY_CAPACITY",
|
|
1, protocol.MaxEndpointMediaCopyCapacity)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
sfu, err := parseSFU(env)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
if environment == EnvironmentProduction && len(stunURLs) == 0 {
|
|
return Config{}, errors.New("STUN is required in production")
|
|
}
|
|
|
|
allowedOrigins, err := parseOrigins(env["ALLOWED_ORIGINS"], Origin(publicBaseURL))
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
return Config{
|
|
Env: environment,
|
|
Port: int(port),
|
|
ListenHost: listenHost,
|
|
PublicBaseURL: publicBaseURL,
|
|
AllowedOrigins: allowedOrigins,
|
|
SiteAccessPassword: siteAccessPassword,
|
|
RoomDatabasePath: roomDatabasePath,
|
|
MaxViewersPerRoom: int(maxViewersPerRoom),
|
|
EndpointMediaCopyCapacity: int(endpointMediaCopyCapacity),
|
|
SFU: sfu,
|
|
STUNURLs: stunURLs,
|
|
STUNListenAddresses: stunListeners,
|
|
NATPredictionEnabled: natPredictionEnabled,
|
|
}, nil
|
|
}
|
|
|
|
// parseEnvironment ports parseEnvironment for PIIK_ENV.
|
|
func parseEnvironment(env map[string]string) (Environment, error) {
|
|
value, present := env["PIIK_ENV"]
|
|
if !present {
|
|
return EnvironmentDevelopment, nil
|
|
}
|
|
switch Environment(value) {
|
|
case EnvironmentDevelopment, EnvironmentProduction:
|
|
return Environment(value), nil
|
|
}
|
|
return "", errors.New("PIIK_ENV must be development or production")
|
|
}
|
|
|
|
// parseBoolean ports parseBoolean; every caller used a false fallback.
|
|
func parseBoolean(value string, name string) (bool, error) {
|
|
switch value {
|
|
case "", "false":
|
|
return false, nil
|
|
case "true":
|
|
return true, nil
|
|
}
|
|
return false, fmt.Errorf("%s must be true or false", name)
|
|
}
|
|
|
|
// parsePositiveInteger ports parsePositiveInteger, including Number.isSafeInteger.
|
|
func parsePositiveInteger(value string, fallback int64, name string) (int64, error) {
|
|
if value == "" {
|
|
return fallback, nil
|
|
}
|
|
number, ok := jsNumber(value)
|
|
if !ok || number != math.Trunc(number) || number <= 0 || number > protocol.MaxSafeInteger {
|
|
return 0, fmt.Errorf("%s must be a positive integer", name)
|
|
}
|
|
return int64(number), nil
|
|
}
|
|
|
|
// parseBoundedInteger ports parseBoundedInteger.
|
|
func parseBoundedInteger(value string, fallback int64, name string, minimum, maximum int64) (int64, error) {
|
|
parsed, err := parsePositiveInteger(value, fallback, name)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if parsed < minimum || parsed > maximum {
|
|
return 0, fmt.Errorf("%s must be between %d and %d", name, minimum, maximum)
|
|
}
|
|
return parsed, nil
|
|
}
|
|
|
|
// Hosted defaults to durable room authority in its working directory. Explicit
|
|
// paths stay absolute so a deployment cannot relocate an existing database
|
|
// when its working directory changes. :memory: selects the in-memory RoomStore.
|
|
func parseRoomDatabasePath(value string) (string, error) {
|
|
path := strings.TrimFunc(value, protocol.IsJSWhitespace)
|
|
if path == "" {
|
|
return filepath.Abs("rooms.sqlite")
|
|
}
|
|
if path == ":memory:" {
|
|
return "", nil
|
|
}
|
|
if strings.ContainsRune(path, 0) || !filepath.IsAbs(path) {
|
|
return "", errors.New("ROOM_DATABASE_PATH must be an absolute file path")
|
|
}
|
|
return path, nil
|
|
}
|
|
|
|
func parseSFU(env map[string]string) (*SFUConfig, error) {
|
|
rawPort := strings.TrimSpace(env["SFU_UDP_PORT"])
|
|
if rawPort == "" {
|
|
return nil, nil
|
|
}
|
|
port, err := parseBoundedInteger(rawPort, 0, "SFU_UDP_PORT", 1, maxPort)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
listenHost := strings.TrimSpace(env["SFU_LISTEN_HOST"])
|
|
if listenHost == "" {
|
|
listenHost = "0.0.0.0"
|
|
}
|
|
if address, err := netip.ParseAddr(listenHost); err != nil || !address.Is4() {
|
|
return nil, errors.New("SFU_LISTEN_HOST must be an IPv4 address")
|
|
}
|
|
publicIP := strings.TrimSpace(env["SFU_PUBLIC_IP"])
|
|
if publicIP != "" {
|
|
if address, err := netip.ParseAddr(publicIP); err != nil || !address.Is4() {
|
|
return nil, errors.New("SFU_PUBLIC_IP must be an IPv4 address")
|
|
}
|
|
}
|
|
return &SFUConfig{
|
|
ListenHost: listenHost,
|
|
Port: int(port),
|
|
PublicIP: publicIP,
|
|
}, nil
|
|
}
|
|
|
|
// parseURLList ports parseUrlList.
|
|
func parseURLList(value string, name string) ([]string, error) {
|
|
if strings.TrimFunc(value, protocol.IsJSWhitespace) == "" {
|
|
return nil, nil
|
|
}
|
|
entries := strings.Split(value, ",")
|
|
list := make([]string, 0, len(entries))
|
|
for _, entry := range entries {
|
|
trimmed := strings.TrimFunc(entry, protocol.IsJSWhitespace)
|
|
if trimmed == "" {
|
|
return nil, fmt.Errorf("%s contains an empty URL", name)
|
|
}
|
|
list = append(list, trimmed)
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
// parseStunURLList validates the bounded ordinary-STUN list.
|
|
func parseStunURLList(value string, name string) ([]string, error) {
|
|
values, err := parseURLList(value, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(values) > protocol.MaxIceServerURLs {
|
|
return nil, fmt.Errorf("%s must contain at most %d URLs", name, protocol.MaxIceServerURLs)
|
|
}
|
|
for _, value := range values {
|
|
if !protocol.ValidStunURLValue(value) {
|
|
return nil, fmt.Errorf("%s contains an invalid STUN URL", name)
|
|
}
|
|
}
|
|
return values, nil
|
|
}
|
|
|
|
// parseOrigins ports parseOrigins.
|
|
func parseOrigins(value string, fallback string) (map[string]struct{}, error) {
|
|
origins, err := parseURLList(value, "ALLOWED_ORIGINS")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(origins) == 0 {
|
|
origins = []string{fallback}
|
|
}
|
|
set := make(map[string]struct{}, len(origins))
|
|
for _, entry := range origins {
|
|
origin, err := toOrigin(entry)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
set[origin] = struct{}{}
|
|
}
|
|
return set, nil
|
|
}
|
|
|
|
// toOrigin validates one allowed HTTP(S) origin.
|
|
func toOrigin(value string) (string, error) {
|
|
parsed, err := url.Parse(value)
|
|
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
|
return "", errors.New("Allowed origins must be valid http or https URLs")
|
|
}
|
|
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
|
return "", errors.New("Allowed origins must use http or https")
|
|
}
|
|
return Origin(parsed), nil
|
|
}
|
|
|
|
// parseOriginURL validates an origin and returns the WHATWG-normalised URL
|
|
// (lowercase host, default port removed, path "/").
|
|
func parseOriginURL(value, name, scheme, alternative string) (*url.URL, error) {
|
|
parsed, err := url.Parse(value)
|
|
// net/url accepts relative references and opaque URLs that the WHATWG
|
|
// parser rejects (or, for "wss:host", repairs); require both parts.
|
|
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
|
return nil, fmt.Errorf("%s must be a valid %s or %s origin", name, scheme, alternative)
|
|
}
|
|
if parsed.Scheme != scheme && parsed.Scheme != alternative {
|
|
return nil, fmt.Errorf("%s must use %s or %s", name, scheme, alternative)
|
|
}
|
|
// WHATWG reports "/" for an empty path, while net/url leaves it "".
|
|
if hasUserinfo(parsed) || (parsed.Path != "" && parsed.Path != "/") ||
|
|
parsed.RawQuery != "" || parsed.Fragment != "" {
|
|
return nil, fmt.Errorf(
|
|
"%s must be an origin without credentials, path, query, or fragment", name)
|
|
}
|
|
return &url.URL{Scheme: parsed.Scheme, Host: normalizedHost(parsed), Path: "/"}, nil
|
|
}
|
|
|
|
// hasUserinfo ports `url.username || url.password`: WHATWG reports empty
|
|
// strings for "https://@host" and "https://:@host", where net/url reports a
|
|
// non-nil (but empty) Userinfo.
|
|
func hasUserinfo(parsed *url.URL) bool {
|
|
if parsed.User == nil {
|
|
return false
|
|
}
|
|
password, _ := parsed.User.Password()
|
|
return parsed.User.Username() != "" || password != ""
|
|
}
|
|
|
|
// Origin ports the WHATWG URL `origin` getter for the http/https/ws/wss schemes
|
|
// this package accepts: new URL("https://Example.com:443/").origin is
|
|
// "https://example.com". It is exported so app and cmd can compare request
|
|
// origins without a second copy of the rule.
|
|
func Origin(parsed *url.URL) string {
|
|
return parsed.Scheme + "://" + normalizedHost(parsed)
|
|
}
|
|
|
|
// normalizedHost lowercases the host, keeps an IPv6 literal bracketed and drops
|
|
// a port equal to the scheme default. Non-ASCII hosts are not IDNA-encoded, so
|
|
// they keep the form they were configured with.
|
|
func normalizedHost(parsed *url.URL) string {
|
|
host := strings.ToLower(parsed.Hostname())
|
|
if strings.Contains(host, ":") {
|
|
host = "[" + host + "]"
|
|
}
|
|
// WHATWG parses the port as a number, so "0443" and "443" are both default.
|
|
if number, err := strconv.Atoi(parsed.Port()); err == nil {
|
|
if port := strconv.Itoa(number); port != defaultSchemePort(parsed.Scheme) {
|
|
host += ":" + port
|
|
}
|
|
}
|
|
return host
|
|
}
|
|
|
|
func defaultSchemePort(scheme string) string {
|
|
switch scheme {
|
|
case "http", "ws":
|
|
return "80"
|
|
case "https", "wss":
|
|
return "443"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// decimalNumberPattern is the StrDecimalLiteral grammar Number(string) accepts.
|
|
var decimalNumberPattern = regexp.MustCompile(
|
|
`^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`)
|
|
|
|
// jsNumber ports Number(string). The second result is false where JavaScript
|
|
// yields NaN; values JavaScript renders as Infinity are reported as NaN too,
|
|
// because every caller rejects them through Number.isSafeInteger anyway.
|
|
func jsNumber(value string) (float64, bool) {
|
|
text := strings.TrimFunc(value, protocol.IsJSWhitespace)
|
|
if text == "" {
|
|
return 0, true // Number("") and Number(" ") are 0.
|
|
}
|
|
if len(text) > 2 && text[0] == '0' {
|
|
if base := numericBase(text[1]); base != 0 {
|
|
number, err := strconv.ParseUint(text[2:], base, 64)
|
|
return float64(number), err == nil
|
|
}
|
|
}
|
|
if !decimalNumberPattern.MatchString(text) {
|
|
return 0, false
|
|
}
|
|
number, err := strconv.ParseFloat(text, 64)
|
|
return number, err == nil
|
|
}
|
|
|
|
func numericBase(marker byte) int {
|
|
switch marker {
|
|
case 'x', 'X':
|
|
return 16
|
|
case 'o', 'O':
|
|
return 8
|
|
case 'b', 'B':
|
|
return 2
|
|
}
|
|
return 0
|
|
}
|