Module:BaseDomain

From Trans People Together Wiki

Documentation for this module may be created at Module:BaseDomain/doc

-- Module:BaseDomain
local p = {}

-- frame.args[1] or frame.args.url is the URL to process
function p.extract(frame)
    local url = frame.args[1] or frame.args.url or ''
    local host

    -- Try to parse with mw.uri (MediaWiki ≥1.35)
    local ok, uri = pcall(mw.uri.new, url)
    if ok and uri and uri.host then
        host = uri.host
    else
        -- Fallback: grab everything after scheme:// up to the next /
        host = url:match('^%w+://([^/]+)') or url
    end

    -- Drop any port number
    host = host:gsub(':%d+$', '')

    -- Split on dots
    local parts = {}
    for label in host:gmatch('([^.]+)') do
        parts[#parts + 1] = label
    end

    -- If we have at least two labels, return the last two; otherwise the whole host
    local n = #parts
    if n >= 2 then
        return parts[n-1] .. '.' .. parts[n]
    else
        return host
    end
end

return p