Jump to content
Menü aufrufen
Toggle preferences menu
Persönliches Menü aufrufen
Nicht angemeldet
Ihre IP-Adresse wird öffentlich sichtbar sein, wenn Sie Änderungen vornehmen.
Modul Dokumentation[view][edit][history][purge]
Diese Dokumentation wird von Modul:Entity/Location/Starmap/doc aus übernommen. Änderungen können auf der Diskussionsseite vorgeschlagen werden.

Die ARK-Starmap-Datensätze, die ein Location-Leaf liest: die beiden Brücken für den enrich-Hook, Lookups im angehängten System-Payload sowie Systemnamen und Starmap-Code, zu denen eine Seite auflöst.

Editoren rufen dieses Modul nie direkt auf; es läuft innerhalb von Vorlage:Location oder Vorlage:Entity. Die Leafs, die es aufrufen, stehen auf Modul:Entity/Location.

Für Modul-Editoren

API

  • p.systemShortName(name): ein Systemname in Kurzform (abschließendes System gestrippt, Alias-Klammer und Vanduul-Katalogform entfernt).
  • p.entrySystem(apiData): apiData.system durch systemShortName reduziert.
  • p.gateEntrySystem(apiData): das System des Datensatzes, sonst die eingangsseitige Hälfte der Objektbezeichnung; lässt auch eine datensatzlose |family=jumppoint-Seite ihr System kennen.
  • p.subjectName(apiData, args): der Name dessen, worum es auf der Seite geht: |starmapname=, sonst der Datensatzname, sonst |name=, sonst der Seitentitel. Der Starmap-Suchschlüssel einer Systemseite und zugleich der Eigenname eines Planeten oder Mondes.
  • p.attachStarsystem(apiData, args, name?): Brücke über den Namen zu /api/starsystems; hängt den Datensatz als apiData.starsystem an. Ein Leaf, dessen Subjekt NICHT das System ist, muss den Namen mitgeben. Soft-failt.
  • p.attachCelestialObject(apiData, code): Brücke über den Starmap-Code zu /api/celestial-objects/<code>; hängt als apiData.celestialobject an. Kein Code, kein Fetch; soft-failt genauso.
  • p.celestialByCode(starsystem, code), p.celestialByName(starsystem, name, types?): findet ein Objekt im System-Payload. Codes ganz und case-sensitiv; ein Namensmatch sollte types mitgeben, weil ein Stern keinen name trägt und seine Bezeichnung die des Systems ist.
  • p.celestialName(obj): der Anzeigename eines Objekts — eigener name, wenn die ARK einen gibt, sonst die von Dekorationen befreite Bezeichnung. Die Alias-Klammer wird überall gestrippt, nicht nur am Ende (die ARK schreibt Kyuk'ya (Indra) A).
  • p.celestialParent(starsystem, obj): löst die numerische parent_id gegen die Objektliste des eigenen Systems; nil bei den elf Planeten ohne ARK-Elternteil.
  • p.celestialStarmapCode(apiData, fallback): der Code des angehängten Objekts, sonst der Rohwert von |starmapcode=.
  • p.starsystemOf(apiData), p.manifestArg(args, manifest, key), p.systemNameFrom(apiData, args, manifest), p.resolvedStarmapCode(args, manifest, obj): die Reads eines Leafs, bevor die redaktionelle Auflösung lief. systemNameFrom liest nie das erste Starmap-Code-Segment, das nicht immer das System ist.

Stolperfallen

  • attachStarsystems locale reitet auf dem Endpunkt-String (...&locale=en_EN), nicht in params: Apiunto hängt params als zweite ?query an und würde das ?filter[...] korrumpieren. attachCelestialObjects Endpunkt trägt keinen eigenen Query-String, sein locale reitet sicher in params.
  • normalizeAggregates verwirft den zurückgehaltenen Vermessungs-Stub der ARK (die identischen Bevölkerungs-/Wirtschafts-/Größenblöcke der Vanduul- und Sonden-Systeme), wann immer ein Datensatz keine katalogisierten Körper und einen unveröffentlichten Status (M/N) hat; kein Test allein ist sicher.
  • pickStarsystem löst eine filter[name]-Teilstring-Trefferliste per Präzedenz: exakter Namensmatch, dann die Xi'an-Form <name> (<alias>), dann die erste Zeile.
  • systemShortName strippt Dekorationen in fester Reihenfolge: erst die Vanduul-Katalogform (VS-9 "Vulture" wird Vulture), dann das Suffix System, dann erst die Alias-Klammer — das Suffix muss zuerst weg, weil sich die Klammer am Stringende verankert. Keine Dekoration ist ein Wiki-Seitenname; eine stehen zu lassen rendert einen roten Link und legt eine Phantomekategorie an.

require('strict')

--- @module Entity/Location/Starmap
--- The ARK starmap records a Location leaf reads: the two bridges its enrich
--- hook calls, lookups inside an attached system payload, and the system names
--- and starmap code a page resolves to.
---
--- For star systems the location record is thin; the substantive data lives in
--- the starmap-derived /api/starsystems endpoint. The two records share no
--- key, so attachStarsystem bridges by name and attaches the record as
--- apiData.starsystem — namespaced, never flat-merged: both payloads carry
--- colliding name/type/description/affiliation keys. Jump points and stars
--- bridge to the starmap differently: by the editor-supplied starmap code, to
--- the /api/celestial-objects endpoint, attached as apiData.celestialobject.
--- The two fetches are mutually exclusive by construction — a page resolves to
--- exactly one leaf, and no leaf calls both.

local api = require('Module:Entity/Api')
local editorial = require('Module:Entity/Editorial')

local p = {}

--- The celestial object in a starsystem payload whose code matches, or nil.
--- Codes are compared case-sensitively and whole: a starmap code is an exact
--- key, and prefix matching would collide (SOL.PLANETS.EARTH against a
--- hypothetical SOL.PLANETS.EARTHII).
--- @param starsystem table|nil
--- @param code string|nil
--- @return table|nil
function p.celestialByCode(starsystem, code)
	if type(starsystem) ~= 'table' or type(code) ~= 'string' or code == '' then
		return nil
	end
	local objects = starsystem.celestial_objects
	if type(objects) ~= 'table' then
		return nil
	end
	for _, obj in ipairs(objects) do
		if type(obj) == 'table' and obj.code == code then
			return obj
		end
	end
	return nil
end

--- The celestial object in a starsystem payload whose name matches, or nil.
--- `types` restricts the candidates to those ARK `type` values, and a body must
--- pass it: Stanton's star is also named "Stanton", so an unrestricted match
--- from a page about a body could land on the star.
---
--- This is how an in-game planet or moon resolves at all. A code is not
--- derivable from a body's name: Hurston's is
--- STANTON.PLANETS.STANTONIHURSTONDYNAMICS, built from the designation and the
--- owning corporation, and the 33 in-game pages carry no `code` arg because
--- they were written from the game API, which has no starmap code. The ARK's
--- own `name` is the body's plain name, so it is the one reliable join.
--- @param starsystem table|nil
--- @param name string|nil
--- @param types table|nil set of accepted ARK `type` values
--- @return table|nil
function p.celestialByName(starsystem, name, types)
	if type(starsystem) ~= 'table' or type(name) ~= 'string' or name == '' then
		return nil
	end
	local objects = starsystem.celestial_objects
	if type(objects) ~= 'table' then
		return nil
	end
	local key = mw.ustring.lower(name)
	for _, obj in ipairs(objects) do
		if type(obj) == 'table' and (types == nil or types[obj.type]) then
			local objName = p.celestialName(obj)
			if objName and mw.ustring.lower(objName) == key then
				return obj
			end
		end
	end
	return nil
end

--- A celestial object's display name: its own `name` when the ARK gives one,
--- else its designation with the alias parenthetical and catalogue decorations
--- stripped. Terra's star is the reason `name` wins: it is "Terra Nova" while
--- the designation is just "Terra". Most objects have no `name` at all, so the
--- designation path is the common one.
---
--- The parenthetical is stripped wherever it sits, not just trailing as
--- systemShortName does it: the ARK embeds a Xi'an alias MID-designation
--- ("Kyuk'ya (Indra) A"), and leaving it in names a page that does not exist.
--- An ARK designation carries no other parentheses.
--- @param obj table|nil
--- @return string|nil
function p.celestialName(obj)
	if type(obj) ~= 'table' then
		return nil
	end
	local name = type(obj.name) == 'string' and obj.name ~= '' and obj.name or nil
	if name then
		return name
	end
	if type(obj.designation) ~= 'string' then
		return nil
	end
	return p.systemShortName((obj.designation:gsub('%s*%b()', '')))
end

--- The object an object orbits, resolved against its own system's object list.
--- The starmap gives only a numeric `parent_id`, so a single-object fetch can
--- never answer this — which is why bodies bridge through attachStarsystem.
--- nil where the ARK records no parent: the eleven planets in multi-star or
--- star-less systems (Goss, Baker, Bacchus, Min) carry `parent_id = null`,
--- because it does not say which sun they orbit.
--- @param starsystem table|nil
--- @param obj table|nil
--- @return table|nil
function p.celestialParent(starsystem, obj)
	local id = type(obj) == 'table' and obj.parent_id or nil
	if id == nil or type(starsystem) ~= 'table' or type(starsystem.celestial_objects) ~= 'table' then
		return nil
	end
	for _, candidate in ipairs(starsystem.celestial_objects) do
		if type(candidate) == 'table' and candidate.id == id then
			return candidate
		end
	end
	return nil
end

--- Bucket's short-name pass: the English wiki's original normalization, kept
--- verbatim because every short description, link and verbatim column already
--- on that wiki was built by it, and the SMW pass (systemShortName) moves
--- values - its VS-catalogue match also runs on spellings carrying a suffix
--- or disambiguator, so a designation like 'VS-9 "Vulture" System' kept the
--- catalogue spelling where the SMW pass reduces it to 'Vulture', and a bare
--- suffix word in any casing stayed a name instead of nil.
--- @param name any
--- @return string|nil
local function bucketShortName(name)
	if type(name) ~= 'string' then
		return nil
	end
	local short = name:match('^%s*VS%-%d+%s*"(.+)"%s*$') or name
	short = short:gsub('%s+[Ss]ystem$', '')
	short = mw.text.trim((short:gsub('%s*%b()%s*$', '')))
	if short == '' then
		return nil
	end
	return short
end

--- A system name reduced to its bare form: a trailing "System" suffix in
--- any casing stripped, whitespace trimmed ("Pyro System" -> "Pyro", "Nyx"
--- -> "Nyx").
--- Page links and stored values resolve it through systemPageName, and the
--- short descriptions label their system word through systemLinkLabel.
--- Backend-split: Bucket keeps
--- the English wiki's original pass (bucketShortName), SMW reduces through
--- the order the canonicalization below needs.
--- @param name any
--- @param keepTrailingParen boolean|nil leave a trailing parenthetical in
---   place; systemPageTitle drops one only when the canonical records verify
---   it, because an unverified parenthetical can be meaningful. The storage
---   path fetches with this set (see storedSystem) so the original value
---   survives to that check.
--- @return string|nil
function p.systemShortName(name, keepTrailingParen)
	if type(name) ~= 'string' then
		return nil
	end
	if require('Module:Entity/StructuredData').backend() ~= 'smw' then
		return bucketShortName(name)
	end
	-- Strip the starmap's naming decorations: an alias parenthetical
	-- ("Kyuk'ya (Indra)") and the Vanduul catalogue form (VS-9 "Vulture").
	-- Both appear in celestial designations and neither is a wiki page name,
	-- so leaving one in renders a red link, files a bogus "<alias> system"
	-- category and stores a junk System value. Defence in depth for the
	-- fallback paths; a gate page's own canonical name is the primary source
	-- (see the JumpPoint leaf's titleSystems).
	-- Whitespace trims BEFORE the suffix, so 'Stanton System ' cannot keep its
	-- suffix and double it when systemPageName appends another; the bare
	-- 'System' a trim can leave (formerly the untrimmed ' System' collapsing
	-- under the suffix pattern) is no name at all. The suffix goes before the
	-- parenthetical ("Yā'mon (Hadur) System"), and the VS catalogue form runs
	-- LAST, after both: a designation carrying the suffix or a disambiguator
	-- (VS-9 "Vulture" System, VS-9 "Vulture" (System)) then reduces like its
	-- bare form, which is what makes systemPageTitle idempotent - the title a
	-- writer stores must re-derive itself when a filter literal spells it.
	local short = mw.text.trim(name)
	if short:lower() == 'system' then
		return nil
	end
	short = short:gsub('%s+[Ss][Yy][Ss][Tt][Ee][Mm]$', '')
	if not keepTrailingParen then
		short = short:gsub('%s*%b()%s*$', '')
	end
	short = short:match('^%s*VS%-%d+%s*"(.+)"%s*$') or short
	if short == '' then
		return nil
	end
	return short
end

--- The system's wiki page name, for a display link or a stored PAGE value:
--- the short name plus the suffix the target wiki titles its system articles
--- by. The Bucket (English) wiki's articles are the lowercase "<name>
--- system"; the SMW (German) wiki's are the capitalized "<Name> System".
--- Storage and display share this one accessor so the two never diverge.
--- @param short string|nil systemShortName's result
--- @return string|nil
function p.systemPageName(short)
	if type(short) ~= 'string' or short == '' then
		return nil
	end
	local suffix = require('Module:Entity/StructuredData').backend() == 'smw' and ' System' or ' system'
	return short .. suffix
end

--- The canonical system records' short names ("Pyro"), read from the
--- SystemMap dataset. Its keys are the ARK names, and the parenthetical in a
--- key is the alias the German wiki's own articles and editors use
--- ("Kyuk'ya (Indra)" - the article is "Indra"), so both spellings fold onto
--- the record's short name. Case-folded lookup, deterministic build (sorted,
--- so a hypothetical key collision cannot pick a winner by pairs() order).
--- @type table<string, string>|nil
local canonicalShorts = nil

--- The trailing parentheticals systemPageTitle may drop from ANY name: the
--- system disambiguators the wikis title disambiguated system articles by
--- ("(System)", "(Sternensystem)"). An alias parenthetical is verified for
--- one record's complete name only (see strippableNames).
--- @type table<string, boolean>|nil
local strippableParens = nil

--- The complete paren-carrying names whose own parenthetical systemPageTitle
--- drops: the alias spellings the dataset's own keys carry ("Kyuk'ya
--- (Indra)"). The whole name must match, because the dataset verifies the
--- name-alias PAIR - "Foo (Indra)" borrows a parenthetical no record verified
--- for it, and "Foo (Alpha)" / "Foo (Beta)" name two different systems whose
--- parenthetical must survive.
--- @type table<string, boolean>|nil
local strippableNames = nil

--- The alias spellings alone ("Indra"): a name that is a LONE alias
--- parenthetical names nothing once it folds away.
--- @type table<string, boolean>|nil
local aliasSpellings = nil

--- Builds the canonical short-name and parenthetical-fold maps once.
local function canonicalRecords()
	if canonicalShorts == nil then
		canonicalShorts = {}
		strippableParens = { system = true, sternensystem = true }
		strippableNames = {}
		aliasSpellings = {}
		local systems = mw.loadJsonData('Module:SystemMap/systems.json').systems
		local keys = {}
		for key in pairs(systems) do
			keys[#keys + 1] = key
		end
		table.sort(keys)
		for _, key in ipairs(keys) do
			local name = p.systemShortName(key)
			if name ~= nil then
				canonicalShorts[mw.ustring.lower(name)] = name
				local alias = key:match('^.-%s*%((.-)%)%s*$')
				if alias ~= nil then
					canonicalShorts[mw.ustring.lower(alias)] = name
					strippableNames[mw.ustring.lower(p.systemShortName(key, true))] = true
					aliasSpellings[mw.ustring.lower(alias)] = true
				end
			end
		end
	end
end

--- A short system name folded onto the canonical record's spelling, or the
--- input verbatim when no record carries it (a future system the dataset has
--- not regrown yet, or free text): the suffix conventions still apply.
--- @param short string
--- @return string
local function canonicalShort(short)
	canonicalRecords()
	return canonicalShorts[mw.ustring.lower(short)] or short
end

--- The short name carrying the trailing-parenthetical decision the
--- canonical records verify: an UNVERIFIED parenthetical is meaningful and
--- stays ('Foo (Alpha)'), a system disambiguator ('(System)',
--- '(Sternensystem)') folds for any name, and a record's alias folds for
--- the record's own complete spelling ("Kyuk'ya (Indra)") or alone
--- ('(Indra)' names nothing). systemPageTitle appends the suffix to this
--- and folds it onto a record's spelling; systemLinkLabel shows it as the
--- label, so the label's word stays its writer's while its parenthetical
--- decision cannot disagree with the target the row links.
--- @param name any
--- @return string|nil
local function foldTrailingParen(name)
	local short = p.systemShortName(name, true)
	if short == nil then
		return nil
	end
	canonicalRecords()
	local bare, paren = short:match('^(.-)%s*%((.-)%)%s*$')
	if paren ~= nil then
		local lowerParen = mw.ustring.lower(paren)
		-- A disambiguator folds for any name; a record's alias folds only for
		-- the record's own complete spelling; a lone alias parenthetical
		-- ('(Indra)') leaves no name at all.
		local fold = strippableParens[lowerParen]
			or strippableNames[mw.ustring.lower(short)]
			or (bare == '' and aliasSpellings[lowerParen])
		if fold then
			return p.systemShortName(short)
		end
	end
	return short
end

--- The canonical system page title the SMW writers and the SMW filters share:
--- any spelling of one system - a short name, the page name, a record alias
--- ("Indra"), a decorated designation - reduces to one title, the record's
--- short name plus the backend's suffix. Deliberately WITHOUT the title API:
--- mw.title exists/redirect probes are expensive-parser calls and resolve by
--- whatever page happens to exist, so the German wiki's mixed state (a bare
--- "Stanton" article beside "Pyro System", "Terra" a disambiguation,
--- redirects whose targets end in neither suffix) would pick a different
--- title per spelling - writer and filter literals would stop agreeing, and
--- an existing-but-wrong page (the disambiguation) would be stored silently.
--- The canonical records decide; a name no record carries keeps the derived
--- suffix form, a visible red link rather than a silent wrong page. The
--- wiki's own redirects reconcile stored spellings at query time. A trailing
--- parenthetical survives unless the records verify it for this complete
--- name (foldTrailingParen above).
--- @param name any
--- @return string|nil
function p.systemPageTitle(name)
	local short = foldTrailingParen(name)
	if short == nil then
		return nil
	end
	return p.systemPageName(canonicalShort(short))
end

--- The link target an infobox's system row uses: the spelling storage
--- keeps, so the row links the very page the System property names. SMW:
--- the canonical title of the WRITER-SHAPED value - structuredData.
--- shapedPageTitle first, the exact non-redirect PAGE pass the store seam
--- runs on every star-system value, then systemPageTitle - so a linked or
--- underscored spelling ('[[Pyro|Pyro system]]', 'Stanton_System') links the
--- title the writer stores, never a decorated target of its own. Bucket:
--- the legacy short-form page name, the target the English wiki's rows have
--- always linked. Takes the ORIGINAL value, never a pre-shortened one: a
--- shortened spelling would strip a suffix or parenthetical before the
--- canonical fold can decide on it.
--- @param name any
--- @return string|nil
function p.systemLinkTarget(name)
	if require('Module:Entity/StructuredData').backend() ~= 'smw' then
		return p.systemPageName(bucketShortName(name))
	end
	return p.systemPageTitle(require('Module:Entity/StructuredData').shapedPageTitle(name))
end

--- The short name a system row's LABEL shows, from the ORIGINAL system
--- value: under SMW the writer-shaped value run through the same
--- trailing-parenthetical fold its target derives from (foldTrailingParen,
--- after structuredData.shapedPageTitle - the shaping pass systemLinkTarget
--- folds the target from), so an unverified parenthetical stays meaningful
--- ('Foo (Alpha)' labels the row that links 'Foo (Alpha) System') while a
--- record-verified alias or a known disambiguator folds, and a linked or
--- underscored spelling renders one clean word instead of nesting its
--- wikitext inside the label. Bucket keeps the raw value's legacy short
--- form. nil for the values that name no system (blank, bare suffix,
--- paren-only), the same spellings systemLinkTarget reduces to no target.
--- @param name any
--- @return string|nil
function p.systemLinkLabel(name)
	if require('Module:Entity/StructuredData').backend() ~= 'smw' then
		return bucketShortName(name)
	end
	return foldTrailingParen(require('Module:Entity/StructuredData').shapedPageTitle(name))
end

--- The value a writer stores for a star-system field, from the ORIGINAL
--- system value - fetched raw (entrySystem, systemNameFrom, gateEntrySystem
--- with raw set), never a pre-shortened name. Under SMW the value verbatim
--- (rawSystem): the one canonicalization runs at the store seam
--- (Module:Entity/StructuredData/Smw), on the shaped value, and is
--- idempotent - the title a writer stores re-derives itself through the
--- same pass both SMW filter paths apply to their literals. A shortened
--- value would lose a meaningful parenthetical ('Foo (Alpha)') before the
--- canonical records can decide to keep it. Under Bucket the suffixed page
--- name of the legacy short form, the spelling the verbatim columns have
--- always carried.
--- @param name any
--- @return string|nil
function p.storedSystem(name)
	if require('Module:Entity/StructuredData').backend() == 'smw' then
		return p.rawSystem(name)
	end
	return p.systemPageName(bucketShortName(name))
end

--- The storage fields whose values are star-system pages. The SMW store
--- seam (Module:Entity/StructuredData/Smw) canonicalizes them through
--- systemPageTitle and both SMW filter paths derive their literals the same
--- way, so one system stores and queries one title; the PAGE shaping leaves
--- their redirects unfollowed for the same reason (see
--- Module:Entity/StructuredData). Declared beside systemPageTitle, the
--- accessor they all share.
p.systemFields = {
	system = true,
	destination_system = true,
	systems = true,
}

--- A raw storage-path system value: the source string verbatim, or nil for
--- anything the display pass (systemShortName) would also reduce to no name
--- at all - non-strings, blanks and the bare-suffix or paren-only spellings
--- (' System', '(System)'). A value that names nothing must not block the
--- fallback (an editor's arg, the designation) the display path takes,
--- storing nothing while the infobox shows a system. The SMW store seam
--- canonicalizes exactly once, so an emitter hands storage the ORIGINAL
--- value through this, never a pre-shortened one; systemShortName is the
--- validity check only - the answer is never the shortened form.
--- @param value any
--- @return string|nil
function p.rawSystem(value)
	if type(value) ~= 'string' or p.systemShortName(value) == nil then
		return nil
	end
	return value
end

--- The gate's entry system (short form) from the location record. The live
--- locations endpoint serves `system` as a plain string ("Pyro System"); the
--- table-with-name shape is tolerated defensively in case the API ever
--- upgrades the field to an embedded record.
--- @param apiData table
--- @param raw boolean|nil return the record's value verbatim for the storage
---   path (see storedSystem): a pre-shortened value would strip a second
---   ' System' suffix or drop a meaningful parenthetical before the seam's
---   single pass can see it
--- @return string|nil
function p.entrySystem(apiData, raw)
	local system = apiData.system
	if type(system) == 'table' then
		system = system.name
	end
	if raw then
		return p.rawSystem(system)
	end
	return p.systemShortName(system)
end

--- The gate's entry system for ANY jump-point page: the location record's
--- system when one exists, else the first side of the celestial designation.
--- The designation is entry-first for the object's own system by starmap
--- convention (every observed object under <SYS>.JUMPPOINTS.* leads with
--- <SYS>'s name), which is what lets a record-less |family=jumppoint page
--- (the starmap-only tunnels) still know which system it sits in — feeding
--- the System row, the destination disambiguation, the entry-system category
--- and the stored System property alike.
--- @param apiData table
--- @param raw boolean|nil return the entry verbatim for the storage path
---   (see entrySystem)
--- @return string|nil
function p.gateEntrySystem(apiData, raw)
	local entry = p.entrySystem(apiData, raw)
	if entry then
		return entry
	end
	local celestial = type(apiData.celestialobject) == 'table' and apiData.celestialobject or nil
	local designation = celestial and celestial.designation or nil
	if type(designation) ~= 'string' then
		return nil
	end
	local sideA = designation:match('^(.-)%s+%-%s+')
	if not sideA then
		return nil
	end
	if raw then
		return p.rawSystem(sideA)
	end
	return p.systemShortName(mw.text.trim(sideA))
end

--- The name of the subject this page is about: explicit override, then the
--- location record's name, then the editor's display name, then the page
--- title. It is the starmap lookup key for a system page and the body's own
--- name for a planet or moon, which is why it is public.
--- @param apiData table
--- @param args table|nil
--- @return string|nil
function p.subjectName(apiData, args)
	if args and type(args.starmapname) == 'string' and args.starmapname ~= '' then
		return args.starmapname
	end
	if type(apiData.name) == 'string' and apiData.name ~= '' then
		return apiData.name
	end
	if args and type(args.name) == 'string' and args.name ~= '' then
		return args.name
	end
	return mw.title.getCurrentTitle().text
end

--- The attached starmap SYSTEM payload, or nil. A leaf that bridges by system
--- namespaces it here rather than flat on apiData.
--- @param apiData table|nil
--- @return table|nil
function p.starsystemOf(apiData)
	return type(apiData) == 'table' and type(apiData.starsystem) == 'table' and apiData.starsystem or nil
end

--- A leaf's own editorial arg, RAW. Raw because the hooks that read these run
--- before editorial resolution, and the leaf's manifest is passed in because
--- each leaf owns its own arg aliases.
--- @param args table|nil
--- @param manifest table the leaf's getEditorialManifest() fragment
--- @param key string
--- @return string|nil
function p.manifestArg(args, manifest, key)
	local entry = type(manifest) == 'table' and manifest[key] or nil
	return entry and editorial.rawArg(args, entry) or nil
end

--- The system a page belongs to: the record's own, else the editorial arg.
--- NOT the starmap code's first segment, which is not always the system.
--- @param apiData table
--- @param args table|nil
--- @param manifest table
--- @param raw boolean|nil return the source value verbatim for the storage
---   path (see entrySystem)
--- @return string|nil
function p.systemNameFrom(apiData, args, manifest, raw)
	local fromRecord = p.entrySystem(apiData, raw)
	if fromRecord then
		return fromRecord
	end
	local arg = p.manifestArg(args, manifest, 'system')
	if raw then
		return p.rawSystem(arg)
	end
	return p.systemShortName(arg)
end

--- The starmap code to publish: the editor's arg when there is one, else the
--- resolved object's own.
--- @param args table|nil
--- @param manifest table
--- @param obj table|nil the leaf's already-resolved celestial object
--- @return string|nil
function p.resolvedStarmapCode(args, manifest, obj)
	local code = p.manifestArg(args, manifest, 'starmapcode')
	if type(code) == 'string' and code ~= '' then
		return code
	end
	code = obj and obj.code or nil
	return type(code) == 'string' and code ~= '' and code or nil
end

--- Plain lowercase key for a system name: trailing " System" stripped. This
--- key drives BOTH the filter query and result selection; it is URL-encoded
--- only where it enters the endpoint.
--- @param name string|nil
--- @return string|nil
local function plainKey(name)
	-- One suffix-stripper: p.systemShortName owns the ' System' handling (and
	-- trims); this is just its lowercased form for the filter[name] URL key.
	local short = p.systemShortName(name)
	return short and short:lower() or nil
end

--- The row for a plain key from a filter[name] result list. filter[name] is a
--- substring match, so short names can return several rows: prefer the exact
--- name, then the Xi'an "<name> (<alias>)" form, then the first row.
--- @param results table
--- @param key string
--- @return table|nil
local function pickStarsystem(results, key)
	for _, row in ipairs(results) do
		if type(row.name) == 'string' and row.name:lower() == key then
			return row
		end
	end
	for _, row in ipairs(results) do
		if type(row.name) == 'string' and row.name:lower():sub(-(#key + 2)) == '(' .. key .. ')' then
			return row
		end
	end
	return results[1]
end

--- Statuses where the ARK has not published a survey: M (UEE Military
--- Classified, the Vanduul-held systems) and N (probe data incomplete).
--- @type table<string, boolean>
local UNPUBLISHED_SURVEY = { M = true, N = true }

--- Drop the ARK's withheld-survey aggregate, which is a stub rather than a set
--- of measurements. Every unpublished system with no catalogued bodies carries
--- the *same* block — the twelve Vanduul systems all report population 1.08 and
--- economy 0.12 with a size of 0, 1 or 7, and the three incomplete-probe systems
--- report straight zeros. One value repeated across twelve systems is a template
--- default, not twelve measurements, so none of it may reach the infobox or the store:
--- left alone these pages claim a 7 AU extent and a 0.1/10 economy for space
--- nobody has surveyed, and store a `System size` that satisfies a "smaller than
--- N AU" query.
---
--- The test is "no catalogued bodies AND the survey is unpublished" rather than
--- the tempting shorter ones, both of which are wrong on live data:
---   * `size <= 0` misses the four stubs that report 1 or 7 AU.
---   * "no bodies" alone would strip Gurzil, which is published with no bodies
---     and a real 4.2 AU extent.
---   * status alone would strip Caliban (5.89), Orion (5), Virgil (16) and
---     Oretani (36.91), which are unpublished but properly catalogued.
--- Stars are deliberately excluded from the body count: the stub block claims one
--- star, so counting it would disable the rule entirely. A zero size is dropped
--- unconditionally as well — it is never a measurement, whatever the status. An
--- editorial `|size=` override still wins wherever an editor knows better.
---
--- @param record table|nil starmap record; mutated in place
--- @return table|nil record the same record, for call chaining
local function normalizeAggregates(record)
	local aggregated = type(record) == 'table' and record.aggregated or nil
	if type(aggregated) ~= 'table' then
		return record
	end
	if (tonumber(aggregated.size) or 0) <= 0 then
		aggregated.size = nil
	end
	local bodies = (tonumber(aggregated.planets) or 0)
		+ (tonumber(aggregated.moons) or 0)
		+ (tonumber(aggregated.stations) or 0)
	if bodies == 0 and UNPUBLISHED_SURVEY[record.status] then
		aggregated.size = nil
		aggregated.population = nil
		aggregated.economy = nil
	end
	return record
end

--- Attach the starmap celestial-object record as apiData.celestialobject: the
--- JumpPoint leaf's enrich. The bridge key is the editor-supplied starmap
--- code (the leaf reads it from its manifest entry); no code, no fetch.
--- Soft-fails: on a fetch error or an empty result the record stays absent
--- and the infobox renders what it has.
---
--- @param apiData table
--- @param code string|nil
--- @param includeJumpPoints boolean|nil
--- @return table apiData
function p.attachCelestialObject(apiData, code, includeJumpPoints)
	if type(code) ~= 'string' or code == '' then
		return apiData
	end
	-- `include=starsystem` names the object's system authoritatively, which is
	-- the only reliable way to get it: the code's own first segment is a code,
	-- not a name, and starsystems' filter[name] does not accept codes (KYUKYA,
	-- RILA, THUSUNG and KAPARI all miss). The included record is compact
	-- ({ id, code, name }) — the zone and aggregate fields live on the full
	-- starsystems record that attachStarsystem fetches.
	-- locale rides the endpoint, NOT `params`: Apiunto appends params as
	-- `?query`, which after an endpoint that already carries `?include=` would
	-- produce a second `?` and corrupt the include value.
	local data = api.fetchApi({
		name = 'StarCitizenWikiAPI',
		endpoint = includeJumpPoints and 'celestial-objects/%s?include=starsystem,jumppoints&locale=en_EN'
			or 'celestial-objects/%s?include=starsystem&locale=en_EN',
		responseDataPath = 'data',
	}, code)
	if type(data) == 'table' and next(data) ~= nil then
		apiData.celestialobject = data
	end
	return apiData
end

--- Attach the starmap star-system record as apiData.starsystem: the
--- StarSystem leaf's enrich, for SolarSystem records (uuid path) and for
--- kind-declared lore pages (the editorial fork, apiData empty). Soft-fails:
--- on a fetch error or an empty result the record stays absent and the
--- infobox renders what it has.
---
--- `name`, when given, names the system outright and wins over every heuristic
--- in p.subjectName. A leaf whose subject is NOT the system must pass it:
--- for a planet or moon `apiData.name` is the body's own name, so the default
--- chain would look up a system called "Hurston" and attach nothing.
--- @param apiData table
--- @param args table|nil
--- @param name string|nil explicit system name
--- @return table apiData
function p.attachStarsystem(apiData, args, name)
	local key = plainKey(name or p.subjectName(apiData, args))
	if not key then
		return apiData
	end
	-- locale rides the endpoint, NOT `params`: Apiunto appends params as
	-- `?query`, which after an endpoint that already carries `?filter[…]`
	-- produces a second `?` that corrupts the include value.
	local data = api.fetchApi({
		name = 'StarCitizenWikiAPI',
		endpoint = 'starsystems?filter[name]=%s&include=celestialObjects&locale=en_EN',
		responseDataPath = 'data',
	}, mw.uri.encode(key, 'QUERY'))
	if type(data) == 'table' and data[1] ~= nil then
		apiData.starsystem = normalizeAggregates(pickStarsystem(data, key))
	end
	return apiData
end

--- The ARK starmap code carried by an attached celestial-object record, else
--- the raw |starmapcode=/|code= arg the fetch would have used — so a page
--- whose fetch soft-failed still gets the button and metadata row keyed by the
--- code the editor supplied. Shared by the two leaves that bridge by code
--- (JumpPoint, Star); the empty case is rejected once, here.
--- @param apiData table
--- @param fallback string|nil the raw starmap-code arg
--- @return string|nil
function p.celestialStarmapCode(apiData, fallback)
	local celestial = type(apiData.celestialobject) == 'table' and apiData.celestialobject or nil
	local code = celestial and celestial.code or nil
	if type(code) == 'string' and code ~= '' then
		return code
	end
	return type(fallback) == 'string' and fallback ~= '' and fallback or nil
end

-- Test-only exports. Not part of the public API.
p._internal = {
	plainKey = plainKey,
	pickStarsystem = pickStarsystem,
	normalizeAggregates = normalizeAggregates,
}

return p
Cookies helfen uns bei der Bereitstellung dieses Wikis. Durch die Nutzung des Star Citizen Wiki erklärst du dich damit einverstanden, dass wir Cookies speichern.