@roxyapi/ui 0.51.2 → 0.51.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/components-catalog.json +153 -153
  2. package/dist/cdn/components/data.js +4 -4
  3. package/dist/cdn/components/data.js.map +4 -4
  4. package/dist/cdn/components/endpoint-form.js +1 -1
  5. package/dist/cdn/components/endpoint-form.js.map +1 -1
  6. package/dist/cdn/components/gematria.js +1 -1
  7. package/dist/cdn/components/gematria.js.map +2 -2
  8. package/dist/cdn/components/guna-milan.js +1 -1
  9. package/dist/cdn/components/guna-milan.js.map +2 -2
  10. package/dist/cdn/components/mayan-day-sign.js +1 -1
  11. package/dist/cdn/components/mayan-day-sign.js.map +2 -2
  12. package/dist/cdn/roxy-ui.js +52 -52
  13. package/dist/cdn/roxy-ui.js.map +4 -4
  14. package/dist/components/data.d.ts +10 -33
  15. package/dist/components/data.d.ts.map +1 -1
  16. package/dist/components/data.js +1 -1
  17. package/dist/components/data.js.map +4 -4
  18. package/dist/components/endpoint-form.js +1 -1
  19. package/dist/components/endpoint-form.js.map +1 -1
  20. package/dist/components/gematria.js +1 -1
  21. package/dist/components/gematria.js.map +2 -2
  22. package/dist/components/guna-milan.js +1 -1
  23. package/dist/components/guna-milan.js.map +2 -2
  24. package/dist/components/mayan-day-sign.js +1 -1
  25. package/dist/components/mayan-day-sign.js.map +2 -2
  26. package/dist/index.cjs +81 -81
  27. package/dist/index.cjs.map +4 -4
  28. package/dist/index.js +76 -76
  29. package/dist/index.js.map +4 -4
  30. package/dist/styles/themes/practitioner.css +5 -5
  31. package/dist/utils/stacked-table.d.ts.map +1 -1
  32. package/dist/version.d.ts +1 -1
  33. package/package.json +1 -1
  34. package/src/components/data.ts +85 -94
  35. package/src/styles/themes/practitioner.css +5 -5
  36. package/src/utils/stacked-table.ts +2 -0
  37. package/src/version.ts +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/components/gematria.ts", "../../src/utils/base-element.ts", "../../src/generated/api-languages.ts", "../../src/i18n/lang.ts", "../../src/i18n/localized-element.ts", "../../src/utils/string.ts", "../../src/i18n/registry.ts", "../../src/i18n/locale-controller.ts", "../../src/utils/base-styles.ts", "../../src/utils/compact.ts", "../../src/utils/key-guard.ts", "../../src/utils/fetch-controller.ts", "../../src/utils/interp-accordion.ts", "../../src/utils/disclosure.ts", "../../src/utils/markup-data.ts", "../../src/utils/format.ts", "../../src/utils/localized.ts", "../../src/utils/stacked-table.ts"],
4
- "sourcesContent": ["import { css, html, nothing } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport type { CalculateGematriaResponse } from '../types/index.js';\nimport { RoxyDataElement } from '../utils/base-element.js';\nimport { baseStyles } from '../utils/base-styles.js';\nimport { formatInteger } from '../utils/format.js';\nimport { displayField, displayOption } from '../utils/localized.js';\nimport { stackedTableStyles } from '../utils/stacked-table.js';\nimport { humanize } from '../utils/string.js';\n\ntype Gematria = CalculateGematriaResponse;\ntype HebrewForm = NonNullable<Gematria['hebrewForms']>[number];\ntype CipherValue = NonNullable<Gematria['values']>[number];\n\n/**\n * Gematria calculator. Pass `data` from POST /kabbalah/gematria.\n *\n * @remarks\n * **Hebrew is written right to left and the letter strip has to be laid out that way, or the\n * breakdown contradicts the word above it.** The response lists letters in string order, so the\n * strip carries `dir=\"rtl\"` and the first letter takes the RIGHTMOST tile. Each tile is `dir=\"ltr\"`\n * inside, because the letter name and its number are Latin and read the other way, and `lang=\"he\"`\n * marks the GLYPH rather than the strip, so a host page picks a Hebrew face for the letter and not\n * for the transliteration beside it. A final form scores differently under the finals reading, so it\n * is tinted AND keyed under the strip: a tint with a hover title is no marker on a touch screen.\n *\n * **Every candidate spelling is shown, because that is the whole answer.** A Latin name has more\n * than one defensible Hebrew spelling, one is chosen for the totals, and a calculator that hides the\n * others is asking to be trusted rather than checked. The chosen one is marked and the rule that\n * chose it is printed beside it.\n *\n * **A cipher with no computed value is left out of the table rather than shown as a zero or a blank.**\n * One catalogued cipher carries a null value on every response, and an absent number and the number\n * zero are different answers: printing it as either would publish a total nobody calculated, and\n * printing a placeholder on every response would be a row that never says anything.\n *\n * `hide-readings` keeps the spellings, every cipher value, the per letter breakdown, the\n * substitutions, the Latin ciphers and the equal-value words with their meanings. Only what the\n * tradition SAYS about an equality goes, which is the one interpretive sentence on the card.\n */\n@customElement('roxy-gematria')\nexport class RoxyGematria extends RoxyDataElement<Gematria> {\n\tstatic styles = [\n\t\tbaseStyles,\n\t\tstackedTableStyles,\n\t\tcss`.card{background:var(--roxy-surface,#fff);color:var(--roxy-fg,#0a0a0a);border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-md,8px);padding:var(--roxy-space-lg,1.5rem);box-shadow:var(--roxy-shadow-sm);gap:var(--roxy-space-md,1rem);grid-template-columns:minmax(0,1fr);display:grid}.head{justify-items:start;gap:.15rem;min-width:0;display:grid}.title{font-size:var(--roxy-text-lg,1.125rem);font-weight:var(--roxy-weight-bold,600);letter-spacing:var(--roxy-tracking-tight);margin:0}.hebrew{font-size:2rem;line-height:1.4;font-weight:var(--roxy-weight-bold,600)}.roman{font-size:var(--roxy-text-sm,.875rem);color:var(--roxy-secondary,#475569);letter-spacing:.04em}.rule{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);line-height:var(--roxy-leading-normal,1.5);margin:0}.lbl{color:var(--roxy-muted,#71717a);font-size:var(--roxy-text-xs,.75rem);text-transform:uppercase;letter-spacing:.06em;font-weight:var(--roxy-weight-bold,600);margin-right:.35rem}.src{margin-inline-start:.35rem}.block-title{margin:0 0 var(--roxy-space-sm,.5rem);font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);font-weight:var(--roxy-weight-bold,600);text-transform:uppercase;letter-spacing:.06em}.letters{flex-wrap:wrap;gap:.35rem;display:flex}.letter{border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-sm,4px);justify-items:center;gap:.1rem;min-width:3rem;padding:.3rem .45rem;display:grid}.letter .glyph{font-size:var(--roxy-text-lg,1.125rem);line-height:1.3}.letter .name{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-secondary,#475569)}.letter .num{font-size:var(--roxy-text-xs,.75rem);font-variant-numeric:tabular-nums;color:var(--roxy-fg,#0a0a0a);font-weight:var(--roxy-weight-bold,600)}.letter.is-final{background:color-mix(in srgb, var(--roxy-accent,#f59e0b) 12%, var(--roxy-surface,#fff))}.legend{margin:var(--roxy-space-sm,.5rem) 0 0;font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a)}.legend .swatch{vertical-align:middle;border:1px solid var(--roxy-border,#e4e4e7);background:color-mix(in srgb, var(--roxy-accent,#f59e0b) 12%, var(--roxy-surface,#fff));border-radius:2px;width:10px;height:10px;margin-right:4px;display:inline-block}.scroll{min-width:0;overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:var(--roxy-text-sm,.875rem)}th,td{text-align:left;border-bottom:1px solid var(--roxy-border,#e4e4e7);vertical-align:top;padding:.35rem .5rem}th{color:var(--roxy-muted,#71717a);font-size:var(--roxy-text-xs,.75rem);text-transform:uppercase;letter-spacing:.06em;white-space:nowrap}td.num{font-variant-numeric:tabular-nums;white-space:nowrap}.provenance{margin:var(--roxy-space-sm,.5rem) 0 0;font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);line-height:var(--roxy-leading-normal,1.5)}.lineage{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-secondary,#475569);white-space:normal;margin:.15rem 0 0}a{color:var(--roxy-accent-ink,#b45309)}.forms{gap:var(--roxy-space-md,1rem);margin:0;padding:0;list-style:none;display:grid}.form{border-top:1px solid var(--roxy-border,#e4e4e7);padding-top:var(--roxy-space-sm,.5rem);gap:.35rem;min-width:0;display:grid}.form:first-child{border-top:0;padding-top:0}.chosen{border-radius:var(--roxy-radius-sm,4px);font-size:var(--roxy-text-xs,.75rem);background:color-mix(in srgb, var(--roxy-success,#16a34a) 12%, var(--roxy-surface,#fff));color:var(--roxy-fg,#0a0a0a);padding:.1rem .4rem;display:inline-block}.match-note{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-secondary,#475569);white-space:normal;margin:.15rem 0 0}`,\n\t];\n\n\tprotected renderData(d: Gematria) {\n\t\tconst locale = this.effectiveLang();\n\t\tconst chosen = d.chosen;\n\t\tconst input = d.input?.text ?? d.input?.textHebrew ?? '';\n\t\treturn html`<article class=\"card\" part=\"card\" aria-labelledby=\"gematria-title\"><header class=\"head\" part=\"header\"><h2 class=\"title\" id=\"gematria-title\">${input ? `${this.t('Gematria')} · ${input}` : this.t('Gematria')}</h2>${\n\t\t\t\t\tchosen?.hebrew\n\t\t\t\t\t\t? html`<span class=\"hebrew\" lang=\"he\" dir=\"rtl\">${chosen.hebrew}</span>`\n\t\t\t\t\t\t: nothing\n\t\t\t\t} ${\n\t\t\t\t\tthis.chosenForm(d)?.romanization\n\t\t\t\t\t\t? html`<span class=\"roman\">${this.chosenForm(d)?.romanization}</span>`\n\t\t\t\t\t\t: nothing\n\t\t\t\t} ${chosen?.rule ? html`<p class=\"rule\">${chosen.rule}</p>` : nothing}</header>${this.renderLetters(locale, this.chosenForm(d)?.letters)} ${this.renderValues(locale, d.values, this.t('Cipher values'))} ${this.renderForms(locale, d)} ${this.renderTransformations(locale, d.transformations)} ${this.renderLatin(locale, d.latinValues)} ${this.renderMatches(locale, d.matches)} ${this.renderConventions(d.conventions)}</article>`;\n\t}\n\n\t/** The spelling the totals were taken from, matched back to the form that carries its letters. */\n\tprivate chosenForm(d: Gematria): HebrewForm | undefined {\n\t\tconst forms = d.hebrewForms ?? [];\n\t\treturn forms.find((f) => f.hebrew === d.chosen?.hebrew) ?? forms[0];\n\t}\n\n\t/**\n\t * The per letter breakdown of the chosen spelling.\n\t *\n\t * @remarks\n\t * `dir=\"rtl\"` on the strip is the correctness half: the response lists letters in string order and\n\t * Hebrew reads right to left, so without it the first letter would sit where a reader looks for\n\t * the last. Each tile is `dir=\"ltr\"` so its Latin name and number are not reordered with it.\n\t */\n\tprivate renderLetters(\n\t\tlocale: string | undefined,\n\t\tletters: HebrewForm['letters'] | undefined,\n\t) {\n\t\tconst rows = letters ?? [];\n\t\tif (rows.length === 0) return nothing;\n\t\treturn html`<section part=\"section letters\"><h3 class=\"block-title\">${this.t('Letters')}</h3><div class=\"letters\" part=\"chart\" dir=\"rtl\">${rows.map(\n\t\t\t\t\t(l) => html`<div class=\"${`letter${l.isFinal ? ' is-final' : ''}`}\" dir=\"ltr\" title=\"${ifDefined(l.isFinal ? this.t('Final form') : undefined)}\"><span class=\"glyph\" lang=\"he\">${l.glyph ?? ''}</span> <span class=\"name\">${l.name ?? ''}</span> <span class=\"num\">${formatInteger(locale, l.value)}</span></div>`,\n\t\t\t\t)}</div>${\n\t\t\t\t// A tint plus a hover title is no marker at all on a phone, so the key is\n\t\t\t\t// drawn whenever a final form is on the strip and never when none is.\n\t\t\t\trows.some((l) => l.isFinal)\n\t\t\t\t\t? html`<p class=\"legend\" part=\"legend\"><span class=\"swatch\"></span>${this.t('Final form')}</p>`\n\t\t\t\t\t: nothing\n\t\t\t}</section>`;\n\t}\n\n\t/** Every cipher applied to one spelling, with the provenance the whole block shares beneath it. */\n\tprivate renderValues(\n\t\tlocale: string | undefined,\n\t\tvalues: Gematria['values'] | undefined,\n\t\theading: string,\n\t) {\n\t\t// A cipher this API does not compute carries a null value, which is not a\n\t\t// zero and not a blank, so the row is dropped rather than given a number.\n\t\tconst rows = (values ?? []).filter((v) => typeof v.value === 'number');\n\t\tif (rows.length === 0) return nothing;\n\t\t// The spec says a second published total is present only where the cipher is\n\t\t// not single valued, so the column is drawn on presence for the same reason a\n\t\t// null cipher is dropped: a column that says nothing on every row is not data.\n\t\tconst alternates = rows.some((v) => (v.alternateValues ?? []).length > 0);\n\t\treturn html`<section part=\"section values\"><h3 class=\"block-title\">${heading}</h3><div class=\"scroll\"><table><thead><tr><th>${this.t('Cipher')}</th><th>${this.t('Value')}</th>${alternates ? html`<th>${this.t('Also published')}</th>` : nothing}</tr></thead><tbody>${rows.map(\n\t\t\t\t\t\t\t(v) => html`<tr><td>${humanize(v.id ?? '')}</td><td class=\"num\">${formatInteger(locale, v.value)}</td>${\n\t\t\t\t\t\t\t\t\talternates\n\t\t\t\t\t\t\t\t\t\t? html`<td class=\"num\">${(v.alternateValues ?? [])\n\t\t\t\t\t\t\t\t\t\t\t\t.map((n) => formatInteger(locale, n))\n\t\t\t\t\t\t\t\t\t\t\t\t.join(', ')}</td>`\n\t\t\t\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t\t\t\t}</tr>`,\n\t\t\t\t\t\t)}</tbody></table></div>${this.renderProvenance(rows)}</section>`;\n\t}\n\n\t/** The distinct tradition and source behind a block of ciphers, once rather than on every row. */\n\tprivate renderProvenance(rows: readonly CipherValue[]) {\n\t\tconst seen = new Map<string, string | undefined>();\n\t\tfor (const r of rows) {\n\t\t\tif (r.tradition && !seen.has(r.tradition))\n\t\t\t\tseen.set(r.tradition, r.source);\n\t\t}\n\t\tif (seen.size === 0) return nothing;\n\t\treturn html`<p class=\"provenance\"><span class=\"lbl\">${this.t('Tradition')}</span> ${[...seen].map(\n\t\t\t\t([tradition, source], i) =>\n\t\t\t\t\thtml`${i > 0 ? ' · ' : ''}${humanize(tradition)}${\n\t\t\t\t\t\tsource\n\t\t\t\t\t\t\t? html`<a class=\"src\" href=\"${source}\" target=\"_blank\" rel=\"noopener noreferrer\">${this.t('Source')}</a>`\n\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t}`,\n\t\t\t)}</p>`;\n\t}\n\n\t/**\n\t * Every Hebrew spelling the input can be written as.\n\t *\n\t * @remarks\n\t * Rendered only when there is a choice to show. One spelling is not a set of candidates, and a\n\t * heading over a single row that repeats the word already at the top of the card reads as a bug.\n\t */\n\tprivate renderForms(locale: string | undefined, d: Gematria) {\n\t\tconst forms = d.hebrewForms ?? [];\n\t\tif (forms.length < 2) return nothing;\n\t\treturn html`<section part=\"section spellings\"><h3 class=\"block-title\">${this.t('Spellings')}</h3><ul class=\"forms\">${forms.map(\n\t\t\t\t\t(f) => html`<li class=\"form\"><div><span class=\"hebrew\" lang=\"he\" dir=\"rtl\">${f.hebrew ?? ''}</span> ${\n\t\t\t\t\t\t\t\tf.hebrew === d.chosen?.hebrew\n\t\t\t\t\t\t\t\t\t? html`<span class=\"chosen\">${this.t('Chosen')}</span>`\n\t\t\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t\t\t}</div><span class=\"roman\">${f.romanization ?? ''}</span> ${f.rule ? html`<p class=\"rule\">${f.rule}</p>` : nothing} ${this.renderFormTotals(locale, f)}</li>`,\n\t\t\t\t)}</ul></section>`;\n\t}\n\n\t/** The standard reading of one candidate spelling, which is what a reader compares the spellings on. */\n\tprivate renderFormTotals(\n\t\tlocale: string | undefined,\n\t\tform: HebrewForm,\n\t): unknown {\n\t\tconst first = (form.values ?? []).find((v) => typeof v.value === 'number');\n\t\tif (!first) return nothing;\n\t\treturn html`<p class=\"rule\"><span class=\"lbl\">${humanize(first.id ?? '')}</span> ${formatInteger(locale, first.value)}</p>`;\n\t}\n\n\t/** AtBash and Albam: the substituted word and what it scores. */\n\tprivate renderTransformations(\n\t\tlocale: string | undefined,\n\t\trows: Gematria['transformations'] | undefined,\n\t) {\n\t\tconst table = rows ?? [];\n\t\tif (table.length === 0) return nothing;\n\t\treturn html`<section part=\"section substitutions\"><h3 class=\"block-title\">${this.t('Substitutions')}</h3><div class=\"scroll\"><table><thead><tr><th>${this.t('Cipher')}</th><th>${this.t('Output')}</th><th>${this.t('Value')}</th></tr></thead><tbody>${table.map(\n\t\t\t\t\t\t\t(r) => html`<tr><td>${humanize(r.id ?? '')}</td><td>${r.output ? html`<span lang=\"he\" dir=\"rtl\">${r.output}</span>` : nothing} ${r.outputRomanization ? html`<span class=\"roman\">${r.outputRomanization}</span>` : nothing}</td><td class=\"num\">${formatInteger(locale, r.value)}</td></tr>`,\n\t\t\t\t\t\t)}</tbody></table></div></section>`;\n\t}\n\n\t/**\n\t * The Latin alphabet ciphers.\n\t *\n\t * @remarks\n\t * Each carries its own lineage sentence and it is kept: it says where the cipher comes from, which\n\t * is what stops a Renaissance Christian or modern cipher being read as a rabbinic one. That is a\n\t * fact about the column rather than a claim about the word, so it is data.\n\t */\n\tprivate renderLatin(\n\t\tlocale: string | undefined,\n\t\trows: Gematria['latinValues'] | undefined,\n\t) {\n\t\tconst table = rows ?? [];\n\t\tif (table.length === 0) return nothing;\n\t\treturn html`<section part=\"section latin-ciphers\"><h3 class=\"block-title\">${this.t('Latin ciphers')}</h3><div class=\"scroll\"><table class=\"stacked\"><thead><tr><th>${this.t('Cipher')}</th><th>${this.t('Value')}</th><th>${this.t('Tradition')}</th></tr></thead><tbody>${table.map(\n\t\t\t\t\t\t\t(r) => html`<tr><td data-label=\"${this.t('Cipher')}\">${humanize(r.id ?? '')} ${r.lineage ? html`<p class=\"lineage\">${r.lineage}</p>` : nothing}</td><td class=\"num\" data-label=\"${this.t('Value')}\">${formatInteger(locale, r.value)}</td><td data-label=\"${this.t('Tradition')}\">${humanize(r.tradition ?? '')}</td></tr>`,\n\t\t\t\t\t\t)}</tbody></table></div></section>`;\n\t}\n\n\t/** Curated words whose standard value equals the chosen spelling. */\n\tprivate renderMatches(\n\t\tlocale: string | undefined,\n\t\trows: Gematria['matches'] | undefined,\n\t) {\n\t\tconst table = rows ?? [];\n\t\tif (table.length === 0) return nothing;\n\t\treturn html`<section part=\"section matches\"><h3 class=\"block-title\">${this.t('Equal values')}</h3><div class=\"scroll\"><table class=\"stacked\"><thead><tr><th>${this.t('Word')}</th><th>${this.t('Meaning')}</th><th>${this.t('Value')}</th></tr></thead><tbody>${table.map(\n\t\t\t\t\t\t\t(m) => html`<tr><td data-label=\"${this.t('Word')}\"><span lang=\"he\" dir=\"rtl\">${m.hebrew ?? ''}</span> <span class=\"roman\">${m.romanization ?? ''}</span></td><td data-label=\"${this.t('Meaning')}\">${m.meaning ?? ''} ${\n\t\t\t\t\t\t\t\t\t\tm.note && !this.hideReadings\n\t\t\t\t\t\t\t\t\t\t\t? html`<p class=\"match-note\" part=\"reading\">${m.note}</p>`\n\t\t\t\t\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t\t\t\t\t}</td><td class=\"num\" data-label=\"${this.t('Value')}\">${formatInteger(locale, m.value)}</td></tr>`,\n\t\t\t\t\t\t)}</tbody></table></div></section>`;\n\t}\n\n\t/**\n\t * The switches this answer was computed under.\n\t *\n\t * @remarks\n\t * Provenance rather than decoration, the same reason a Vedic chart names its frame: the name\n\t * mispar gadol is used for two different methods, and a total printed without saying which one\n\t * produced it cannot be reconciled against any other calculator.\n\t */\n\tprivate renderConventions(conventions: Gematria['conventions'] | undefined) {\n\t\tconst locale = this.effectiveLang();\n\t\t// Both switches are REQUEST fields, so the published field-label payload\n\t\t// already names each one and each of its options in the reader's language.\n\t\t// Reading it is what stops a second translation of the same choice.\n\t\tconst pairs: Array<[string, string]> = [];\n\t\tfor (const key of ['transliteration', 'misparGadol'] as const) {\n\t\t\tconst value = conventions?.[key];\n\t\t\tif (!value) continue;\n\t\t\tpairs.push([\n\t\t\t\tdisplayField(locale, key),\n\t\t\t\tdisplayOption(locale, key, value),\n\t\t\t]);\n\t\t}\n\t\tif (pairs.length === 0) return nothing;\n\t\treturn html`<p class=\"provenance\">${pairs.map(\n\t\t\t\t([label, value], i) =>\n\t\t\t\t\thtml`${i > 0 ? ' · ' : ''}<span class=\"lbl\">${label}</span>${value}`,\n\t\t\t)}</p>`;\n\t}\n}\n\ndeclare global {\n\tinterface HTMLElementTagNameMap {\n\t\t'roxy-gematria': RoxyGematria;\n\t}\n}\n", "import {\n\ttype ComplexAttributeConverter,\n\ttype CSSResultGroup,\n\thtml,\n\tnothing,\n\ttype PropertyValues,\n} from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport type { ChromeString } from '../i18n/chrome-strings.js';\nimport { apiLang } from '../i18n/lang.js';\nimport { RoxyLocalizedElement } from '../i18n/localized-element.js';\nimport { baseStyles } from './base-styles.js';\nimport { expandCompact } from './compact.js';\nimport {\n\ttype ApiIssue,\n\tapiFetch,\n\tbuildRequest,\n\tFetchController,\n\ttype RoxyRequest,\n} from './fetch-controller.js';\nimport {\n\ttype InterpSection,\n\trenderInterpAccordion,\n} from './interp-accordion.js';\nimport { MarkupDataController } from './markup-data.js';\n\n/**\n * Read the `submit-context` attribute into the object a proxied submit carries.\n *\n * @remarks\n * Hand-written rather than `type: Object`, which resolves malformed JSON to `null` in silence: a page whose context never left has nothing to look at, and the route it was meant for reports only that the value it expected is not there. One warning covers both refusals (unparseable, or parsed to something that is not an object) because both leave the request without a context, which is the fact worth reading.\n */\nconst submitContextConverter: ComplexAttributeConverter<\n\tRecord<string, unknown> | undefined\n> = {\n\tfromAttribute: (value) => {\n\t\tif (value == null) return undefined;\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(value);\n\t\t\tif (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n\t\t\t\treturn parsed as Record<string, unknown>;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Both refusals share the warning below.\n\t\t}\n\t\tconsole.warn(\n\t\t\t'[roxy-ui] submit-context must be a JSON object; sending the request without it.',\n\t\t);\n\t\treturn undefined;\n\t},\n};\n\n/**\n * Shared base for every data-driven Roxy component. Carries once what every component needs, rather than per component, and adds the self-contained, drop-in behavior: controlled-mode hydration, an opt-in self-fetch (form, request, loading, error, empty), the typed `data` slot, and the render switch. A subclass implements one method, {@link RoxyDataElement.renderData}.\n *\n * @remarks\n * Two render modes, one component, which is the whole drop-in contract:\n *\n * - Controlled: a server (WordPress, JSX SSR, static HTML) fetches the response and injects it as a direct-child `<script type=\"application/json\" class=\"roxy-data\">`. {@link MarkupDataController} hydrates `data` from it on connect. No key reaches the browser. This is the path the WordPress plugin drives, and it is unchanged by the base class.\n * - Uncontrolled: no data is injected, but a `data-endpoint` and a `pk_` `publishable-key` are set. The component renders its own `<roxy-endpoint-form>` (an internal detail, never placed by the consumer), and on submit fetches through {@link FetchController}, which refuses any non-publishable key. The result populates `data` and the component renders it.\n *\n * The JavaScript `data` property always wins over markup, so a host that assigns `el.data = …` after upgrade is authoritative.\n *\n * A list component can open one of its rows in place: it declares {@link RoxyDataElement.rowDetail} (the element that draws one row and the path that fetches it) and calls {@link RoxyDataElement.openRow} on a pick. In self-fetch mode the base creates that element, hands it the key and the settings this element already holds, and {@link RoxyDataElement.load}s the row into it, so a hosted embed completes the flow with no host code. In controlled mode nothing is created and the pick reaches the host as the same `roxy-symbol-select` event it always sent, because the host holds the key and owns the navigation.\n *\n * Self-fetch needs `<roxy-endpoint-form>` (and `<roxy-location-search>`) registered. The CDN bundle and the full `@roxyapi/ui` entry register everything; per-component ESM consumers that want self-fetch import the form component too.\n *\n * Two things every subclass inherits for the host page to shape the render from outside the shadow root, with no JavaScript: the `hide-readings` attribute ({@link RoxyDataElement.hideReadings}), and the `part` names on the base's own branches (`form`, `loading`, `error`, `empty`, `edit-bar`, `attribution`). A component adds `part` to its own structural blocks, drawn from the published part vocabulary.\n *\n * Translation is inherited rather than defined here: `t()`, `translator` and `effectiveLang()` live on {@link RoxyLocalizedElement}, which the two declared widgets extend as well, so the form a visitor fills and the card it produces read the same catalogue.\n *\n * @example\n * ```ts\n * @customElement('roxy-dream-card')\n * export class RoxyDreamCard extends RoxyDataElement<GetDreamSymbolResponse> {\n * static styles = [baseStyles, css`.card { … }`];\n * protected renderData(d: GetDreamSymbolResponse) {\n * return html`<article class=\"card\">…</article>`;\n * }\n * }\n * ```\n */\nexport abstract class RoxyDataElement<\n\tT = unknown,\n> extends RoxyLocalizedElement {\n\tstatic styles: CSSResultGroup = [baseStyles];\n\n\t/** Typed RoxyAPI response. Assigned in JavaScript, hydrated from the roxy-data island, or set by a self-fetch. */\n\t@property({ attribute: false })\n\tdata: T | null = null;\n\n\t/** Endpoint path for self-fetch, e.g. \"astrology/natal-chart\" or \"dreams/symbols/{id}\". Empty disables self-fetch (controlled mode only). */\n\t@property({ type: String, attribute: 'data-endpoint' })\n\tendpoint = '';\n\n\t/** HTTP method for self-fetch. */\n\t@property({ type: String })\n\tmethod: 'GET' | 'POST' = 'POST';\n\n\t/** Browser-safe publishable key (pk_) for self-fetch. A secret key is refused client-side. */\n\t@property({ type: String, attribute: 'publishable-key' })\n\tpublishableKey?: string;\n\n\t/** Override the API origin for self-hosted or proxied deployments. Absolute, or relative to the page for a same-origin route. */\n\t@property({ type: String, attribute: 'base-url' })\n\tbaseUrl?: string;\n\n\t/** Override the OpenAPI spec URL the self-fetch form introspects. */\n\t@property({ type: String, attribute: 'spec-url' })\n\tspecUrl?: string;\n\n\t/** Consumer backend route that proxies the request (holds the secret key). When set, self-fetch POSTs the request here instead of calling RoxyAPI directly, so no key reaches the browser. The server-rendered (WordPress) path. */\n\t@property({ type: String, attribute: 'submit-url' })\n\tsubmitUrl?: string;\n\n\t/**\n\t * Data the host page chooses, as a JSON object, sent to the {@link RoxyDataElement.submitUrl} route as `context` beside the request. The place a page attaches its own verification data to a proxied submission.\n\t *\n\t * @remarks\n\t * Shapeless by design and never read here: the component parses the attribute, hands the object to the request, and leaves every key of it to the page and the route that answers it. Nothing is sent when it is unset, when the JSON does not parse, and when it parses to anything but an object, so a route written before this existed goes on receiving exactly the request it always did.\n\t *\n\t * It rides the proxy path only. A direct call with a `publishable-key` sends what the endpoint declares, so setting this without a `submit-url` does nothing.\n\t *\n\t * @example\n\t * ```html\n\t * <roxy-natal-chart\n\t * data-endpoint=\"astrology/natal-chart\"\n\t * submit-url=\"/api/roxy/proxy\"\n\t * submit-context='{\"token\":\"...\"}'\n\t * ></roxy-natal-chart>\n\t * ```\n\t */\n\t@property({ attribute: 'submit-context', converter: submitContextConverter })\n\tsubmitContext?: Record<string, unknown>;\n\n\t/**\n\t * Where the self-fetch form's city search sends its request, absolute or relative to the page.\n\t *\n\t * @remarks\n\t * The companion of {@link RoxyDataElement.submitUrl}, and it is separate because the two requests have different shapes: the proxy route takes one POSTed `{ path, method, body, query }`, while the city search is a GET the search issues on its own while a visitor types. A birth-data form makes both, so a page that routes its API traffic through its own server names that route here as well. It is forwarded to the internal form, which forwards it to the search; unset, the search keeps its own default.\n\t */\n\t@property({ type: String, attribute: 'location-url' })\n\tlocationUrl?: string;\n\n\t/** Persist the last self-fetch form values in sessionStorage (keyed by endpoint) and prefill the form on reload. */\n\t@property({ type: Boolean })\n\tremember = false;\n\n\t/**\n\t * Render the chart and the data, and omit the written interpretation. Off by default, so a component that does not set it is byte-identical to before.\n\t *\n\t * @remarks\n\t * The suppressed content is the prose an endpoint returns ABOUT the result: the interpretation accordion, the interpretive paragraphs, and the keyword chips that belong to them. Everything a practitioner reads the numbers off stays: wheels, tables, grids, legends, pills, counts and dates. The reading is dropped from the DOM rather than hidden with CSS, so a page that publishes the chart alone never ships the prose it is not showing.\n\t *\n\t * Set it when the page supplies its own words, which is the common case for a practitioner site that wants the graphic under its own writing.\n\t */\n\t@property({ type: Boolean, attribute: 'hide-readings', reflect: true })\n\thideReadings = false;\n\n\t/**\n\t * Remove named structural blocks from this component, as a comma-separated list of `part` names.\n\t *\n\t * @remarks\n\t * The sibling of {@link RoxyDataElement.hideReadings} and deliberately a different tool. `hide-readings` drops the PROSE an endpoint returns about a result; this drops a whole block whatever it contains, which is what a page wants when the block is measurement rather than writing. Hiding the chart-pattern list on a teaching page is the case it exists for: a T-square is data, so `hide-readings` leaves it standing on purpose.\n\t *\n\t * Any name in `components-catalog.json` works, on any component that publishes it, because the rule is generated from the name rather than from a list of components that opted in. A name no block carries costs nothing and hides nothing.\n\t *\n\t * **This hides with CSS, it does not remove from the DOM, and the difference is the reason both exist.** A part name is a rendering concern the base can act on generically; whether a block is prose is a question only the component can answer. So a page that must not SHIP the words uses `hide-readings`, and a page that just should not SHOW a block uses this.\n\t *\n\t * @example\n\t * ```html\n\t * <roxy-natal-chart hide-sections=\"patterns\"></roxy-natal-chart>\n\t * <roxy-natal-chart hide-sections=\"patterns, aspects\"></roxy-natal-chart>\n\t * <roxy-natal-chart data-endpoint=\"astrology/natal-chart\" hide-sections=\"hint\"></roxy-natal-chart>\n\t * ```\n\t */\n\t@property({ type: String, attribute: 'hide-sections', reflect: true })\n\thideSections = '';\n\n\t/** Override the self-fetch form's submit-button label. Empty derives one from the endpoint. */\n\t@property({ type: String, attribute: 'submit-label' })\n\tsubmitLabel?: string;\n\n\t/** The host page's own words for a failed self-fetch the API did not word (a dropped connection, a body with no message); a failure the API explains reads as the API worded it. */\n\t@property({ type: String, attribute: 'error-message' })\n\terrorMessage?: string;\n\n\t/** Render a small \"Spiritual data by RoxyAPI\" credit under a self-fetch or auto-mount result. Off by default; any value except \"off\"/\"false\" enables it. The one-tag widgets script forwards data-attribution as this attribute. Never shown in controlled mode. */\n\t@property({ type: String })\n\tattribution?: string;\n\n\t/** True while an uncontrolled self-fetch is in flight. Public so {@link FetchController} can drive it. */\n\t@state()\n\tloading = false;\n\n\t/** Message from a failed self-fetch, or null. Public so {@link FetchController} can drive it. */\n\t@state()\n\terror: string | null = null;\n\n\t/** The fields a rejected self-fetch named, or null. Public so {@link FetchController} can drive it; the form prints each under its input. */\n\t@state()\n\tissues: ApiIssue[] | null = null;\n\n\t/**\n\t * True once a self-fetch (not a consumer-assigned or island-hydrated `data`) produced the current result. It gates the interactive result affordances, so controlled mode never shows an Edit control or a sticky picker.\n\t */\n\t@state()\n\tprivate selfFetched = false;\n\n\t/** True when the visitor asked to edit a self-fetch result, so the form is restored over the result. */\n\t@state()\n\tprivate editing = false;\n\n\t/** True when the last self-fetch form stays above its result (a sole choice, or a form that opened on load), so a change refetches under it. */\n\t@state()\n\tprivate sticky = false;\n\n\t/** Last submitted form values (nested per group), kept in memory to restore the form on Edit and to prefill the sticky picker. */\n\tprivate lastValues?: Record<string, unknown>;\n\n\tprivate fetcher: FetchController<T>;\n\n\t/** The element that draws one row of this list and the path that fetches it, `{id}` standing for the picked row. Declared by a list component; absent on everything else, so {@link openRow} is a no-op there. */\n\tprotected rowDetail?: { tag: string; path: string };\n\n\t/** The opened row, or undefined until a pick. A list component renders it under its rows, inside its own `part=\"detail\"` block, so the name is scanned onto that component and not onto every card the base draws. */\n\t@state()\n\tprotected openedRow?: RoxyDataElement;\n\n\t/** The id of the opened row, so a list can mark the picked tile. */\n\t@state()\n\tprotected openedRowId?: string;\n\n\t/** The response key a list draws its rows from (`symbols`, `crystals`, `cards`); declared by a list component so the base can page it with {@link renderMore}. */\n\tprotected listKey?: string;\n\n\t/** The request behind the data this element fetched for itself, kept so a list can ask for the page after it. */\n\tprivate lastRequest?: RoxyRequest;\n\n\t/** True while the next page of a list is in flight. */\n\t@state()\n\tprivate moreLoading = false;\n\n\t/** Message from a failed next-page read, printed under the button that asked for it. */\n\t@state()\n\tprivate moreError: string | null = null;\n\n\tconstructor() {\n\t\tsuper();\n\t\t// Controlled mode: hydrate `data` from a direct-child roxy-data island when\n\t\t// no JS property was assigned. Keyless; the server already fetched.\n\t\tnew MarkupDataController<T>(this);\n\t\tthis.fetcher = new FetchController<T>(this);\n\t}\n\n\tprotected willUpdate(changed: PropertyValues): void {\n\t\t// A result asked for in compact form arrives with its same-shaped arrays\n\t\t// columnar, so it is decoded once here and every component goes on\n\t\t// rendering the plain shape. `expandCompact` hands back the same object\n\t\t// when nothing is encoded, so an ordinary response is neither copied nor\n\t\t// re-rendered, and Lit records a property set here inside the update in\n\t\t// progress rather than scheduling another one.\n\t\tif (changed.has('data') && this.data != null) {\n\t\t\tconst expanded = expandCompact(this.data);\n\t\t\tif (expanded !== this.data) this.data = expanded;\n\t\t}\n\t\tif (\n\t\t\tchanged.has('publishableKey') ||\n\t\t\tchanged.has('baseUrl') ||\n\t\t\tchanged.has('submitUrl') ||\n\t\t\tchanged.has('submitContext')\n\t\t) {\n\t\t\tthis.syncFetcher();\n\t\t}\n\t}\n\n\t/** Hand the request settings to the controller. Called on any change of them, and by {@link load} before it runs, because a host that sets the properties and loads in the same tick has not been through an update yet. */\n\tprivate syncFetcher(): void {\n\t\tthis.fetcher.publishableKey = this.publishableKey;\n\t\tif (this.baseUrl) this.fetcher.baseUrl = this.baseUrl;\n\t\tthis.fetcher.submitUrl = this.submitUrl;\n\t\tthis.fetcher.submitContext = this.submitContext;\n\t}\n\n\trender(): unknown {\n\t\treturn html`${this.hiddenSectionsStyle()}${this.renderState()}`;\n\t}\n\n\t/**\n\t * A bespoke card that throws while drawing a response degrades to the generic renderer instead of a dead skeleton.\n\t *\n\t * @remarks\n\t * A response the card was not written for (a sibling endpoint's shape, a field the spec grew) reaches `renderData` as data the type system cannot check at runtime, and a render that throws leaves whatever was on screen before it, which for a self-fetch is the loading placeholder, forever. The library already promises that an endpoint nothing draws falls back to `<roxy-data>`, so a card that cannot draw falls back the same way: the visitor reads the response as a table, the page hears `roxy-render-error` with the exception, and the console names the element. When the generic renderer is not registered (a per-component import), the empty state stands in.\n\t */\n\tprivate drawn(data: T): unknown {\n\t\ttry {\n\t\t\treturn this.renderData(data);\n\t\t} catch (err) {\n\t\t\tconsole.warn(\n\t\t\t\t`[roxy-ui] ${this.localName} could not draw its response`,\n\t\t\t\terr,\n\t\t\t);\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('roxy-render-error', {\n\t\t\t\t\tdetail: { error: err },\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tcomposed: true,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn customElements.get('roxy-data')\n\t\t\t\t? html`<roxy-data .data=\"${data}\" lang=\"${ifDefined(this.effectiveLang())}\"></roxy-data>`\n\t\t\t\t: this.renderEmpty();\n\t\t}\n\t}\n\n\t/**\n\t * The one rule set that acts on {@link RoxyDataElement.hideSections}, generated from the names rather than from a list of components.\n\t *\n\t * @remarks\n\t * `[part~=\"name\"]` is the selector because `part` is a space-separated list: the natal chart's aspect grid carries `section aspects table aspect-grid`, so a `~=` match reaches it by any one of its names while `=` would reach it by none. It is emitted INSIDE the shadow root, which is the only place a rule can see a `part` attribute on the element that declares it.\n\t *\n\t * Names are filtered to the same `[a-z][a-z0-9-]*` shape the catalog and the WordPress setting both use, so nothing a page passes can close the rule or inject a second one. An unknown name compiles to a selector that matches nothing, which is why there is no validation error and no list of legal names to keep in sync.\n\t *\n\t * A `<style>` element in the template rather than a static stylesheet, because static styles are evaluated once and shared across every instance, so two charts on one page could not hide different blocks. Lit supports per-instance style elements; the documented cost is a re-parse when the expression changes, which is irrelevant here because the value is set once from a page attribute and effectively never changes after that.\n\t *\n\t * **`!important` is load-bearing and is not a shortcut around specificity.** Lit puts static `styles` in `adoptedStyleSheets`, and the scoping spec applies those AFTER any `<style>` element inside the same shadow root, so an in-tree rule loses to the component's own stylesheet at equal specificity no matter how it is written. Measured: `patterns` is a bare `section` with no declared display and hid correctly without it, while `legend` carries `display:flex` from the static sheet and stayed visible. The WordPress site-wide rule needs no `!important` for the opposite reason, that an outer-tree `::part()` rule already outranks anything inside.\n\t */\n\tprivate hiddenSectionsStyle(): unknown {\n\t\tconst names = this.hideSections\n\t\t\t.split(',')\n\t\t\t.map((n) => n.trim().toLowerCase())\n\t\t\t.filter((n) => /^[a-z][a-z0-9-]*$/.test(n));\n\t\tif (names.length === 0) return nothing;\n\t\t// The second selector reaches a part the self-fetch form forwards through `exportparts`.\n\t\tconst rules = names\n\t\t\t.map(\n\t\t\t\t(n) =>\n\t\t\t\t\t`[part~=\"${n}\"],roxy-endpoint-form::part(${n}){display:none!important}`,\n\t\t\t)\n\t\t\t.join('');\n\t\treturn html`<style>${rules}</style>`;\n\t}\n\n\t/** The state machine every render goes through, split out so {@link render} can pair it with the per-instance rules above. */\n\tprivate renderState(): unknown {\n\t\tif (this.endpoint && this.sticky && this.selfFetched && !this.editing)\n\t\t\treturn this.renderWithForm(this.stickyBody());\n\t\tif (this.loading) return this.renderLoading();\n\t\tif (this.error != null) return this.renderError(this.error);\n\t\tif (this.data != null) {\n\t\t\t// Controlled mode (consumer-assigned or island-hydrated data) renders the\n\t\t\t// result alone, byte-identical to before: no picker, no Edit. The one\n\t\t\t// exception is the widgets auto-mount attrs-complete path, which assigns\n\t\t\t// data directly AND sets `attribution`; a real controlled consumer never\n\t\t\t// sets the attribute, so this stays byte-identical for them.\n\t\t\tif (!this.selfFetched) {\n\t\t\t\treturn this.showAttribution()\n\t\t\t\t\t? html`${this.drawn(this.data)}${this.renderAttribution()}`\n\t\t\t\t\t: this.drawn(this.data);\n\t\t\t}\n\t\t\tif (this.editing) return this.renderForm();\n\t\t\treturn this.renderResult(this.data);\n\t\t}\n\t\treturn this.renderNoData();\n\t}\n\n\t/** Render the populated response. The single method every component implements. */\n\tprotected abstract renderData(data: T): unknown;\n\n\t/**\n\t * The interpretation accordion, gated by {@link RoxyDataElement.hideReadings}. Every component that shows a written reading routes through here instead of calling {@link renderInterpAccordion} directly.\n\t *\n\t * @remarks\n\t * The gate lives on the base rather than in each component because the property does, and a plain render function cannot read component state. One call site per accordion, one place that decides whether prose renders, and the section it emits carries the same `readings` part in every component.\n\t *\n\t * Prose that is NOT in an accordion (a summary paragraph, a per-item interpretation) is still the component's own to gate, since only the component knows which of its blocks are readings.\n\t *\n\t * @param heading - English source copy, translated here. Typed as {@link ChromeString} so the compiler, not a reviewer, rejects a heading no catalogue carries.\n\t */\n\tprotected renderInterpretation(\n\t\tsections: InterpSection[],\n\t\tname: string,\n\t\theading?: ChromeString,\n\t): unknown {\n\t\tif (this.hideReadings) return nothing;\n\t\t// Localized HERE rather than in the accordion: that is a plain render\n\t\t// function with no host, so it cannot read a language, and this is the one\n\t\t// call site every component routes through.\n\t\treturn renderInterpAccordion(sections, name, this.t(heading ?? 'Reading'));\n\t}\n\n\t/** A self-fetch result under a compact Edit control that restores the form with the previous values. */\n\tprotected renderResult(data: T): unknown {\n\t\tconst body = html`<div class=\"roxy-edit-bar\" part=\"edit-bar\"><button type=\"button\" class=\"roxy-edit\" @click=\"${this.onEdit}\">${this.t('Edit query')}</button></div>${this.drawn(data)}`;\n\t\treturn this.showAttribution()\n\t\t\t? html`${body}${this.renderAttribution()}`\n\t\t\t: body;\n\t}\n\n\t/** The form with what stands under it, from ONE call site, so the form element and the choices it read survive every refetch of a form that stays above its result. */\n\tprivate renderWithForm(body: unknown): unknown {\n\t\treturn html`${this.renderForm()}${body}`;\n\t}\n\n\t/** What a form that stays above its result shows under it: the skeleton while a refetch is in flight, the failure, or the result. */\n\tprivate stickyBody(): unknown {\n\t\tif (this.loading) return this.renderLoading();\n\t\tif (this.error != null)\n\t\t\treturn this.issues ? nothing : this.renderErrorBanner(this.error);\n\t\tif (this.data == null) return nothing;\n\t\treturn this.showAttribution()\n\t\t\t? html`${this.drawn(this.data)}${this.renderAttribution()}`\n\t\t\t: this.drawn(this.data);\n\t}\n\n\t/**\n\t * The next page of a list this element fetched for itself, appended under its rows: a list component places it after its rows, and it draws nothing in controlled mode, once every row is in, or for a response that reports no total.\n\t */\n\tprotected renderMore(): unknown {\n\t\tconst rows = this.listRows();\n\t\tconst total = (this.data as { total?: unknown } | null)?.total;\n\t\tif (!this.lastRequest || !rows || typeof total !== 'number') return nothing;\n\t\tif (rows.length >= total) return nothing;\n\t\treturn html`<div class=\"roxy-more\" part=\"more\"><button type=\"button\" class=\"roxy-edit\" ?disabled=\"${this.moreLoading}\" aria-busy=\"${this.moreLoading ? 'true' : 'false'}\" @click=\"${this.onMore}\">${this.t('Show more')}</button> ${this.moreError ? html`<p class=\"roxy-error\" role=\"alert\">${this.t(this.moreError)}</p>` : nothing}</div>`;\n\t}\n\n\t/** The rows of a list response, or undefined when this element is not a list or the response has none. */\n\tprivate listRows(): unknown[] | undefined {\n\t\tconst rows = this.listKey\n\t\t\t? (this.data as Record<string, unknown> | null)?.[this.listKey]\n\t\t\t: undefined;\n\t\treturn Array.isArray(rows) ? rows : undefined;\n\t}\n\n\tprivate onMore = async () => {\n\t\tconst req = this.lastRequest;\n\t\tconst key = this.listKey;\n\t\tconst rows = this.listRows();\n\t\tif (!req || !key || !rows) return;\n\t\tthis.moreLoading = true;\n\t\tthis.moreError = null;\n\t\ttry {\n\t\t\tconst next = await apiFetch<Record<string, unknown>>(this.fetcher, {\n\t\t\t\t...req,\n\t\t\t\tquery: { ...req.query, offset: rows.length },\n\t\t\t});\n\t\t\t// A new search replaced the list while this page was in flight; it belongs to the old one.\n\t\t\tif (this.lastRequest !== req) return;\n\t\t\tconst added = next[key];\n\t\t\tthis.data = {\n\t\t\t\t...(this.data as Record<string, unknown>),\n\t\t\t\t...next,\n\t\t\t\t[key]: [...rows, ...(Array.isArray(added) ? added : [])],\n\t\t\t} as T;\n\t\t} catch (err) {\n\t\t\tif (this.lastRequest === req)\n\t\t\t\tthis.moreError = err instanceof Error ? err.message : String(err);\n\t\t} finally {\n\t\t\tthis.moreLoading = false;\n\t\t}\n\t};\n\n\t/** Start a request that REPLACES the data: the row a previous list opened and the page state it reached belong to the old data, so they go with it. */\n\tprivate fetchFresh(req: RoxyRequest): Promise<void> {\n\t\tthis.lastRequest = req;\n\t\tthis.openedRow = undefined;\n\t\tthis.openedRowId = undefined;\n\t\tthis.moreError = null;\n\t\treturn this.fetcher.run(req);\n\t}\n\n\tprivate onEdit = () => {\n\t\tthis.editing = true;\n\t};\n\n\t/**\n\t * Fetch one request into this element from a host that already holds the key. The result renders as assigned data (no form, no edit bar), which is what a list component needs when it opens one of its rows in place, and the key guard is the same one every self-fetch passes through: a secret key is refused before anything is sent.\n\t */\n\tload(req: RoxyRequest): Promise<void> {\n\t\tthis.syncFetcher();\n\t\treturn this.fetchFresh(req);\n\t}\n\n\t/** A visitor picked a row of this list: emit `roxy-symbol-select` with it for a host that pairs its own detail, then open it here when this element can fetch. */\n\tprotected pickRow(detail: { id: string } & Record<string, unknown>): void {\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent('roxy-symbol-select', {\n\t\t\t\tdetail,\n\t\t\t\tbubbles: true,\n\t\t\t\tcomposed: true,\n\t\t\t}),\n\t\t);\n\t\tthis.openRow(detail.id);\n\t}\n\n\t/**\n\t * Open one row of this list in place. Only when this element can fetch for itself, a publishable key or a proxy route; a controlled host receives the select event and owns the navigation, so the DOM it was given stays byte-identical. The detail element is created once and reused across picks, carries the key, origin, proxy, section and reading switches and language of this element, and asks the API for the row in the language of the page.\n\t */\n\tprotected openRow(id: string): void {\n\t\tif (!this.rowDetail || !(this.publishableKey || this.submitUrl)) return;\n\t\tconst el =\n\t\t\tthis.openedRow ??\n\t\t\t(document.createElement(this.rowDetail.tag) as RoxyDataElement);\n\t\tel.publishableKey = this.publishableKey;\n\t\tel.baseUrl = this.baseUrl;\n\t\tel.submitUrl = this.submitUrl;\n\t\tel.submitContext = this.submitContext;\n\t\tel.hideReadings = this.hideReadings;\n\t\tel.hideSections = this.hideSections;\n\t\tconst lang = this.effectiveLang();\n\t\tif (lang) el.setAttribute('lang', lang);\n\t\tthis.openedRow = el;\n\t\tthis.openedRowId = id;\n\t\tvoid el\n\t\t\t.load({\n\t\t\t\tpath: `/${this.rowDetail.path.replace('{id}', encodeURIComponent(id))}`,\n\t\t\t\tmethod: 'GET',\n\t\t\t\tquery: { lang: apiLang(this) },\n\t\t\t})\n\t\t\t// The card lands under the whole list, so a tile picked near the top of a\n\t\t\t// phone would otherwise open it out of sight. Nearest keeps a visible card still.\n\t\t\t.then(() => el.scrollIntoView?.({ block: 'nearest' }));\n\t}\n\n\t/** True when the attribution credit renders: the attribute is present and not explicitly disabled. */\n\tprivate showAttribution(): boolean {\n\t\treturn (\n\t\t\tthis.attribution != null &&\n\t\t\tthis.attribution !== 'off' &&\n\t\t\tthis.attribution !== 'false'\n\t\t);\n\t}\n\n\t/** Small muted credit under a self-fetch or auto-mount result. Reached only from the result path, so controlled mode never renders it. */\n\tprotected renderAttribution(): unknown {\n\t\treturn html`<div class=\"roxy-attribution\" part=\"attribution\"><a href=\"https://roxyapi.com/?utm_source=widget&utm_medium=embed\" target=\"_blank\" rel=\"noopener\">${this.t('Spiritual data by RoxyAPI')}</a></div>`;\n\t}\n\n\t/** The data-absent branch: the self-fetch form when an endpoint is set, otherwise the empty state. */\n\tprotected renderNoData(): unknown {\n\t\treturn this.endpoint ? this.renderWithForm(nothing) : this.renderEmpty();\n\t}\n\n\t/**\n\t * Internal self-fetch form. Reuses the introspecting `<roxy-endpoint-form>`; the consumer never places it.\n\t *\n\t * @remarks\n\t * `exportparts` forwards exactly one inner name, `hint`, so the same `::part(hint)` rule works whether the page places the form itself or runs a component in self-fetch mode. The rest of the form parts stay inside: this element is an internal detail, and a name is forwarded only when hiding or restyling that block is a decision a host page makes about ITS page rather than about our form. Field help is that case, because the text is API reference prose and a page written for a client wants its own words or none.\n\t */\n\tprotected renderForm(): unknown {\n\t\treturn html`<roxy-endpoint-form part=\"form\" exportparts=\"hint\" data-endpoint=\"${this.endpoint}\" method=\"${this.method}\" spec-url=\"${ifDefined(this.specUrl)}\" publishable-key=\"${ifDefined(this.publishableKey)}\" location-url=\"${ifDefined(this.locationUrl)}\" submit-label=\"${ifDefined(this.submitLabel)}\" lang=\"${ifDefined(this.effectiveLang())}\" .initialValues=\"${this.formInitialValues()}\" .serverIssues=\"${this.issues}\" .apiRoute=\"${this.fetcher}\" .autoload=\"${!this.selfFetched}\" .fullPages=\"${!!this.listKey}\" @roxy-submit=\"${this.onFormSubmit}\"></roxy-endpoint-form>`;\n\t}\n\n\t/** Prefill source for the form: the last submission (Edit / sticky refetch) wins over remembered storage. */\n\tprivate formInitialValues(): Record<string, unknown> | undefined {\n\t\treturn (\n\t\t\tthis.lastValues ?? (this.remember ? this.readRemembered() : undefined)\n\t\t);\n\t}\n\n\tprivate onFormSubmit = (e: Event) => {\n\t\tconst detail = (e as CustomEvent).detail as {\n\t\t\tvalues: Record<string, unknown>;\n\t\t\tqueryKeys?: string[];\n\t\t\tsticky?: boolean;\n\t\t};\n\t\tthis.lastValues = detail.values;\n\t\tthis.sticky = !!detail.sticky;\n\t\tthis.selfFetched = true;\n\t\tthis.editing = false;\n\t\tif (this.remember) this.writeRemembered(detail.values);\n\t\tvoid this.fetchFresh(\n\t\t\tbuildRequest(\n\t\t\t\tthis.endpoint,\n\t\t\t\tthis.method,\n\t\t\t\tdetail.values,\n\t\t\t\tdetail.queryKeys ?? [],\n\t\t\t),\n\t\t);\n\t};\n\n\t/** sessionStorage key for this component's remembered form values, scoped by endpoint. */\n\tprivate rememberKey(): string {\n\t\treturn `roxy-ui:form:${this.endpoint}`;\n\t}\n\n\tprivate readRemembered(): Record<string, unknown> | undefined {\n\t\ttry {\n\t\t\tconst raw = sessionStorage.getItem(this.rememberKey());\n\t\t\treturn raw ? (JSON.parse(raw) as Record<string, unknown>) : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate writeRemembered(values: Record<string, unknown>): void {\n\t\ttry {\n\t\t\tsessionStorage.setItem(this.rememberKey(), JSON.stringify(values));\n\t\t} catch {\n\t\t\t// Private mode / disabled storage: remembering is best-effort, never fatal.\n\t\t}\n\t}\n\n\t/** Terminal empty state: one translated message for every component, addressable as `::part(empty)`. Override only where an empty state must DO something a message cannot. */\n\tprotected renderEmpty(): unknown {\n\t\treturn html`<div class=\"roxy-empty\" role=\"status\" part=\"empty\">${this.t('No data')}</div>`;\n\t}\n\n\t/** Loading placeholder shown during a self-fetch. */\n\tprotected renderLoading(): unknown {\n\t\treturn html`<div class=\"roxy-skeleton\" style=\"height:8rem\" role=\"status\" aria-label=\"${this.t('Loading')}\" part=\"loading\"></div>`;\n\t}\n\n\t/**\n\t * Error state shown when a self-fetch fails. Keeps the form in view so the request can be retried.\n\t *\n\t * The message goes through `t()` because the key refusal messages that reach here are ours: `KEY_REFUSALS` (`utils/key-guard.ts`), which {@link FetchController} assigns when a site owner leaves a secret or sample key in a browser page, and which `<roxy-location-search>` and the form render in their own shadow roots from the same constants. Translating it in one place and not the other would put two languages on one page. Everything else that lands here is a wire fact (an HTTP status, a browser network error), misses the catalogue and renders unchanged.\n\t */\n\tprotected renderError(message: string): unknown {\n\t\t// A rejected request that names its fields is answered on the form, field by\n\t\t// field, and needs no banner repeating the same words over it.\n\t\tif (this.endpoint && this.issues) return this.renderForm();\n\t\tconst banner = this.renderErrorBanner(message);\n\t\treturn this.endpoint ? html`${banner}${this.renderForm()}` : banner;\n\t}\n\n\t/** The failure line: the message the request failed with, or the host page's own {@link errorMessage} in place of a failure the API did not word. */\n\tprivate renderErrorBanner(message: string): unknown {\n\t\treturn html`<div class=\"roxy-error\" role=\"alert\" part=\"error\">${(!this.fetcher.worded && this.errorMessage) || this.t(message)}</div>`;\n\t}\n}\n", "// Generated by scripts/sync-bindings.ts (the `lang` query enum in specs/openapi.json). Do not edit.\n\n/**\n * Every language tag the API accepts on `?lang=`.\n *\n * @remarks\n * A self-fetch resolves the site language from the DOM, which means ANY value a\n * host page happens to carry can reach the query string. The API rejects an\n * unlisted tag with a 400, so a page in a language we do not translate would\n * stop working the moment the language chain was completed. Membership is\n * checked against this list before `lang` is sent, and a miss simply omits the\n * parameter, leaving the endpoint on its English default.\n */\nexport const API_LANGUAGES: readonly string[] = [\"de\",\"en\",\"es\",\"fr\",\"hi\",\"pt\",\"ru\",\"tr\",\"zh-Hans\",\"zh-Hant\"];\n", "/**\n * Where a component's language comes from, and what is safe to send to the API.\n *\n * @remarks\n * Two different answers, and conflating them is the whole reason this file is separate from the catalogue:\n *\n * - {@link resolveLang} answers \"what language is this PAGE in\", and keeps the full tag, because `es-AR` is a legitimate thing for a catalogue to want to differ on.\n * - {@link apiLang} answers \"what may go on the query string\", which is a narrower question with a hard edge: `?lang=es-AR` is a 400, `?lang=es` is a 200.\n *\n * The full tag is not a nicety the catalogue happens to tolerate: `utils/format.ts` hands it to `Intl`, which reads the region and writes `15 de ene de 1990` for `es-AR` where it writes `15 ene 1990` for `es`. Passing the API answer to a formatter demotes every regional visitor to the base language and nothing fails, so the two values are never interchangeable.\n */\n\nimport { API_LANGUAGES } from '../generated/api-languages.js';\n\n/**\n * The site-owner language for an element, resolved through the four-link chain the revamp design specifies.\n *\n * @remarks\n * 1. the element's own `lang` attribute (the explicit per-embed override),\n * 2. the nearest ancestor carrying `lang`, so one wrapper localizes a whole section,\n * 3. `document.documentElement.lang`, which is what makes this work on a real CMS with no markup change at all: WordPress emits `<html lang=\"es-AR\">` on every page of a Spanish site,\n * 4. nothing, which the callers read as English.\n *\n * All four links matter: with only the first, a component on a fully Spanish page renders English chrome and the only remedy is hand-editing every embed.\n *\n * `navigator.language` is deliberately NOT in the chain. It is the VISITOR's preference, not the site's: it fragments the API cache across every locale a visitor might carry and silently serves two people different content from the same URL.\n *\n * Link 2 uses `closest`, which stops at a shadow boundary. A component composed INSIDE another component's shadow root therefore cannot see the host page, which is why every composing component forwards `lang` to its children explicitly.\n */\nexport function resolveLang(el: HTMLElement): string | undefined {\n\t// Native accessor, never a Lit @property: declaring one would shadow\n\t// HTMLElement.lang and break the platform attribute for every consumer.\n\tif (el.lang) return el.lang;\n\tif (typeof document === 'undefined') return undefined;\n\tconst inherited = el.closest?.('[lang]')?.getAttribute('lang');\n\tif (inherited) return inherited;\n\treturn document.documentElement.lang || undefined;\n}\n\n/**\n * Which script a Chinese page is written in, read off the region it names.\n *\n * @remarks\n * Chinese is the one language the API keys by SCRIPT rather than by language alone, because `zh`\n * on its own does not say which of the two a reader can actually read. Real pages almost never\n * write the script: a Taiwanese site writes `zh-TW` and a mainland site writes `zh-CN`, which is\n * what the region-to-script correspondence every internationalisation library ships is for.\n * Without this step both of those degrade to English, which takes the whole Chinese audience off\n * the domains the API answers in Chinese at all.\n *\n * A bare `zh` with neither region nor script resolves to nothing on purpose: guessing a script for\n * a reader who did not name one picks characters half of them cannot read.\n */\nconst ZH_SCRIPT_BY_REGION: Readonly<Record<string, string>> = {\n\ttw: 'hant',\n\thk: 'hant',\n\tmo: 'hant',\n\tcn: 'hans',\n\tsg: 'hans',\n\tmy: 'hans',\n};\n\n/** The API's own spelling of a tag, matched case-insensitively, or undefined when it serves no such language. */\nfunction asApiLang(tag: string): string | undefined {\n\tconst wanted = tag.toLowerCase();\n\treturn API_LANGUAGES.find((l) => l.toLowerCase() === wanted);\n}\n\n/**\n * The value safe to put on `?lang=`, or `undefined` to leave the request on the API default.\n *\n * @remarks\n * Three steps, and the order is load-bearing the moment {@link resolveLang} starts reading `<html lang>`:\n *\n * - **A tag the API serves goes as it is**, matched without regard to case, so `zh-Hant` and `ZH-HANT` both send the spelling the API declares. This comes first because the next step would throw away the very subtag those tags are identified by.\n * - **Chinese resolves its script**, from an explicit script subtag or from the region ({@link ZH_SCRIPT_BY_REGION}), because that is where the language actually lives.\n * - **Everything else drops its region.** A regional tag is a 400, so a Spanish WordPress site would go from English-but-working to broken the day the language chain was completed. `es-AR`, `es-419` and `ES` all send `es`.\n *\n * **An unsupported language is omitted, not sent.** The chain surfaces whatever the host page carries, including languages the API does not translate, and an unlisted tag is the same 400. Omitting it degrades to English, which is the behaviour those pages already had.\n */\nexport function apiLang(el: HTMLElement): string | undefined {\n\tconst tag = resolveLang(el);\n\tif (!tag) return undefined;\n\tconst exact = asApiLang(tag);\n\tif (exact) return exact;\n\tconst parts = tag.toLowerCase().split('-');\n\tconst base = parts[0] as string;\n\tif (base === 'zh') {\n\t\tconst script =\n\t\t\tparts.find((p) => p === 'hans' || p === 'hant') ??\n\t\t\tZH_SCRIPT_BY_REGION[parts[1] ?? ''];\n\t\treturn script ? asApiLang(`zh-${script}`) : undefined;\n\t}\n\treturn asApiLang(base);\n}\n", "import { LitElement } from 'lit';\nimport { resolveLang } from './lang.js';\nimport { LocaleController } from './locale-controller.js';\nimport { translate } from './registry.js';\n\n/**\n * The base every element that writes WORDS extends: it resolves the page language and translates its own chrome.\n *\n * @remarks\n * This is deliberately smaller than {@link RoxyDataElement}, and the split is what makes the widgets translatable at all. `<roxy-endpoint-form>` and `<roxy-location-search>` are the two declared widgets: they fetch, they hold state, and they are NOT data components, so they cannot inherit the data base without dragging its controlled-mode hydration, its self-fetch controller and its own form rendering (which renders the form, so the form inheriting it would compose itself). They extended `LitElement` directly instead, which meant they had no `t()` and no {@link LocaleController}, so a Spanish page rendered a Spanish result card over an English form and neither widget re-rendered when a deferred locale payload landed.\n *\n * So the mechanism lives here ONCE and all three inherit it. There is no second translator, no second registry and no second way to resolve a language: adding one is how a catalogue entry and a call site drift apart.\n *\n * Two costs are why this is its own module rather than a second export of `utils/base-element.ts`. Every `dist/cdn/components/*.js` is a self-contained IIFE, so importing the data base into the city search would compile `FetchController`, `MarkupDataController` and the interpretation accordion into a bundle that uses none of them. And `utils/base-element.ts` imports THIS file, so putting the class there would close a cycle the moment a widget imported it.\n */\nexport abstract class RoxyLocalizedElement extends LitElement {\n\tconstructor() {\n\t\tsuper();\n\t\t// Re-render if a chrome-string catalogue lands after this element upgraded.\n\t\t// A host page loads the payload as its own script tag, so it can arrive\n\t\t// after first paint and there is nothing the site owner could do about it.\n\t\tnew LocaleController(this);\n\t}\n\n\t/**\n\t * The chrome string for this element's language, keyed by its own English source text.\n\t *\n\t * @remarks\n\t * Pass the English copy, never a key. With no catalogue registered the source string is returned unchanged, so an English page pays nothing and a language we do not ship degrades to English rather than to a visible key.\n\t *\n\t * Chrome only. A value the API returned (a planet, a sign, an aspect, a house system) is NOT translated here: it is rendered as the response carries it, so the words on the chart and the words in the response can never disagree. The same holds for a label derived from a spec field NAME through `humanize()`: a catalogue keyed on English source text cannot reach a string computed per response. A derived name is catalogued only where the set it comes from is CLOSED and small enough to enumerate against the spec, which is true of the nine form group names and of nothing else so far.\n\t *\n\t * @example\n\t * ```ts\n\t * this.t('Aspect grid'); // 'Cuadricula de aspectos' under lang=\"es\"\n\t * this.t('{{count}} planets', { count: 12 }); // '12 planetas'\n\t * ```\n\t */\n\tprotected t(source: string, vars?: Record<string, string | number>): string {\n\t\treturn translate(this.effectiveLang(), source, vars);\n\t}\n\n\t/** {@link RoxyLocalizedElement.t} as a value, bound once, for a shared render helper that has no host of its own and therefore cannot resolve a page language (`utils/hd-reading.ts`). Named `translator` and not `translate` because `HTMLElement.translate` is a real DOM property and shadowing it with a protected member makes every `@customElement` decorator in the library fail to typecheck. */\n\tprotected readonly translator = (\n\t\tsource: string,\n\t\tvars?: Record<string, string | number>,\n\t): string => this.t(source, vars);\n\n\t/**\n\t * Site-owner language for this element: the `lang` attribute, the nearest ancestor carrying one, or the document. Protected so a component that composes another can forward it (a child inside this shadow root cannot reach the host page on its own).\n\t *\n\t * Full tag, region included. The truncation to what `?lang=` accepts happens where the request is built, in `<roxy-endpoint-form>`.\n\t */\n\tprotected effectiveLang(): string | undefined {\n\t\treturn resolveLang(this);\n\t}\n}\n", "/**\n * Shared string helpers used across components. Single source of truth so the\n * same formatting rules apply to every key/label/title that surfaces in the\n * shadow tree.\n *\n * - `lookupKey`: the ONE normalizer every lookup table in this library is keyed\n * and read by (`tokens/index.ts` glyphs and abbreviations, `i18n/` chrome\n * strings).\n * - `capitalize`: title-cases the first character, lowercases the rest. A\n * DISPLAY helper only; it is not a lookup key (see `lookupKey`).\n * - `humanize`: turns an API key (`birth_date`, `birthDate`, `mahadasha-end`)\n * into a label suitable for display (\"Birth date\", \"Mahadasha end\").\n */\n\n/**\n * Fold a name to the canonical key its lookup table is stored under: lower case, every run of spaces, underscores and hyphens collapsed to one space, trimmed.\n *\n * @remarks\n * This exists because a GUESSED key spelling is a defect class this repo has now shipped twice. The glyph tables were keyed off whatever {@link capitalize} happened to produce (`North node`), while the API returns `North Node`, so every call site that reached the table without first calling `capitalize` missed and fell through to a fabricated abbreviation. Aspects hit the same wall from the other side: `/aspects` returns `SEMI SEXTILE` where synastry returns `SEMI_SEXTILE`.\n *\n * One normalizer, applied when a table is DEFINED and again when it is READ, removes the whole class: no call site has to remember a convention, and no table has to guess a spelling. Use it for every new table keyed by an API-supplied name.\n *\n * @example\n * ```ts\n * lookupKey('North Node'); // 'north node'\n * lookupKey('SEMI_SEXTILE'); // 'semi sextile'\n * lookupKey('semi-sextile'); // 'semi sextile'\n * ```\n */\nexport function lookupKey(s: string): string {\n\treturn s\n\t\t.toLowerCase()\n\t\t.replace(/[\\s_-]+/g, ' ')\n\t\t.trim();\n}\n\nexport function capitalize(s: string): string {\n\tif (!s) return '';\n\treturn s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();\n}\n\nexport function humanize(s: string): string {\n\treturn (\n\t\ts\n\t\t\t.replace(/[_-]+/g, ' ')\n\t\t\t.replace(/([a-z])([A-Z])/g, '$1 $2')\n\t\t\t// Split a trailing/embedded digit off a word so \"person1\" reads \"Person 1\"\n\t\t\t// and every group legend and field label spaces its ordinal.\n\t\t\t.replace(/([a-z])([0-9])/g, '$1 $2')\n\t\t\t.replace(/^\\w/, (c) => c.toUpperCase())\n\t);\n}\n", "/**\n * The chrome-string catalogue: one resolver reading one registry, so a translation can arrive from anywhere without a component changing.\n *\n * @remarks\n * **The key IS the canonical English string**, folded through {@link lookupKey}. There is no invented key vocabulary to keep in sync with the copy, which is the same rule the glyph tables in `tokens/index.ts` follow (they key off the exact value the API returns). Two consequences that are the whole point:\n *\n * - **English costs zero bytes.** A miss returns the source string, so the English build ships no catalogue at all, and a site that never loads a locale payload is byte-identical to one built before this file existed.\n * - **A missing translation degrades to English, never to a key.** The failure mode of a keyed catalogue is a raw `natal.tabs.wheel` on the page; here the worst case is the English word.\n *\n * **The registry lives on `globalThis`, not in module scope, because it has to.** Every `dist/cdn/components/*.js` is a self-contained IIFE with its own copy of this module, so a `Map` here would be invisible to the second component on the page. One global object, written by the locale payload and read by every bundle, is what makes `dist/cdn/locales/es.js` a single download that translates all of them.\n *\n * Load order is not guaranteed on a real host (WordPress enqueues scripts in an order the plugin does not fully control, and a payload may be deferred), so {@link onLocaleChange} lets an element that has already rendered in English re-render when its catalogue lands.\n */\n\nimport { lookupKey } from '../utils/string.js';\n\n/** Shared mutable state, addressed by a name rather than a module binding so every bundle on the page reaches the same object. */\ninterface LocaleRegistry {\n\t/** Language tag (lower case) to catalogue, keyed by {@link lookupKey} of the English source string. */\n\tcatalogs: Record<string, Record<string, string>>;\n\t/**\n\t * Language tag (lower case) to the API's field-label map: `fields` keyed by wire name,\n\t * `enums` keyed `{fieldName}.{value}`.\n\t *\n\t * A SEPARATE key space from `catalogs` on purpose. A chrome string is keyed by the English\n\t * text a component writes, which is a constant in our source; a field label is keyed by a\n\t * name that only the OpenAPI spec knows, computed per operation, so no catalogue keyed on\n\t * English source text can ever reach it. Same registry because the delivery problem is\n\t * identical (a payload that may land after first paint), so it reuses one global object and\n\t * one listener set rather than growing a second of each.\n\t */\n\tfieldLabels: Record<string, FieldLabels>;\n\t/** Language tags whose fetch is in flight or done, so N forms on a page cost ONE request. */\n\trequested: Set<string>;\n\t/** Elements waiting to re-render when a catalogue arrives. */\n\tlisteners: Set<() => void>;\n}\n\n/** The `/languages/field-labels` payload, minus the echoed `lang`. */\nexport interface FieldLabels {\n\tfields: Record<string, string>;\n\tenums: Record<string, string>;\n}\n\nconst GLOBAL_KEY = '__ROXY_UI_I18N__';\n\nfunction registry(): LocaleRegistry {\n\tconst holder = globalThis as unknown as Record<string, LocaleRegistry>;\n\tconst existing = holder[GLOBAL_KEY];\n\tif (existing) return existing;\n\tconst created: LocaleRegistry = {\n\t\tcatalogs: {},\n\t\tfieldLabels: {},\n\t\trequested: new Set(),\n\t\tlisteners: new Set(),\n\t};\n\tholder[GLOBAL_KEY] = created;\n\treturn created;\n}\n\n/**\n * Publish a catalogue for a language tag and wake every mounted element.\n *\n * @remarks\n * The catalogue is authored keyed by the English source string, exactly as it appears at the call site, and normalized here. That keeps the source file readable and diffable against the component that renders it, while the runtime lookup stays a single property read.\n *\n * This is the ONLY way into the registry, so a catalogue can later come from a static file, a server response, or a host page inlining a script tag, without a component knowing the difference.\n */\nexport function registerLocale(\n\tlang: string,\n\tcatalog: Record<string, string>,\n): void {\n\tconst reg = registry();\n\tconst normalized: Record<string, string> = {};\n\tfor (const [source, translated] of Object.entries(catalog)) {\n\t\tnormalized[lookupKey(source)] = translated;\n\t}\n\treg.catalogs[lang.toLowerCase()] = normalized;\n\tfor (const listener of reg.listeners) listener();\n}\n\n/**\n * Replace `{{name}}` placeholders. Copied from the API-side translator so both sides of the product interpolate identically; an unknown placeholder is left verbatim rather than blanked, so a typo in a catalogue is visible instead of silently eating the value.\n */\nexport function interpolate(\n\ttemplate: string,\n\tvars?: Record<string, string | number>,\n): string {\n\tif (!vars) return template;\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key: string) =>\n\t\tkey in vars ? String(vars[key] ?? '') : match,\n\t);\n}\n\n/**\n * The chrome string for `lang`, falling back to the English `source` it is keyed by.\n *\n * @remarks\n * A regional tag resolves against its base language, so `es-AR` and `es-419` both read the `es` catalogue and a site does not have to know which tags we happen to ship. An exact regional catalogue still wins if one is ever registered.\n */\nexport function translate(\n\tlang: string | undefined,\n\tsource: string,\n\tvars?: Record<string, string | number>,\n): string {\n\treturn interpolate(chromeLabel(lang, source) ?? source, vars);\n}\n\n/** A published chrome label, including translations equal to the source; absent on a miss. */\nexport function chromeLabel(\n\tlang: string | undefined,\n\tsource: string,\n): string | undefined {\n\tif (!lang) return undefined;\n\tconst { catalogs } = registry();\n\tconst tag = lang.toLowerCase();\n\tconst catalog = catalogs[tag] ?? catalogs[tag.split('-')[0] as string];\n\treturn catalog?.[lookupKey(source)];\n}\n\n/**\n * Publish a field-label map for a language tag and wake every mounted element.\n *\n * @remarks\n * Exported so a host that already has the payload (a server-rendered page, a test, a WordPress\n * plugin inlining it) can supply it without a network call, exactly as {@link registerLocale}\n * allows for chrome strings.\n */\nexport function registerFieldLabels(lang: string, labels: FieldLabels): void {\n\tconst reg = registry();\n\treg.fieldLabels[lang.toLowerCase()] = labels;\n\tfor (const listener of reg.listeners) listener();\n}\n\n/**\n * Read the registered field-label payload for `lang`, resolving regional tags against their base.\n *\n * @remarks\n * Shared by browser label lookups and build-time manifest generation after importing the locale\n * modules. Returns `undefined` when no payload is registered, leaving English fallback to callers.\n */\nexport function labelsFor(lang: string | undefined): FieldLabels | undefined {\n\tif (!lang) return undefined;\n\tconst { fieldLabels } = registry();\n\tconst tag = lang.toLowerCase();\n\treturn fieldLabels[tag] ?? fieldLabels[tag.split('-')[0] as string];\n}\n\n/**\n * The label for a request field name, or `undefined` when nothing has been published.\n *\n * @remarks\n * Returning `undefined` rather than the name is deliberate: the caller owns the fallback, which is\n * `humanize()`, and that keeps this resolver honest about what it actually knows. A form renders\n * identically to before until a payload arrives.\n */\nexport function fieldLabel(\n\tlang: string | undefined,\n\tname: string,\n): string | undefined {\n\treturn labelsFor(lang)?.fields[name];\n}\n\n/** The label for one selectable option, keyed `{fieldName}.{value}` as the API publishes it. */\nexport function optionLabel(\n\tlang: string | undefined,\n\tfield: string,\n\tvalue: string,\n): string | undefined {\n\treturn labelsFor(lang)?.enums[`${field}.${value}`];\n}\n\n/** Subscribe to catalogue arrivals. Returns the unsubscribe, so an element can drop it on disconnect. */\nexport function onLocaleChange(listener: () => void): () => void {\n\tconst { listeners } = registry();\n\tlisteners.add(listener);\n\treturn () => {\n\t\tlisteners.delete(listener);\n\t};\n}\n", "import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport { onLocaleChange } from './registry.js';\n\n/**\n * Re-renders its host when a chrome-string catalogue arrives.\n *\n * @remarks\n * Without this the catalogue would have to be on the page BEFORE the elements upgrade, which is not something a component can require of a real host. WordPress orders enqueued scripts by dependency and a site owner can add `defer` to any of them; a CDN embed is two independent `<script src>` tags. Any of those can land the locale payload after the first paint, and the visible result would be a chart that renders in English on a Spanish page for no reason the site owner can see or fix.\n *\n * Mirrors `MarkupDataController`: constructed in {@link RoxyDataElement}'s constructor, subscribes on connect, drops the subscription on disconnect. Registration is idempotent and a re-register of the same language simply re-renders, so a payload loaded twice is harmless.\n */\nexport class LocaleController implements ReactiveController {\n\tprivate readonly host: ReactiveControllerHost;\n\tprivate unsubscribe?: () => void;\n\n\tconstructor(host: ReactiveControllerHost) {\n\t\tthis.host = host;\n\t\thost.addController(this);\n\t}\n\n\thostConnected(): void {\n\t\tthis.unsubscribe = onLocaleChange(() => this.host.requestUpdate());\n\t}\n\n\thostDisconnected(): void {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t}\n}\n", "import { css } from 'lit';\n\n/**\n * Shared host styles every component pulls in. Sets default font, color,\n * container query support, and the entry fade-in.\n */\nexport const baseStyles = css`:host{--roxy-label-col:minmax(0, 25%);--_success-fg:var(--roxy-success-fg,#09632a);--_warning-fg:var(--roxy-warning-fg,#913304);--_danger-fg:var(--roxy-danger-fg,#881313);--_info-fg:var(--roxy-info-fg,#014f7a);font-family:var(--roxy-font-sans,system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif);color:var(--roxy-fg,#0a0a0a);font-size:var(--roxy-text-base,1rem);line-height:var(--roxy-leading-normal,1.5);animation:roxy-fade-in var(--roxy-motion-duration,.2s) var(--roxy-motion-easing,cubic-bezier(.4, 0, .2, 1)) both;background:0 0;display:block;container-type:inline-size}:host([hidden]){display:none}:host([bare]){--roxy-surface:transparent;--roxy-shadow-sm:none;--roxy-shadow-md:none}*,:before,:after{box-sizing:border-box}h1,h2,h3,h4{font-family:var(--roxy-font-display,var(--roxy-font-sans,system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif))}@keyframes roxy-fade-in{0%{transform:translateY(2px)}to{transform:translateY(0)}}@media (prefers-reduced-motion:reduce){:host{animation:none}}.roxy-skeleton{background:linear-gradient(90deg, var(--roxy-border,#e4e4e7) 0%, color-mix(in srgb, var(--roxy-border,#e4e4e7) 60%, transparent) 50%, var(--roxy-border,#e4e4e7) 100%);border-radius:var(--roxy-radius-md,8px);background-size:200% 100%;animation:1.4s ease-in-out infinite roxy-shimmer}@keyframes roxy-shimmer{0%{background-position:200% 0}to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){.roxy-skeleton{animation:none}}.roxy-sr-only{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:0;padding:0;position:absolute;overflow:hidden}.roxy-empty{padding:var(--roxy-space-lg,1.5rem);color:var(--roxy-muted,#71717a);text-align:center;font-size:var(--roxy-text-sm,.875rem)}.roxy-error{gap:var(--roxy-space-sm,.5rem);padding:var(--roxy-space-lg,1.5rem);background:var(--roxy-surface,#fff);border:1px solid var(--roxy-danger,#dc2626);border-radius:var(--roxy-radius-md,8px);color:var(--_danger-fg);font-size:var(--roxy-text-sm,.875rem);justify-items:start;display:grid}:host(:focus-within) .roxy-card{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px}.roxy-attribution{margin-top:var(--roxy-space-sm,.5rem);font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);text-align:right}.roxy-attribution a{color:inherit;text-decoration:none}.roxy-attribution a:hover{color:var(--roxy-accent-ink,#b45309);text-decoration:underline}.roxy-attribution a:focus-visible{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px}.roxy-edit-bar{margin-bottom:var(--roxy-space-sm,.5rem);justify-content:flex-end;display:flex}.roxy-edit{padding:var(--roxy-space-xs,.25rem) var(--roxy-space-md,1rem);border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-md,8px);color:var(--roxy-fg,#0a0a0a);font-family:inherit;font-size:var(--roxy-text-sm,.875rem);cursor:pointer;background:0 0}.roxy-edit:hover{border-color:var(--roxy-accent,#f59e0b);color:var(--roxy-accent-ink,#b45309)}.roxy-edit:focus-visible{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px}.roxy-edit:disabled{cursor:progress;color:var(--roxy-muted,#71717a)}roxy-endpoint-form+*{margin-top:var(--roxy-space-md,1rem)}.roxy-more{justify-items:center;gap:var(--roxy-space-sm,.5rem);margin-top:var(--roxy-space-md,1rem);display:grid}.roxy-more .roxy-edit{min-height:44px}:host{font-variant-emoji:text}`;\n", "const COLS = '__cols';\nconst ROWS = '__rows';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Walk a value, rebuilding only the branches that actually hold an encoded array.\n *\n * @remarks\n * The identity return is the contract, not an optimisation: a response with nothing encoded in it comes back as the same object, so every render path that existed before this decoder sees the exact bytes it always saw.\n */\nfunction decode(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\tlet rebuilt = false;\n\t\tconst out = value.map((item) => {\n\t\t\tconst next = decode(item);\n\t\t\tif (next !== item) rebuilt = true;\n\t\t\treturn next;\n\t\t});\n\t\treturn rebuilt ? out : value;\n\t}\n\tif (!isPlainObject(value)) return value;\n\n\tconst cols = value[COLS];\n\tconst rows = value[ROWS];\n\t// Exactly the two keys and nothing else: a real payload that happens to carry\n\t// a field of either name is left alone.\n\tif (\n\t\tArray.isArray(cols) &&\n\t\tArray.isArray(rows) &&\n\t\tObject.keys(value).length === 2\n\t) {\n\t\treturn rows.map((row) => {\n\t\t\tconst item: Record<string, unknown> = {};\n\t\t\t(cols as string[]).forEach((col, i) => {\n\t\t\t\titem[col] = decode((row as unknown[])[i]);\n\t\t\t});\n\t\t\treturn item;\n\t\t});\n\t}\n\n\tlet rebuilt = false;\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tconst next = decode(item);\n\t\tif (next !== item) rebuilt = true;\n\t\tout[key] = next;\n\t}\n\treturn rebuilt ? out : value;\n}\n\n/**\n * Turn a compact API response back into the plain shape the components render.\n *\n * @remarks\n * Asking a Remote MCP tool for a compact result trades repeated field names for a header: an array of same-shaped objects arrives as `{ __cols: [names], __rows: [[values]] }`, which costs an agent far fewer tokens to read and carries exactly the same data. This is the decoder, applied at every depth, so a compact result renders in a component with nothing else to do.\n *\n * Every data component runs it on the way in, so a page that sets `data` from a tool result needs no call of its own. It is exported for the paths that hold the JSON before an element does.\n *\n * A value with nothing encoded in it is returned unchanged, by reference.\n *\n * @example\n * ```ts\n * expandCompact({ aspects: { __cols: ['a', 'b'], __rows: [['sun', 'moon'], ['sun', 'mars'], ['moon', 'mars']] } });\n * // { aspects: [{ a: 'sun', b: 'moon' }, { a: 'sun', b: 'mars' }, { a: 'moon', b: 'mars' }] }\n * ```\n */\nexport function expandCompact<T>(value: T): T {\n\treturn decode(value) as T;\n}\n", "/**\n * The one place the \"publishable key only\" rule lives. Every client-side fetch boundary ({@link ../components/location-search.ts}, {@link ./fetch-controller.ts}) and the self-fetch form ({@link ../components/endpoint-form.ts}) call through here so a refused key is refused identically: no network call, the same visible message, the same `roxy-validation-error` event. Centralising it is what stops the paths drifting into different answers for the same key, one warning and fetching where another refuses.\n */\n\n/** The sample key every copy-paste snippet ships with; pages that offer a live key input search snippets for this exact string, so changing it breaks them. */\nexport const SAMPLE_PUBLISHABLE_KEY = 'pk_live_YOUR_KEY';\n\n/** Each reason a key is refused: the `roxy-validation-error` detail reason and the English source of the message, translated where it renders. */\nexport const KEY_REFUSALS = {\n\tsecret: {\n\t\treason: 'possible-secret-key',\n\t\tmessage:\n\t\t\t'Client-side components accept a pk_ publishable key only. Use a publishable key with an origin allowlist, or render server-side.',\n\t},\n\tsample: {\n\t\treason: 'sample-key',\n\t\tmessage:\n\t\t\t'Replace the sample key with your own publishable key from your RoxyAPI account.',\n\t},\n} as const;\n\nexport type KeyRefusal = (typeof KEY_REFUSALS)[keyof typeof KEY_REFUSALS];\n\n/** Why a present key may not be sent (a secret or unprefixed key, or the snippet sample no account owns), or undefined when it may, an absent key included. */\nexport function keyRefusal(\n\tkey: string | undefined | null,\n): KeyRefusal | undefined {\n\tif (!key) return undefined;\n\tif (key === SAMPLE_PUBLISHABLE_KEY) return KEY_REFUSALS.sample;\n\treturn key.startsWith('pk_') ? undefined : KEY_REFUSALS.secret;\n}\n\n/** Dispatch the shared bubbling `roxy-validation-error` for a refused key, and log it once when `warn` is set; the caller shows the message and skips the fetch. */\nexport function dispatchKeyRefusal(\n\thost: EventTarget,\n\trefusal: KeyRefusal,\n\topts: { warn?: boolean } = {},\n): void {\n\tif (opts.warn) console.warn(refusal.message);\n\thost.dispatchEvent(\n\t\tnew CustomEvent('roxy-validation-error', {\n\t\t\tdetail: { reason: refusal.reason, message: refusal.message },\n\t\t\tbubbles: true,\n\t\t\tcomposed: true,\n\t\t}),\n\t);\n}\n", "import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport {\n\tdispatchKeyRefusal,\n\ttype KeyRefusal,\n\tkeyRefusal,\n} from './key-guard.js';\n\n/**\n * Host slots the controller drives. {@link RoxyDataElement} satisfies this, so the form mixin can attach a controller without the component wiring state by hand.\n *\n * @remarks\n * Intersected with `HTMLElement` because the controller dispatches events on the host. Lit's `ReactiveControllerHost` is the update-lifecycle contract only (`addController`, `requestUpdate`, `updateComplete`) and carries no DOM surface, even though every real host is a `LitElement` and therefore an `HTMLElement`. Declaring the DOM half is what the controller actually needs, and it is declared rather than reached through a `this.host as unknown as EventTarget` double cast, which would assert a capability the type never promised.\n */\ntype FetchHost<T> = ReactiveControllerHost &\n\tHTMLElement & {\n\t\tdata: T | null;\n\t\tloading: boolean;\n\t\terror: string | null;\n\t\t/** The field-level issues of a rejected request, or null when the failure was not about the request body. */\n\t\tissues: ApiIssue[] | null;\n\t};\n\n/** One field the API rejected, as the API reports it: the wire path of the field (`year`, `person1.date`, `members.0.date`) and the reason. */\nexport interface ApiIssue {\n\tpath: string;\n\tmessage: string;\n}\n\n/** A failed request, read once: the message every failure carries and the per-field issues a validation failure adds. */\ninterface ApiFailure {\n\tmessage: string;\n\tissues: ApiIssue[] | null;\n\t/** False when the body carried no `error` sentence and the message is the status line. */\n\tworded: boolean;\n}\n\n/** The public API root, which a component overrides per instance through its `base-url` attribute; exported so every request names one origin. */\nexport const DEFAULT_BASE_URL = 'https://roxyapi.com/api/v2';\n\n/**\n * Turn a failed `Response` into the message to show: the API's own `{ error }` string when the body carries one, else the status line.\n *\n * @remarks\n * Exported so every client-side fetch boundary renders the same words for the same failure, the way {@link keyRefusal} centralizes the key refusal. A boundary that discards the response body cannot tell a rejected request from an empty result, and renders the two identically.\n */\nexport async function readApiError(res: Response): Promise<string> {\n\treturn (await readApiFailure(res)).message;\n}\n\n/**\n * The failure a response carries.\n *\n * @remarks\n * A rejected request answers `{ error, code, issues }`, and `issues` is what makes the error actionable: each names the field by its wire path, which is the same identity the form keys its inputs by, so the message can sit under the input it is about instead of in a banner quoting a path. Only a `validation_error` carries them; every other failure keeps the message alone.\n */\nasync function readApiFailure(res: Response): Promise<ApiFailure> {\n\ttry {\n\t\tconst body = (await res.json()) as {\n\t\t\terror?: string;\n\t\t\tcode?: string;\n\t\t\tissues?: Array<{ path?: unknown; message?: unknown }>;\n\t\t};\n\t\tif (body?.error) {\n\t\t\tconst issues =\n\t\t\t\tbody.code === 'validation_error' && Array.isArray(body.issues)\n\t\t\t\t\t? body.issues\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(i) =>\n\t\t\t\t\t\t\t\t\ttypeof i.path === 'string' && typeof i.message === 'string',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.map((i) => ({\n\t\t\t\t\t\t\t\tpath: i.path as string,\n\t\t\t\t\t\t\t\tmessage: i.message as string,\n\t\t\t\t\t\t\t}))\n\t\t\t\t\t: null;\n\t\t\treturn {\n\t\t\t\tmessage: body.error,\n\t\t\t\tissues: issues?.length ? issues : null,\n\t\t\t\tworded: true,\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// Non-JSON error body: fall through to the status line.\n\t}\n\treturn {\n\t\tmessage: `Request failed (${res.status})`,\n\t\tissues: null,\n\t\tworded: false,\n\t};\n}\n\n/** A single request the controller issues on the component's behalf. */\nexport interface RoxyRequest {\n\t/** Path under the API base, e.g. \"/dreams/symbols/water\" or \"/astrology/natal-chart\". */\n\tpath: string;\n\tmethod?: 'GET' | 'POST';\n\t/** JSON body for POST endpoints. */\n\tbody?: unknown;\n\t/** Query string parameters; nullish values are dropped. */\n\tquery?: Record<string, string | number | undefined>;\n}\n\n/**\n * Where an element sends its requests: the key it may present, the API origin, and the host route that proxies them.\n *\n * @remarks\n * Every element that fetches holds these four, and {@link apiFetch} is the one function that turns them into a request, so a list that loads its next page, a form that loads its choices and a component that loads its result reach the API, or the host route standing in for it, the same way.\n */\nexport interface ApiRoute {\n\t/** Browser-safe publishable key; anything else is refused before a request is made. */\n\tpublishableKey?: string;\n\t/** API origin, absolute or relative to the page; {@link DEFAULT_BASE_URL} when unset. */\n\tbaseUrl?: string;\n\t/** Host route that holds the secret key. When set, the request is POSTed there as `{ path, method, body, query }` and no key leaves the browser. */\n\tsubmitUrl?: string;\n\t/** Object the host page attaches to a proxied request as `context`, passed through unread. */\n\tsubmitContext?: Record<string, unknown>;\n}\n\n/** A request the API answered with a failure: its own message, plus the fields it named when it rejected the request, and whether the message is a sentence it wrote rather than the status line. */\nexport class ApiError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly issues: ApiIssue[] | null = null,\n\t\treadonly worded = true,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/** The key refusal that applies to a route, or undefined when it may send; a proxy route holds its own key, so none applies there. */\nexport function routeRefusal(route: ApiRoute): KeyRefusal | undefined {\n\treturn route.submitUrl ? undefined : keyRefusal(route.publishableKey);\n}\n\n/** True when a route can reach the API at all: it carries a publishable key it may send, or a proxy route that holds one. */\nexport function canFetch(route: ApiRoute): boolean {\n\treturn !!(route.submitUrl || (route.publishableKey && !routeRefusal(route)));\n}\n\n/**\n * Send one request through a route and resolve to the JSON it answered.\n *\n * @remarks\n * The one place a request is built, so the key refusal, the proxy body and the failure reading cannot drift between the elements that fetch. A refused key throws before anything is sent; a failed response throws an {@link ApiError} carrying the API message and, for a rejected body, the fields it named.\n */\nexport async function apiFetch<T>(\n\troute: ApiRoute,\n\treq: RoxyRequest,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst refusal = routeRefusal(route);\n\tif (refusal) throw new ApiError(refusal.message);\n\tconst res = route.submitUrl\n\t\t? await fetch(route.submitUrl, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t},\n\t\t\t\tbody: proxyBody(req, route.submitContext),\n\t\t\t\tsignal,\n\t\t\t})\n\t\t: await callApi(route, req, signal);\n\tif (!res.ok) {\n\t\tconst failure = await readApiFailure(res);\n\t\tthrow new ApiError(failure.message, failure.issues, failure.worded);\n\t}\n\treturn (await res.json()) as T;\n}\n\n/**\n * The body of a proxied POST: the request, plus the host context under `context` when one is set.\n *\n * @remarks\n * The context is appended rather than declared on {@link RoxyRequest}, so with none set the payload is the request object itself and every route already written against it keeps receiving the same four keys in the same order. A `null` or an empty object would be a fifth key such a route never agreed to read.\n */\nfunction proxyBody(\n\treq: RoxyRequest,\n\tcontext?: Record<string, unknown>,\n): string {\n\treturn JSON.stringify(context ? { ...req, context } : req);\n}\n\n/** Direct call against RoxyAPI with the publishable key (the no-backend path). */\nfunction callApi(\n\troute: ApiRoute,\n\treq: RoxyRequest,\n\tsignal?: AbortSignal,\n): Promise<Response> {\n\t// Resolved against the page, so a same-origin base (\"/api/roxy\") is as valid as an\n\t// absolute one. Every route a host page can name resolves the same way, and a bare\n\t// `new URL()` would reject the relative shape with an opaque \"Invalid URL\".\n\tconst url = new URL(\n\t\t`${route.baseUrl ?? DEFAULT_BASE_URL}${req.path}`,\n\t\tdocument.baseURI,\n\t);\n\tfor (const [k, v] of Object.entries(req.query ?? {})) {\n\t\tif (v != null) url.searchParams.set(k, String(v));\n\t}\n\tconst headers: Record<string, string> = { Accept: 'application/json' };\n\tif (route.publishableKey) headers['X-API-Key'] = route.publishableKey;\n\tif (req.body != null) headers['Content-Type'] = 'application/json';\n\treturn fetch(url, {\n\t\tmethod: req.method ?? 'GET',\n\t\theaders,\n\t\tbody: req.body != null ? JSON.stringify(req.body) : undefined,\n\t\tsignal,\n\t});\n}\n\n/**\n * Client-side fetch for uncontrolled (self-fetching) components: drives `host.data` / `host.loading` / `host.error` and cancels a stale request when a newer one starts or the host disconnects.\n *\n * @remarks\n * Security boundary. The only credential this ever sends is a `pk_` publishable key, which carries a server-side origin allowlist. A secret (`sk_`), legacy unprefixed or sample key is refused before any network call and surfaced as an error, so a server secret cannot leak into a browser request. The request itself goes through {@link apiFetch}, which every other fetch on an element shares.\n *\n * Controlled-mode components never construct this. When a server injects the response as a `<script class=\"roxy-data\">` island, there is no key and no fetch, which is the path server-rendered consumers (WordPress, JSX SSR, static HTML) rely on.\n */\nexport class FetchController<T = unknown>\n\timplements ReactiveController, ApiRoute\n{\n\tprivate readonly host: FetchHost<T>;\n\tprivate abort?: AbortController;\n\n\t/** Browser-safe publishable key. Set by the host from its `publishable-key` attribute. */\n\tpublishableKey?: string;\n\t/** API origin, overridable for self-hosted or proxied deployments. */\n\tbaseUrl = DEFAULT_BASE_URL;\n\t/** Consumer backend route that holds the secret key, set from the host `submit-url` attribute; see {@link ApiRoute.submitUrl}. */\n\tsubmitUrl?: string;\n\t/** Object the host page attaches to the proxied request, set from its `submit-context` attribute; see {@link ApiRoute.submitContext}. */\n\tsubmitContext?: Record<string, unknown>;\n\t/** False when the last failure carried no sentence of its own: a dropped connection, or a body with no `error`. */\n\tworded = true;\n\n\tconstructor(host: FetchHost<T>) {\n\t\tthis.host = host;\n\t\thost.addController(this);\n\t}\n\n\thostDisconnected() {\n\t\tthis.abort?.abort();\n\t\tthis.abort = undefined;\n\t}\n\n\t/**\n\t * Issue the request and resolve once `host.data` (success) or `host.error`\n\t * (failure) is set. A no-op return when the key is refused: the error is\n\t * already surfaced and nothing is sent.\n\t */\n\tasync run(req: RoxyRequest): Promise<void> {\n\t\tthis.worded = true;\n\t\tconst refusal = routeRefusal(this);\n\t\tif (refusal) {\n\t\t\tthis.host.error = refusal.message;\n\t\t\tdispatchKeyRefusal(this.host, refusal);\n\t\t\treturn;\n\t\t}\n\t\tthis.abort?.abort();\n\t\tconst controller = new AbortController();\n\t\tthis.abort = controller;\n\t\tthis.host.loading = true;\n\t\tthis.host.error = null;\n\t\tthis.host.issues = null;\n\t\ttry {\n\t\t\tconst json = await apiFetch<T>(this, req, controller.signal);\n\t\t\tif (controller.signal.aborted) return;\n\t\t\tthis.host.data = json;\n\t\t} catch (err) {\n\t\t\tif (controller.signal.aborted) return;\n\t\t\tif ((err as { name?: string })?.name === 'AbortError') return;\n\t\t\tif (err instanceof ApiError) this.host.issues = err.issues;\n\t\t\tthis.worded = err instanceof ApiError && err.worded;\n\t\t\tthis.host.error = err instanceof Error ? err.message : String(err);\n\t\t} finally {\n\t\t\tif (this.abort === controller) this.abort = undefined;\n\t\t\tif (!controller.signal.aborted) this.host.loading = false;\n\t\t}\n\t}\n}\n\n/**\n * Translate flat form values into a {@link RoxyRequest} for an endpoint. The `{name}` segments in the endpoint template are substituted from the values and removed; the rest become the JSON body for POST or query parameters for GET. This is the spec-light request builder the base element uses to turn a `<roxy-endpoint-form>` submission into a self-fetch, so a component needs no per-endpoint glue.\n *\n * @param queryKeys - Names the spec declares as `in: query` for this operation, which `<roxy-endpoint-form>` reports on its `roxy-submit` event. A POST operation can still take query parameters (every localized endpoint takes `?lang=`), and sending one in the JSON body silently drops it, so those names are routed to the query string on POST as well as GET.\n */\nexport function buildRequest(\n\tendpoint: string,\n\tmethod: 'GET' | 'POST',\n\tvalues: Record<string, unknown>,\n\tqueryKeys: readonly string[] = [],\n): RoxyRequest {\n\tconst rest: Record<string, unknown> = { ...values };\n\tconst path = `/${endpoint.replace(/^\\//, '')}`.replace(\n\t\t/\\{([^}]+)\\}/g,\n\t\t(_match, name: string) => {\n\t\t\tconst v = rest[name];\n\t\t\tdelete rest[name];\n\t\t\treturn encodeURIComponent(String(v ?? ''));\n\t\t},\n\t);\n\tconst inQuery = new Set(queryKeys);\n\tconst query: Record<string, string | number | undefined> = {};\n\tconst body: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(rest)) {\n\t\tif (v === undefined || v === '') continue;\n\t\tif (method === 'GET' || inQuery.has(k)) query[k] = v as string | number;\n\t\telse body[k] = v;\n\t}\n\treturn { path, method, query, body: method === 'POST' ? body : undefined };\n}\n", "/**\n * The interpretation accordion: the one way this library shows a label, a short value, and a body of prose behind a disclosure.\n *\n * @remarks\n * Exclusive by construction (`<details name>`), so a card grows by at most one open section and never becomes a wall of text. Callers pass their own group `name` so two accordions on one page do not fight over which section is open.\n *\n * This lives here rather than in a component because the same accordion is the right shape wherever an endpoint returns a labelled reading: the Human Design bodygraph and type card use it for strategy, authority, and aura; `roxy-hexagram` uses it for the changing lines. A card that draws its own disclosure, because its summary carries more than a label and an aside, still renders the shared body and imports {@link readingDetailStyles} for it rather than restating those rules.\n *\n * **Call it through `RoxyDataElement.renderInterpretation`, never directly.** That method is where `hide-readings` is honoured, so a direct call renders prose a host asked to be left out. The section it emits carries `part=\"section readings\"` and each row `part=\"reading\"`, which is what makes the readings of EVERY component addressable under one name from outside the shadow root.\n */\n\nimport { css, html, nothing } from 'lit';\nimport type { ChromeString } from '../i18n/chrome-strings.js';\nimport { chevron } from './disclosure.js';\nimport type { Translate } from './hd-reading.js';\n\n/** One row: the label, the short value shown as the aside, and the interpretation body. `extra` renders under the body for a section that carries more than prose. */\nexport interface InterpSection {\n\tlabel: string;\n\taside?: string;\n\tbody: string;\n\textra?: unknown;\n}\n\n/**\n * Styles for the markup {@link renderReadingDetail} emits. Import this wherever that helper is called; {@link interpAccordionStyles} already embeds it, so an accordion caller needs only the one.\n *\n * @remarks\n * Separate from the accordion shell because the two are needed independently: a card can draw its own disclosure and still render the shared reading body, and hand-copying these rules is how the chip colour and spacing drifted apart across five components.\n *\n * No margin-top on the chip row. The body above already spaces its children, so a margin here would set the chips twice as far out as every other row.\n */\nexport const readingDetailStyles = css`.interp-keywords{flex-wrap:wrap;gap:.25rem;display:flex}.interp-keywords .kw{border-radius:var(--roxy-radius-full,9999px);background:color-mix(in srgb, var(--roxy-accent,#f59e0b) 14%, transparent);color:var(--roxy-fg,#0a0a0a);font-size:var(--roxy-text-xs,.75rem);padding:1px 8px}`;\n\nexport const interpAccordionStyles = css`.block{border-top:1px solid var(--roxy-border,#e4e4e7);padding-top:var(--roxy-space-md,1rem)}.block h3{margin:0 0 var(--roxy-space-sm,.5rem);font-size:var(--roxy-text-sm,.875rem);font-weight:var(--roxy-weight-bold,600);color:var(--roxy-muted,#71717a);text-transform:uppercase;letter-spacing:.06em}.interp-card{border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-md,8px);padding:var(--roxy-space-sm,.5rem) var(--roxy-space-md,1rem);margin-bottom:var(--roxy-space-xs,.25rem)}.interp-card summary{cursor:pointer;color:var(--roxy-fg,#0a0a0a);align-items:center;gap:var(--roxy-space-sm,.5rem);font-weight:500;font-size:var(--roxy-text-sm,.875rem);display:flex}.interp-card summary:focus-visible{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px;border-radius:var(--roxy-radius-sm,4px)}.interp-lead{flex-wrap:wrap;flex:auto;order:1;align-items:baseline;gap:.4rem;min-width:0;display:inline-flex}.interp-aside{flex-shrink:0;order:2;align-items:center;gap:.5rem;display:inline-flex}.roxy-chevron{order:3}.interp-aside small{color:var(--roxy-muted,#71717a);white-space:nowrap;font-weight:400}@container (width<=26rem){.interp-card summary{flex-wrap:wrap}.roxy-chevron{order:2}.interp-aside{flex-basis:100%;order:3;justify-content:flex-end}}.interp-body{margin-top:var(--roxy-space-sm,.5rem);gap:var(--roxy-space-sm,.5rem);color:var(--roxy-fg,#0a0a0a);font-size:var(--roxy-text-sm,.875rem);overflow-wrap:anywhere;line-height:1.6;display:grid}.interp-body p{margin:0}${readingDetailStyles}`;\n\n/** The keyword chips a reading carries, or nothing. One renderer because four components drew the identical row, and the markup has to match {@link readingDetailStyles}, which is the pairing that drifts when it is copied. */\nexport function renderKeywordChips(keywords: readonly string[] | undefined) {\n\tif (!keywords?.length) return nothing;\n\treturn html`<div class=\"interp-keywords\">${keywords.map((k) => html`<span class=\"kw\">${k}</span>`)}</div>`;\n}\n\n/** The prose an endpoint returns ABOUT one contact: a summary, up to three labelled lines, and the keyword chips under them. Every field is optional, so a narrower response renders fewer rows rather than empty ones. */\nexport interface ReadingDetail {\n\tsummary?: string;\n\timpact?: string;\n\ttiming?: string;\n\tguidance?: string;\n\tkeywords?: readonly string[];\n}\n\n/** Render one {@link ReadingDetail}. The three labels are copy, so this takes the translator, and they are typed {@link ChromeString} because the lookup is one indirection from the call: a scan of `t(...)` sites cannot follow that, and the compiler can. */\nexport function renderReadingDetail(\n\td: ReadingDetail | undefined,\n\tt: Translate,\n) {\n\tif (!d) return nothing;\n\tconst line = (label: ChromeString, value: string | undefined) =>\n\t\tvalue ? html`<p><strong>${t(label)}</strong> ${value}</p>` : nothing;\n\treturn html`${d.summary ? html`<p>${d.summary}</p>` : nothing} ${line('Impact:', d.impact)}${line('Timing:', d.timing)}${line('Guidance:', d.guidance)} ${renderKeywordChips(d.keywords)}`;\n}\n\n/**\n * Render the accordion. Sections with no body are dropped, so a caller can pass the full set and let a narrower response render only what it carries. `name` groups the `<details>` exclusively, so opening one closes the last.\n */\nexport function renderInterpAccordion(\n\tsections: InterpSection[],\n\tname: string,\n\theading: string,\n) {\n\tconst shown = sections.filter((s) => Boolean(s.body));\n\tif (shown.length === 0) return nothing;\n\n\treturn html`<section class=\"block\" part=\"section readings\"><h3>${heading}</h3>${shown.map(\n\t\t\t(\n\t\t\t\ts,\n\t\t\t\ti,\n\t\t\t) => html`<details class=\"interp-card\" part=\"reading\" name=\"${name}\" ?open=\"${i === 0}\"><summary><span class=\"interp-lead\">${s.label}</span> ${chevron()} ${s.aside ? html`<span class=\"interp-aside\"><small>${s.aside}</small></span>` : nothing}</summary><div class=\"interp-body\"><p>${s.body}</p>${s.extra ?? nothing}</div></details>`,\n\t\t)}</section>`;\n}\n", "import type { TemplateResult } from 'lit';\nimport { css, html } from 'lit';\n\n/**\n * Disclosure chevron for `<details>`/`<summary>` accordions. Replaces the\n * browser default triangle with a thin chevron that rotates when the host\n * `<details>` opens. Render it inside the `<summary>` and pair with\n * {@link disclosureStyles}.\n */\nexport function chevron(): TemplateResult {\n\treturn html`<svg class=\"roxy-chevron\" viewBox=\"0 0 16 16\" width=\"14\" height=\"14\" aria-hidden=\"true\"><path d=\"M4 6l4 4 4-4\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`;\n}\n\n/**\n * Shared `<details>` accordion styling: hides the native disclosure triangle\n * and rotates the {@link chevron} 180 degrees when the accordion is open.\n * Import into any component that renders disclosure accordions so the chevron\n * looks and behaves identically.\n */\nexport const disclosureStyles = css`summary{list-style:none}summary::-webkit-details-marker{display:none}.roxy-chevron{aspect-ratio:auto;width:14px;height:14px;color:var(--roxy-muted,#71717a);transition:transform var(--roxy-motion-duration,.2s) var(--roxy-motion-easing,ease);flex-shrink:0}details[open]>summary .roxy-chevron{transform:rotate(180deg)}@media (prefers-reduced-motion:reduce){.roxy-chevron{transition:none}}`;\n", "import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\n/**\n * Marker class on the inline JSON script a server emits inside a component.\n *\n * @example\n * ```html\n * <roxy-natal-chart>\n * <script type=\"application/json\" class=\"roxy-data\">{ ...response... }</script>\n * </roxy-natal-chart>\n * ```\n */\nconst ROXY_DATA_CLASS = 'roxy-data';\n\n/**\n * Serialize a RoxyAPI response for embedding inside an inline `<script type=\"application/json\" class=\"roxy-data\">`. This is the safe writer counterpart to {@link MarkupDataController}, the reader: server-rendered and cached consumers (WordPress, JSX SSR, static HTML) emit the script with this, and the component hydrates `data` from it on connect.\n *\n * @remarks\n * Use this instead of a bare `JSON.stringify`. A raw stringify of a response that contains the literal text `</script>` (common in long interpretation prose) closes the script element early, corrupting the page and creating an HTML-injection vector. This escapes the script-unsafe characters to their `\\uXXXX` JSON escapes, which `JSON.parse` restores to the original characters, so the value the component receives is identical to the response you passed.\n *\n * `<` is the load-bearing escape (it defeats `</script>` and `<!--`). `>` and `&` are escaped for defence in depth, and U+2028 / U+2029 because they are valid in JSON yet are line terminators in a `<script>` context and break some parsers. The escapes introduce only `\\uXXXX` sequences, so the replacements never feed each other and order is irrelevant.\n *\n * Pass the unwrapped RoxyAPI response, the same shape you would assign to `element.data`. Do not pass the SDK envelope (`{ data, error, request, response }`).\n *\n * @example\n * ```ts\n * import { serializeRoxyData } from '@roxyapi/ui';\n *\n * const { data } = await roxy.dreams.getDreamSymbol({ path: { id: 'water' } });\n * const html = `<roxy-dream-card><script type=\"application/json\" class=\"roxy-data\">${serializeRoxyData(data)}</script></roxy-dream-card>`;\n * ```\n */\nexport function serializeRoxyData(data: unknown): string {\n\treturn JSON.stringify(data)\n\t\t.replace(/</g, '\\\\u003c')\n\t\t.replace(/>/g, '\\\\u003e')\n\t\t.replace(/&/g, '\\\\u0026')\n\t\t.replace(/\\u2028/g, '\\\\u2028')\n\t\t.replace(/\\u2029/g, '\\\\u2029');\n}\n\n/**\n * Build the complete `<script type=\"application/json\" class=\"roxy-data\">…</script>` element a server nests inside a `roxy-*` component for the no-JavaScript hydration path. The payload is escaped via {@link serializeRoxyData}, so it is safe to drop straight into HTML output.\n *\n * @remarks\n * The element carries both `type=\"application/json\"` and `class=\"roxy-data\"` because {@link MarkupDataController} reads only a direct-child script that has both. Emit one of these inside the target component; the JavaScript `data` property still wins if it is later assigned.\n *\n * @example\n * ```ts\n * import { roxyDataScript } from '@roxyapi/ui';\n *\n * const { data } = await roxy.crystals.getCrystal({ path: { id: 'amethyst' } });\n * const html = `<roxy-crystal-grid>${roxyDataScript(data)}</roxy-crystal-grid>`;\n * ```\n */\nexport function roxyDataScript(data: unknown): string {\n\treturn `<script type=\"application/json\" class=\"${ROXY_DATA_CLASS}\">${serializeRoxyData(data)}</script>`;\n}\n\n/**\n * True when the element is a `<script type=\"application/json\">`. Uses tag name and attribute rather than `instanceof HTMLScriptElement` so the check holds in every DOM implementation, including server-rendered and hydration runtimes where the constructor global may be absent.\n */\nfunction isJsonScript(el: Element): boolean {\n\treturn (\n\t\tel.nodeName === 'SCRIPT' && el.getAttribute('type') === 'application/json'\n\t);\n}\n\n/**\n * Host shape the controller drives: any reactive element that exposes a public `data` slot. The controller only writes `data` when the host left it unset, so the JavaScript property path always wins.\n */\ninterface DataHost extends ReactiveControllerHost, HTMLElement {\n\tdata?: unknown;\n}\n\n/**\n * Reactive controller that lets a component hydrate its `data` from embedded markup when no `data` property was assigned in JavaScript.\n *\n * @remarks\n * The server-side and cached-render model: a backend renders the RoxyAPI response into a direct-child `<script type=\"application/json\" class=\"roxy-data\">` element, ships static HTML, and never runs per-element JavaScript to assign a property. On connect this controller reads that script, parses it, and feeds the result to the host. The JavaScript property path is untouched and authoritative: if `host.data` already holds a value when the host connects, the controller does nothing and the markup is ignored.\n *\n * Source resolution order on connect, first hit wins:\n *\n * 1. `host.data` already set in JavaScript -> leave it, read nothing.\n * 2. A direct-child `<script type=\"application/json\" class=\"roxy-data\">` -> parse and use. Direct-child only, so a nested component's own script is never read by an ancestor.\n *\n * Fetching from a URL is intentionally unsupported: that would require a browser-visible key and breaks the server-rendered, cached model these consumers rely on.\n *\n * Timing: {@link hostConnected} runs inside the host `connectedCallback`. For an element parsed from server HTML, its direct children are present by the time the custom element upgrades and connects, so the script is readable here. For an element created with `document.createElement` and connected before any child is appended, there is nothing to read and the property path is the only source, which is exactly the existing behavior.\n *\n * Failure is safe: malformed JSON or a missing script leaves `host.data` untouched, so the host renders its normal empty state.\n *\n * Reading the script never mutates it, and only the marked script is touched, so any sibling fallback markup a server nested inside the element (for no-JavaScript, AMP, or crawler rendering) is left in place.\n *\n * @example\n * ```ts\n * import { MarkupDataController } from '../utils/markup-data.js';\n *\n * export class RoxyExample extends LitElement {\n * constructor() {\n * super();\n * new MarkupDataController(this);\n * }\n *\n * @property({ attribute: false })\n * data: ExampleResponse | null = null;\n * }\n * ```\n */\nexport class MarkupDataController<T = unknown> implements ReactiveController {\n\tprivate readonly host: DataHost;\n\n\tconstructor(host: DataHost) {\n\t\tthis.host = host;\n\t\thost.addController(this);\n\t}\n\n\thostConnected() {\n\t\t// Property path wins. If the consumer (React, vanilla `.data =`, the\n\t\t// widgets script, an MCP agent) already set data, never look at markup.\n\t\tif (this.host.data != null) return;\n\n\t\tconst parsed = this.read();\n\t\tif (parsed === undefined) return;\n\n\t\tthis.host.data = parsed as T;\n\t\tthis.host.requestUpdate();\n\t}\n\n\t/**\n\t * Resolve the embedded payload. Returns `undefined` when there is nothing valid to read so the caller can leave `host.data` untouched.\n\t */\n\tprivate read(): T | undefined {\n\t\tconst inline = this.findInlineScript();\n\t\treturn inline ? this.parse(inline.textContent) : undefined;\n\t}\n\n\t/**\n\t * Direct-child `<script type=\"application/json\" class=\"roxy-data\">`. Scoped to immediate children so a nested data-driven component never has its script read by an ancestor, and so sibling fallback markup is ignored.\n\t */\n\tprivate findInlineScript(): Element | null {\n\t\tfor (const child of Array.from(this.host.children)) {\n\t\t\tif (isJsonScript(child) && child.classList.contains(ROXY_DATA_CLASS)) {\n\t\t\t\treturn child;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate parse(text: string | null): T | undefined {\n\t\tif (!text?.trim()) return undefined;\n\t\ttry {\n\t\t\treturn JSON.parse(text) as T;\n\t\t} catch {\n\t\t\t// Malformed embedded JSON: fail safe, leave the host empty state in\n\t\t\t// place rather than throwing during connect.\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n", "/**\n * Display formatters for ISO timestamps and floats coming back from the API.\n * Every helper returns \"\" for nullish or unparseable input so it falls out of\n * template literals cleanly.\n *\n * @remarks\n * **This file is the ONLY place in the library that may call `Intl` or a `toLocale*` method, and every helper that does takes the locale as its first argument, required.** Both halves are enforced by a source scan in `tests/i18n.test.ts`.\n *\n * The locale is the DISPLAY locale, the full tag `resolveLang` returns, region included. It is NOT the value that goes on `?lang=`: that one is truncated to a supported two-letter code because the API rejects anything else, and handing THAT to Intl would render every Argentine visitor's dates in Castilian conventions. `es-AR` is exactly the tag Intl wants.\n *\n * It is required rather than optional because the failure it prevents is an omission: `toLocaleDateString(undefined, ...)` means the locale of whoever is looking, so a Spanish page renders `Carta natal` above `Jan 15, 1990, 2:30 PM` and two visitors to one page see two different strings. An optional parameter defaults straight back to that. A missing argument is now a typecheck failure at every call site.\n */\n\nimport { capitalize, humanize } from './string.js';\n\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** A bare `YYYY-MM`, which several payloads use to name the month a forecast covers. */\nconst MONTH_ONLY = /^\\d{4}-\\d{2}$/;\nconst BARE_TIME = /^\\d{2}:\\d{2}(:\\d{2})?$/;\n/** An ISO datetime with NO timezone designator: a wall clock, not an instant. */\nconst NAIVE_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/;\n\n/** Canonical form per tag seen, so a page carrying an unparseable `lang` does not throw once per rendered date. */\nconst CANONICAL: Map<string, string> = new Map();\n\n/**\n * The locale list to hand Intl: the page's tag first, English behind it.\n *\n * @remarks\n * Two failure modes, both reachable from a `lang` attribute a site owner typed by hand and neither of which may reach a visitor:\n *\n * - **A structurally invalid tag throws.** `lang=\"english\"` or `lang=\"en_US\"` makes every `toLocale*` call raise a RangeError, which inside a render is a blank component rather than a wrong date. Canonicalizing behind a try/catch degrades it to English instead.\n * - **A valid-but-unknown tag falls back to the RUNTIME default**, which is the viewer's browser again, so the bug reappears for exactly the pages least likely to notice. Naming `en` as the second entry makes the fallback the page's, not the visitor's.\n *\n * No language signal at all resolves to English for the same reason the chrome catalogue does: a page that never declares a language is English as far as this library is concerned, and English chrome over German dates is the inconsistency this whole file exists to remove. `navigator.language` is deliberately absent from the chain here as it is in `resolveLang`: it is the VISITOR's preference, not the site's.\n */\nfunction intlLocales(locale: string | undefined): string[] {\n\tif (!locale) return ['en'];\n\tconst cached = CANONICAL.get(locale);\n\tif (cached) return [cached, 'en'];\n\tlet canonical = 'en';\n\ttry {\n\t\tcanonical = Intl.getCanonicalLocales(locale)[0] ?? 'en';\n\t} catch {\n\t\tcanonical = 'en';\n\t}\n\tCANONICAL.set(locale, canonical);\n\treturn [canonical, 'en'];\n}\n\nconst CLOCK = new Map<string, Intl.DateTimeFormatOptions>();\n\n/** The hour and minute fields in the locale's own short-time style, so a 24-hour locale pads `09:52` and a 12-hour one keeps `9:52 AM`. */\nfunction clock(locale: string | undefined): Intl.DateTimeFormatOptions {\n\tconst key = locale ?? '';\n\tconst cached = CLOCK.get(key);\n\tif (cached) return cached;\n\tconst hour = new Intl.DateTimeFormat(intlLocales(locale), {\n\t\ttimeStyle: 'short',\n\t\ttimeZone: 'UTC',\n\t})\n\t\t.formatToParts(new Date(Date.UTC(2000, 0, 1, 1)))\n\t\t.find((p) => p.type === 'hour')?.value;\n\tconst fields: Intl.DateTimeFormatOptions = {\n\t\thour: hour?.length === 2 ? '2-digit' : 'numeric',\n\t\tminute: '2-digit',\n\t};\n\tCLOCK.set(key, fields);\n\treturn fields;\n}\n\n/** Two formatted ends as one label, falling back to whichever end is present. */\nfunction joinRange(a: string, b: string): string {\n\treturn a && b ? `${a} - ${b}` : a || b;\n}\n\n/**\n * Resolve an API timestamp to a Date plus the timezone it must be RENDERED in.\n *\n * @remarks\n * The API returns chart times naive (`2026-07-13T04:36:00`): that is 04:36 in the CHART's timezone, not UTC and not the viewer's. A wall clock must read the same for every viewer on earth, so hora at sunrise says 04:36 in Tokyo and in Chicago alike.\n *\n * Handing a naive string to `new Date()` makes the runtime interpret it in the VIEWER's zone, which is a silent corruption whenever that wall clock lands in the viewer's DST gap. In America/New_York `2026-03-08T02:30:00` does not exist, so the clock jumps and it renders as `3:30 AM`. Pinning the wall clock to UTC, which has no DST and therefore no gap, preserves the digits exactly while Intl still writes them in the PAGE locale conventions.\n *\n * An offset-bearing timestamp (`...Z`, `...+05:30`) IS a real instant, so it keeps the normal behaviour and converts to the viewer's local time.\n *\n * A DATE_ONLY value (`2026-08-01`) is the same wall clock with the time left off, and it is normalised HERE rather than at each call site because leaving it to the caller is a defect that formats correctly for whoever writes the code: the platform parses a bare date as UTC midnight, and Intl then renders that instant in the VIEWER's zone, so every viewer west of Greenwich reads the previous day. Three helpers pinned it inline and {@link formatDateGrain} did not, which nothing caught because its only caller passes full datetimes.\n *\n * A bare `YYYY-MM` is the same case one grain coarser and carries the same trap, so it is normalised to the first of the month here. Without it a monthly forecast labelled `2026-08` renders as July for every viewer west of Greenwich, or as the raw string wherever a caller decided not to risk it.\n *\n * Deliberately NOT exported. Exporting it lets a component needing a shape these helpers do not offer pin its own wall clock and call Intl itself, which is how a boundary date ends up hardcoded to one locale. A missing shape is added here, beside the locale handling, not reimplemented in a component.\n */\nfunction resolveDisplayDate(input: string): {\n\td: Date;\n\ttimeZone?: string;\n} {\n\tconst naive = BARE_TIME.test(input)\n\t\t? `1970-01-01T${input}`\n\t\t: DATE_ONLY.test(input)\n\t\t\t? `${input}T00:00:00`\n\t\t\t: MONTH_ONLY.test(input)\n\t\t\t\t? `${input}-01T00:00:00`\n\t\t\t\t: NAIVE_DATETIME.test(input)\n\t\t\t\t\t? input\n\t\t\t\t\t: null;\n\treturn naive\n\t\t? { d: new Date(`${naive}Z`), timeZone: 'UTC' }\n\t\t: { d: new Date(input) };\n}\n\n/**\n * The clock, in the page locale: `2:30 PM` in English, `14:30` in German.\n *\n * @remarks\n * The hour cycle is the locale's, never ours. Pinning `hour12: true` puts an AM/PM clock on every page in Europe and Latin America while the embedded form beside it labels its own input \"formato de 24 horas\". CLDR already knows which convention each locale reads, including the ones that surprise you (`es` is 24-hour, `es-AR` is 12-hour with `p. m.`), so asserting a cycle here is asserting we know better than the locale data.\n */\nexport function formatTime(locale: string | undefined, input: unknown): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tif (DATE_ONLY.test(input)) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleTimeString(intlLocales(locale), {\n\t\t...clock(locale),\n\t\ttimeZone,\n\t});\n}\n\nexport function formatDate(locale: string | undefined, input: unknown): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleDateString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\tyear: 'numeric',\n\t\ttimeZone,\n\t});\n}\n\nexport function formatTimeRange(\n\tlocale: string | undefined,\n\tt: { start?: string; end?: string } | undefined,\n): string {\n\tif (!t) return '';\n\treturn joinRange(formatTime(locale, t.start), formatTime(locale, t.end));\n}\n\n/** Two dates as one label: `Jan 1, 2026 - Jan 7, 2026`. Falls back to whichever end parses when the other is absent. */\nexport function formatDateRange(\n\tlocale: string | undefined,\n\tstart: unknown,\n\tend: unknown,\n): string {\n\treturn joinRange(formatDate(locale, start), formatDate(locale, end));\n}\n\n/** How much of a timestamp a label shows. `time` is the whole date plus the clock. */\nexport type DateGrain = 'year' | 'month' | 'day' | 'time';\n\n/**\n * A timestamp at a chosen granularity, for an axis or a bar end where the full date would not fit.\n *\n * @remarks\n * Every grain below `year` carries the year, because a period routinely straddles new year and a label reading `28 Dec - 3 Jan` says nothing about which side moved. `year` is sliced off the string rather than formatted, since a bare four-digit year is the same in every locale this library ships and running it through Intl would introduce era and numbering-system differences into an axis tick.\n */\nexport function formatDateGrain(\n\tlocale: string | undefined,\n\tinput: unknown,\n\tgrain: DateGrain,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tif (grain === 'year') {\n\t\tconst m = input.match(/^(\\d{4})/);\n\t\treturn m?.[1] ?? input;\n\t}\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleString(intlLocales(locale), {\n\t\tday: grain === 'month' ? undefined : 'numeric',\n\t\tmonth: 'short',\n\t\tyear: 'numeric',\n\t\t...(grain === 'time' ? clock(locale) : {}),\n\t\ttimeZone,\n\t});\n}\n\n/**\n * A day inside a month already named elsewhere: `Aug 3`, `3 ago`, `3. Aug.`.\n *\n * @remarks\n * Deliberately WITHOUT the year, which is the one thing {@link formatDateGrain} will not do at any grain below `year`, and for a good reason there: a period can straddle new year and `28 Dec - 3 Jan` says nothing about which side moved. This shape exists for the opposite case, a payload whose own fields pin the month (a monthly ephemeris carries `year` and `month` at the top level and prints them in its header), where repeating the year on thirty-one rows and a dozen chips is noise rather than safety. Do not reach for it where the month is not already on screen.\n *\n * A date-only string is pinned to UTC like every other naive value, so the digits read the same for every viewer instead of rolling back a day west of Greenwich.\n */\nexport function formatMonthDay(\n\tlocale: string | undefined,\n\tinput: unknown,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleDateString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\ttimeZone,\n\t});\n}\n\n/**\n * A day of the month with its weekday: `1 Sat`, `sáb 1`, `Sa., 1.`.\n *\n * @remarks\n * The row label a printed ephemeris uses (`01 Sa`, `02 Su`), and it carries neither the month nor the year because the page header already names both. The weekday is not decoration: half of what a practitioner asks a monthly ephemeris is which DAY of the week a placement falls on, and deriving it from a bare number is exactly the arithmetic a table exists to save. Order and separator belong to the locale, which is why this is one Intl call rather than a join.\n *\n * A date-only string is pinned to UTC like every other naive value, so the weekday cannot roll backwards west of Greenwich.\n */\nexport function formatWeekdayDay(\n\tlocale: string | undefined,\n\tinput: unknown,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleDateString(intlLocales(locale), {\n\t\tweekday: 'short',\n\t\tday: 'numeric',\n\t\ttimeZone,\n\t});\n}\n\n/**\n * A calendar month and its year: `August 2026`, `agosto de 2026`, `August 2026`.\n *\n * @remarks\n * Takes the two NUMBERS an endpoint returns rather than a timestamp, because that is the shape a monthly payload echoes, and anchors them at UTC noon for the same reason {@link monthName} does: no timezone can roll the anchor into the neighbouring month. The connective belongs to the locale (`de` in Spanish, nothing in English), which is why this is one Intl call rather than a join of {@link monthName} and the year.\n */\nexport function formatMonthYear(\n\tlocale: string | undefined,\n\tyear: unknown,\n\tmonth: unknown,\n): string {\n\tif (typeof year !== 'number' || !Number.isFinite(year)) return '';\n\tif (typeof month !== 'number' || !Number.isInteger(month)) return '';\n\tif (month < 1 || month > 12) return '';\n\treturn new Date(Date.UTC(year, month - 1, 1, 12)).toLocaleDateString(\n\t\tintlLocales(locale),\n\t\t{ month: 'long', year: 'numeric', timeZone: 'UTC' },\n\t);\n}\n\n/**\n * Month name from a 1-based month number: `January`, `enero`, `janvier`.\n *\n * @remarks\n * Two components carried a byte-identical array of twelve English month names, which is both a duplicated table and a table of something the platform already knows in every language. Anchored to a UTC noon so no timezone can roll the date into the neighbouring month.\n */\nexport function monthName(locale: string | undefined, month: unknown): string {\n\tif (typeof month !== 'number' || !Number.isInteger(month)) return '';\n\tif (month < 1 || month > 12) return '';\n\treturn new Date(Date.UTC(2000, month - 1, 1, 12)).toLocaleDateString(\n\t\tintlLocales(locale),\n\t\t{ month: 'long', timeZone: 'UTC' },\n\t);\n}\n\n/**\n * A whole number with the page locale's digit grouping: `12,345` in English, `12.345` in Spanish.\n *\n * @remarks\n * Rounds rather than truncating, so a caller testing the magnitude (`Math.round(km) === 0`) and this label agree about which side of a boundary a value fell.\n */\nexport function formatInteger(\n\tlocale: string | undefined,\n\tvalue: unknown,\n): string {\n\tif (typeof value !== 'number' || !Number.isFinite(value)) return '';\n\treturn value.toLocaleString(intlLocales(locale), {\n\t\tmaximumFractionDigits: 0,\n\t});\n}\n\n/**\n * A list of names joined the way the reader's language joins one: `Mercury and Jupiter`, `Mercury und Jupiter`, `Меркурий и Юпитер`.\n *\n * @remarks\n * Several responses pack a list into one space separated string, which reads as a typo once it is\n * printed beside other values. The conjunction, the serial comma and the spacing are all CLDR's, and\n * they differ per language, which is exactly why this cannot be a `join(', ')` at a call site.\n *\n * Empty entries are dropped, so a trailing separator in the wire value cannot produce a dangling\n * conjunction, and a single entry comes back as itself.\n *\n * @example\n * ```ts\n * formatList('en', ['Mercury', 'Jupiter']); // 'Mercury and Jupiter'\n * formatList('de', ['Mercury', 'Jupiter']); // 'Mercury und Jupiter'\n * ```\n */\nexport function formatList(\n\tlocale: string | undefined,\n\titems: readonly string[],\n): string {\n\tconst parts = items.filter(Boolean);\n\tif (parts.length < 2) return parts[0] ?? '';\n\treturn new Intl.ListFormat(intlLocales(locale), {\n\t\tstyle: 'long',\n\t\ttype: 'conjunction',\n\t}).format(parts);\n}\n\n/**\n * A number to at most `dp` decimals in the reader's notation: `2.5` in English, `2,5` in German.\n *\n * @remarks Trailing zeros drop on the fractional side only, so `100` at `dp = 0` stays `100`.\n *\n * @example\n * ```ts\n * formatNumber('en', 2.5, 1); // '2.5'\n * formatNumber('de', 2.5, 1); // '2,5'\n * ```\n */\nexport function formatNumber(\n\tlocale: string | undefined,\n\tvalue: unknown,\n\tdp = 1,\n): string {\n\tif (typeof value !== 'number' || !Number.isFinite(value)) return '';\n\treturn value.toLocaleString(intlLocales(locale), {\n\t\tmaximumFractionDigits: dp,\n\t});\n}\n\n/**\n * A 0-to-100 value as a percentage in the reader's notation, which places the sign: `82.5%` in English, `%82,5` in Turkish.\n *\n * @remarks `style: 'percent'` takes a fraction, so the value is divided first.\n */\nexport function formatPercent(\n\tlocale: string | undefined,\n\tvalue: unknown,\n\tdp = 1,\n): string {\n\tif (typeof value !== 'number' || !Number.isFinite(value)) return '';\n\treturn (value / 100).toLocaleString(intlLocales(locale), {\n\t\tstyle: 'percent',\n\t\tmaximumFractionDigits: dp,\n\t});\n}\n\n/**\n * CSS class name per aspect type. Used by natal and synastry chart aspect\n * lines so the same color encoding (harmonious vs challenging) applies in\n * both wheels. Keys are lowercase canonical names, values are CSS class\n * suffixes the chart components define in their `:host` styles.\n */\nexport const ASPECT_CLASS: Record<string, string> = {\n\tconjunction: 'aspect-conjunction',\n\tsextile: 'aspect-sextile',\n\tsquare: 'aspect-square',\n\ttrine: 'aspect-trine',\n\topposition: 'aspect-opposition',\n};\n\n/**\n * Normalize the `type` field on an aspect entry to a lowercase, hyphen-separated canonical name (`SEMI_SEXTILE` and `SEMI SEXTILE` both become `semi-sextile`). Accepts any aspect-shaped object so both natal and synastry inter-aspect entries can share this.\n *\n * @remarks\n * Spaces are folded as well as underscores because the endpoints do not agree on the separator: aspects returns `SEMI SEXTILE` where synastry returns `SEMI_SEXTILE`. Handling only the underscore left the space form failing every {@link ASPECT_CLASS} and `ASPECT_SYMBOL` lookup, so the same aspect rendered hyphenated and correctly coloured in one component and space-separated in the neutral fallback colour in another.\n */\nexport function normalizeAspect(a: { type?: string }): string {\n\treturn (a.type ?? '')\n\t\t.toLowerCase()\n\t\t.trim()\n\t\t.replace(/[\\s_]+/g, '-');\n}\n\n/**\n * Display label for an aspect: `SEMI_SEXTILE` -> `Semi-sextile`.\n *\n * The raw value is an API enum and the table column it lands in is read by practitioners, not parsers. {@link normalizeAspect} stays the lookup key for classes and glyphs; this is the human-facing form.\n */\nexport function formatAspectName(a: { type?: string }): string {\n\treturn capitalize(normalizeAspect(a));\n}\n\n/**\n * Display label for an ayanamsa identifier. `kp-newcomb` -> `KP Newcomb`.\n *\n * The raw values are API enums, and every one of them needs a human form that {@link humanize} cannot derive: KP is an initialism that must stay uppercase, and `raman` is a person, B.V. Raman, not a word. Anything unmapped degrades to a humanized slug rather than rendering the enum. That fallback is a safety net, not a licence to skip the map, since a humanized slug reads as a bare surname where a full name belongs. A test fails if the committed spec gains a frame this map lacks.\n */\nexport const AYANAMSA_LABEL: Record<string, string> = {\n\t'kp-newcomb': 'KP Newcomb',\n\t'kp-old': 'KP Old',\n\tlahiri: 'Lahiri',\n\traman: 'B.V. Raman',\n\n\tcustom: 'Custom',\n};\n\nexport function formatAyanamsa(\n\tlocale: string | undefined,\n\ttype: unknown,\n\tdegrees?: unknown,\n): string {\n\tconst label =\n\t\ttypeof type === 'string' ? (AYANAMSA_LABEL[type] ?? humanize(type)) : '';\n\tconst deg =\n\t\ttypeof degrees === 'number'\n\t\t\t? `${formatNumber(locale, degrees, 2)}\\u00b0`\n\t\t\t: '';\n\tif (label && deg) return `${label} (${deg})`;\n\treturn label || deg;\n}\n\n/**\n * Date plus time in one label: `Jan 15, 1990, 2:30 PM`.\n *\n * @remarks\n * Components were concatenating a raw date and a raw time (`1990-01-15 \\u00b7 14:30:00`) while siblings rendered the same instant through {@link formatDate}. One helper keeps every card reading the same way.\n *\n * Birth details arrive as two fields rather than one timestamp, so `time` may be passed separately; it is merged into a naive datetime, pinned to UTC so the wall clock renders identically for every viewer.\n *\n * @example\n * ```ts\n * formatDateTime('en', '1990-01-15T14:30:00'); // 'Jan 15, 1990, 2:30 PM'\n * formatDateTime('en', '1990-01-15', '14:30:00'); // 'Jan 15, 1990, 2:30 PM'\n * formatDateTime('de', '1990-01-15T14:30:00'); // '15. Jan. 1990, 14:30'\n * formatDateTime('en', '1990-01-15'); // 'Jan 15, 1990'\n * ```\n */\nexport function formatDateTime(\n\tlocale: string | undefined,\n\tinput: unknown,\n\ttime?: unknown,\n): string {\n\tconst merged =\n\t\ttypeof input === 'string' &&\n\t\tDATE_ONLY.test(input) &&\n\t\ttypeof time === 'string' &&\n\t\tBARE_TIME.test(time)\n\t\t\t? `${input}T${time}`\n\t\t\t: input;\n\tif (typeof merged !== 'string' || merged.length === 0) return '';\n\tif (DATE_ONLY.test(merged)) return formatDate(locale, merged);\n\tconst { d, timeZone } = resolveDisplayDate(merged);\n\tif (Number.isNaN(d.getTime())) return merged;\n\t// One Intl call, so the locale joins the date and the clock (Turkish writes no comma).\n\treturn d.toLocaleString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\tyear: 'numeric',\n\t\t...clock(locale),\n\t\ttimeZone,\n\t});\n}\n\n/** Two timestamps as one label, each through {@link formatDateTime}. */\nexport function formatDateTimeRange(\n\tlocale: string | undefined,\n\tstart: unknown,\n\tend: unknown,\n): string {\n\treturn joinRange(formatDateTime(locale, start), formatDateTime(locale, end));\n}\n\n/**\n * An instant on the UTC clock, with the zone named: `Apr 4, 2021, 1:24 PM UTC`.\n *\n * @remarks\n * {@link formatDateTime} converts an offset-bearing timestamp to the viewer's zone, which is right for an event the viewer is living through and wrong for a value that exists to be compared against a printed reference: the Design moment on a bodygraph is published to the minute in UTC, so a reader in Kolkata and one in Chicago must see the same digits. The zone name comes from Intl rather than a typed suffix, so it follows the locale like every other unit here.\n */\nexport function formatDateTimeUtc(\n\tlocale: string | undefined,\n\tinput: unknown,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\tyear: 'numeric',\n\t\t...clock(locale),\n\t\ttimeZone: 'UTC',\n\t\ttimeZoneName: 'short',\n\t});\n}\n\n/**\n * The Sanskrit form of a name, but only when it actually differs from the English one.\n *\n * @remarks\n * Several endpoints pair an English `name` with a `sanskritName` that is sometimes the SAME string, because the tradition and the translation coincide (a nakshatra is `Ashwini` either way). Rendering the pair unconditionally then prints `Ashwini (Ashwini)`. That guard is the whole reason this exists: it is one comparison, it is easy to leave out, and leaving it out is invisible until a reader hits a name where the two agree.\n *\n * Presentation deliberately stays with the caller, since the same fact is drawn as a parenthetical in a table cell and as a middot-separated span on a chart heading.\n */\nexport function distinctSanskrit(\n\tname: unknown,\n\tsanskritName: unknown,\n): string | undefined {\n\tif (typeof sanskritName !== 'string' || !sanskritName) return undefined;\n\treturn sanskritName === name ? undefined : sanskritName;\n}\n\n/**\n * `English (Sanskrit)` for a value that carries both, falling back to whichever one exists.\n *\n * @example\n * ```ts\n * formatWithSanskrit('Tuesday', 'Mangalavara'); // 'Tuesday (Mangalavara)'\n * formatWithSanskrit('Ashwini', 'Ashwini'); // 'Ashwini'\n * ```\n */\nexport function formatWithSanskrit(\n\tname: unknown,\n\tsanskritName: unknown,\n): string {\n\tconst english = typeof name === 'string' ? name : '';\n\tconst sanskrit = distinctSanskrit(english, sanskritName);\n\tif (!english) return sanskrit ?? '';\n\treturn sanskrit ? `${english} (${sanskrit})` : english;\n}\n", "/**\n * The value a READER sees, for a response field the API returns twice.\n *\n * @remarks\n * Several endpoints now echo a display translation beside the canonical value: `nameLocalized` next to `name`, `signLocalized` next to `sign`, `typeLocalized` next to `type`. **The canonical field is deliberately always English, whatever `?lang=` says, so it stays safe to compare against in code**, and the localized one is deliberately absent from an English response.\n *\n * That split is the whole contract, and inverting it breaks charts silently rather than loudly: `planetGlyph`, `signGlyph`, `aspectSymbol`, `ASPECT_CLASS`, `SIGNS_ORDER.indexOf`, every `Map` key and every CSS class fragment is keyed on the English name, so pointing one of them at `nameLocalized` resolves to nothing on a translated page and to the same value on an English one, which is exactly the shape of defect that passes every gate (lesson 24). **The lookup stays on the canonical value; only the printed text node, the `title` and the `aria-label` move.**\n *\n * These two helpers exist so that rule lives in one place rather than as a `??` at every call site, and so an English response, where the localized field simply is not there, degrades by construction instead of by remembering. Both take the KEY of the canonical field and derive its partner, so a mistyped key or a field that is not a display string is a compile error rather than a silent empty string.\n */\n\nimport { fieldLabel, optionLabel } from '../i18n/registry.js';\nimport { humanize } from './string.js';\n\n/**\n * The label for a field NAME, which is a different problem from a field VALUE.\n *\n * @remarks\n * A catalogue keyed on English source text cannot reach a name computed per response, so these read the published field-label payload instead and fall back to {@link humanize}, which is exactly what every caller printed before one existed. A name the payload does not carry therefore renders as it always did rather than as a gap.\n *\n * Here rather than in each component because three of them need the identical pairing: the form that asks for a field, and the two generic renderers that label what came back.\n *\n * @param english - The API English label to print where the payload carries none, INSTEAD of the humanized name; the form passes it, so a field reads as the API names it on an English page too.\n */\nexport function displayField(\n\tlang: string | undefined,\n\tname: string,\n\tenglish?: string,\n): string {\n\treturn fieldLabel(lang, name) ?? english ?? humanize(name);\n}\n\n/**\n * The label for one selectable VALUE of a field, same fallback rule.\n *\n * @param fallback - What to print where the payload carries no label, INSTEAD of the humanized value.\n * The default suits a word (`81-pada` reads as `81 pada`) and not an identifier that carries a number\n * a reader checks against a published table: `humanize` turns `gmt-584283` into `Gmt 584283`, which\n * is neither the label nor the identifier. Pass the raw value for those, so an English page prints\n * what a caller stores and a translated one prints the published word.\n */\nexport function displayOption(\n\tlang: string | undefined,\n\tfield: string,\n\tvalue: string,\n\tfallback?: string,\n): string {\n\treturn optionLabel(lang, field, value) ?? fallback ?? humanize(value);\n}\n\n/** The one naming convention every helper here derives from. Ratified by the API and spreading to more operations, so it is matched as a convention and never as a list of field names. */\nconst LOCALIZED = 'Localized';\n\n/** A response row carrying a canonical English `K` plus the optional localized partner the API writes beside it. */\nexport type Localizable<K extends string> = Partial<\n\tRecord<K | `${K}Localized`, string>\n>;\n\n/** The same pairing where the value is a LIST of names, e.g. `retrogradePlanets`. */\nexport type LocalizableList<K extends string> = Partial<\n\tRecord<K | `${K}Localized`, string[]>\n>;\n\n/**\n * The text to print for `key`: the localized value when the response carried one, else the English one.\n *\n * @param english - What to print in the English case INSTEAD of the raw field, for a canonical value that is an API enum with a display form of its own (`type` is `SEMI_SEXTILE` on the wire and `Semi-sextile` on screen). Omit it wherever the canonical value is already the readable one.\n *\n * @example\n * ```ts\n * display(planet, 'name'); // 'Sol' on ?lang=es, 'Sun' on English\n * planetGlyph(planet.name) ?? display(planet, 'name'); // the lookup stays English, the fallback TEXT does not\n * display(aspect, 'type', formatAspectName(aspect)); // 'Trígono', else 'Trine' and never 'TRINE'\n * ```\n */\nexport function display<\n\tT extends Localizable<K>,\n\tK extends Extract<keyof T, string>,\n>(row: T | null | undefined, key: K, english?: string): string {\n\tconst rec = row as Record<string, unknown> | null | undefined;\n\tconst localized = rec?.[`${key}${LOCALIZED}`];\n\tif (typeof localized === 'string' && localized !== '') return localized;\n\tif (english !== undefined) return english;\n\tconst canonical = rec?.[key];\n\treturn typeof canonical === 'string' ? canonical : '';\n}\n\n/**\n * A list field as `{ value, label }` pairs: the English `value` every lookup is keyed on, and the `label` a reader sees.\n *\n * @remarks\n * The localized array is INDEX-ALIGNED with the canonical one, which is the only thing that makes the pairing possible, so it is zipped by position and neither side is ever sorted, filtered or deduped on its own. A list that is short or absent falls back per item, so a partial translation still resolves every glyph.\n */\nexport function displayList<\n\tT extends LocalizableList<K>,\n\tK extends Extract<keyof T, string>,\n>(row: T | null | undefined, key: K): Array<{ value: string; label: string }> {\n\tconst rec = row as Record<string, unknown> | null | undefined;\n\tconst canonical = rec?.[key];\n\tif (!Array.isArray(canonical)) return [];\n\tconst localized = rec?.[`${key}${LOCALIZED}`];\n\tconst labels = Array.isArray(localized) ? localized : [];\n\treturn canonical.map((value, i) => {\n\t\tconst label = labels[i];\n\t\treturn {\n\t\t\tvalue: String(value),\n\t\t\tlabel: typeof label === 'string' && label !== '' ? label : String(value),\n\t\t};\n\t});\n}\n\n/**\n * Fold every `XLocalized` field into its `X` partner: the reader's value under the canonical NAME, and the duplicate key gone.\n *\n * @remarks\n * For a renderer that has no idea what its fields MEAN and derives its columns from `Object.keys(row)`, which is how `<roxy-data>` started drawing `Planet | Planet Localized | Longitude | Sign | Sign Localized` the day the API began sending both. Two extra columns, headed in English, carrying the same fact twice, on a page whose owner changed nothing. That is a regression rather than a missing feature, so it is repaired at the key layer every render path already funnels through rather than at each of them.\n *\n * Three rules, and each has a way of going wrong:\n *\n * - **A `*Localized` key with no canonical partner stays put.** Suppressing on the name alone deletes data the response carries and nothing else is rendering.\n * - **The canonical key keeps its POSITION**, so a translated response and an English one lay out identically, column for column.\n * - **A row with nothing to fold is returned as the same object**, so the English path is not merely equivalent but untouched.\n *\n * The English value is dropped rather than shown beside its translation because the two are the same fact, and the caller here is generic: it cannot know that `sign` is the value a lookup would be keyed on. A component that needs both halves reads them itself with {@link display}.\n */\nexport function foldLocalized<V>(row: Record<string, V>): Record<string, V> {\n\tlet folded: Record<string, V> | undefined;\n\tfor (const key of Object.keys(row)) {\n\t\tif (!key.endsWith(LOCALIZED)) continue;\n\t\tconst base = key.slice(0, -LOCALIZED.length);\n\t\tif (base === '' || !(base in row)) continue;\n\t\tfolded ??= { ...row };\n\t\tconst value = row[key];\n\t\tif (value !== undefined && value !== null && value !== '')\n\t\t\tfolded[base] = value;\n\t\tdelete folded[key];\n\t}\n\treturn folded ?? row;\n}\n", "import { css } from 'lit';\n\n/**\n * A data table that stacks into rows of label and value once its card is too narrow to hold its columns.\n *\n * @remarks\n * **The case it exists for is a table carrying a PROSE column.** Three columns share a card happily\n * until one of them holds a sentence: on a phone the sentence gets whatever is left after the other\n * two, which is around a third of 250 pixels, and a paragraph rendered five characters wide is a\n * column of one word lines. A horizontal scroll box does not answer it either, because the reader is\n * then scrolling a paragraph rather than reading it.\n *\n * Stacked, each cell takes the full width with its column heading in front of it, and the prose gets\n * the whole card. The heading comes from `data-label` on the cell, painted through `content`, so the\n * markup stays ONE table and there is no second render path to keep in step. Two consequences worth\n * knowing: the label is translated copy, so it goes through `t()` like any other string and the i18n\n * scan reads that attribute; and painted text is not selectable, which is why the value stays a real\n * text node and only the heading is painted.\n *\n * Opt in with `class=\"stacked\"` on the table plus a `data-label` per cell, and import this beside the\n * component's own styles. Everything above the breakpoint is untouched, so a card that has room keeps\n * its table.\n */\nexport const stackedTableStyles = css`@container (width<=30rem){table.stacked,table.stacked tbody,table.stacked tr,table.stacked td{width:100%;display:block}table.stacked thead{display:none}table.stacked tr{border-bottom:1px solid var(--roxy-border,#e4e4e7);padding-block:var(--roxy-space-sm,.5rem)}table.stacked tr:last-child{border-bottom:0}table.stacked td{white-space:normal;border:0;padding:.1rem 0}table.stacked td:empty{display:none}table.stacked td[data-label]:before{content:attr(data-label) \" \";color:var(--roxy-muted,#71717a);font-size:var(--roxy-text-xs,.75rem);text-transform:uppercase;letter-spacing:.06em;font-weight:var(--roxy-weight-bold,600)}}`;\n"],
5
- "mappings": "4MAAA,OAAS,OAAAA,GAAK,QAAAC,EAAM,WAAAC,MAAe,MACnC,OAAS,iBAAAC,OAAqB,oBAC9B,OAAS,aAAAC,OAAiB,+BCF1B,OAGC,QAAAC,EACA,WAAAC,MAEM,MACP,OAAS,YAAAC,EAAU,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C,EACvB,OAAIgB,EAAM,SAAW,EAAUpB,EACxBD,4DAA+D,KAAK,EAAE,cAAc,CAAC,kEAAkE,KAAK,EAAE,MAAM,CAAC,YAAY,KAAK,EAAE,SAAS,CAAC,YAAY,KAAK,EAAE,OAAO,CAAC,4BAA4BqB,EAAM,IAChQE,GAAMvB,wBAA2B,KAAK,EAAE,MAAM,CAAC,+BAA+BuB,EAAE,QAAU,EAAE,+BAA+BA,EAAE,cAAgB,EAAE,+BAA+B,KAAK,EAAE,SAAS,CAAC,KAAKA,EAAE,SAAW,EAAE,IACjNA,EAAE,MAAQ,CAAC,KAAK,aACbvB,yCAA4CuB,EAAE,IAAI,OAClDtB,CACJ,oCAAoC,KAAK,EAAE,OAAO,CAAC,KAAKO,EAAcX,EAAQ0B,EAAE,KAAK,CAAC,YACzF,CAAC,kCACN,CAUQ,kBAAkBC,EAAkD,CAC3E,IAAM3B,EAAS,KAAK,cAAc,EAI5B4B,EAAiC,CAAC,EACxC,QAAWC,IAAO,CAAC,kBAAmB,aAAa,EAAY,CAC9D,IAAMC,EAAQH,IAAcE,CAAG,EAC1BC,GACLF,EAAM,KAAK,CACVG,GAAa/B,EAAQ6B,CAAG,EACxBG,GAAchC,EAAQ6B,EAAKC,CAAK,CACjC,CAAC,CACF,CACA,OAAIF,EAAM,SAAW,EAAUxB,EACxBD,0BAA6ByB,EAAM,IACxC,CAAC,CAACK,EAAOH,CAAK,EAAGT,IAChBlB,IAAOkB,EAAI,EAAI,MAAQ,EAAE,qBAAqBY,CAAK,UAAUH,CAAK,EACpE,CAAC,MACH,CACD,EAxMajC,EACL,OAAS,CACfqC,EACAC,GACAC,khHACD,EALYvC,EAANwC,EAAA,CADNC,GAAc,eAAe,GACjBzC",
4
+ "sourcesContent": ["import { css, html, nothing } from 'lit';\nimport { customElement } from 'lit/decorators.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport type { CalculateGematriaResponse } from '../types/index.js';\nimport { RoxyDataElement } from '../utils/base-element.js';\nimport { baseStyles } from '../utils/base-styles.js';\nimport { formatInteger } from '../utils/format.js';\nimport { displayField, displayOption } from '../utils/localized.js';\nimport { stackedTableStyles } from '../utils/stacked-table.js';\nimport { humanize } from '../utils/string.js';\n\ntype Gematria = CalculateGematriaResponse;\ntype HebrewForm = NonNullable<Gematria['hebrewForms']>[number];\ntype CipherValue = NonNullable<Gematria['values']>[number];\n\n/**\n * Gematria calculator. Pass `data` from POST /kabbalah/gematria.\n *\n * @remarks\n * **Hebrew is written right to left and the letter strip has to be laid out that way, or the\n * breakdown contradicts the word above it.** The response lists letters in string order, so the\n * strip carries `dir=\"rtl\"` and the first letter takes the RIGHTMOST tile. Each tile is `dir=\"ltr\"`\n * inside, because the letter name and its number are Latin and read the other way, and `lang=\"he\"`\n * marks the GLYPH rather than the strip, so a host page picks a Hebrew face for the letter and not\n * for the transliteration beside it. A final form scores differently under the finals reading, so it\n * is tinted AND keyed under the strip: a tint with a hover title is no marker on a touch screen.\n *\n * **Every candidate spelling is shown, because that is the whole answer.** A Latin name has more\n * than one defensible Hebrew spelling, one is chosen for the totals, and a calculator that hides the\n * others is asking to be trusted rather than checked. The chosen one is marked and the rule that\n * chose it is printed beside it.\n *\n * **A cipher with no computed value is left out of the table rather than shown as a zero or a blank.**\n * One catalogued cipher carries a null value on every response, and an absent number and the number\n * zero are different answers: printing it as either would publish a total nobody calculated, and\n * printing a placeholder on every response would be a row that never says anything.\n *\n * `hide-readings` keeps the spellings, every cipher value, the per letter breakdown, the\n * substitutions, the Latin ciphers and the equal-value words with their meanings. Only what the\n * tradition SAYS about an equality goes, which is the one interpretive sentence on the card.\n */\n@customElement('roxy-gematria')\nexport class RoxyGematria extends RoxyDataElement<Gematria> {\n\tstatic styles = [\n\t\tbaseStyles,\n\t\tstackedTableStyles,\n\t\tcss`.card{background:var(--roxy-surface,#fff);color:var(--roxy-fg,#0a0a0a);border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-md,8px);padding:var(--roxy-space-lg,1.5rem);box-shadow:var(--roxy-shadow-sm);gap:var(--roxy-space-md,1rem);grid-template-columns:minmax(0,1fr);display:grid}.head{justify-items:start;gap:.15rem;min-width:0;display:grid}.title{font-size:var(--roxy-text-lg,1.125rem);font-weight:var(--roxy-weight-bold,600);letter-spacing:var(--roxy-tracking-tight);margin:0}.hebrew{font-size:2rem;line-height:1.4;font-weight:var(--roxy-weight-bold,600)}.roman{font-size:var(--roxy-text-sm,.875rem);color:var(--roxy-secondary,#475569);letter-spacing:.04em}.rule{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);line-height:var(--roxy-leading-normal,1.5);margin:0}.lbl{color:var(--roxy-muted,#71717a);font-size:var(--roxy-text-xs,.75rem);text-transform:uppercase;letter-spacing:.06em;font-weight:var(--roxy-weight-bold,600);margin-right:.35rem}.src{margin-inline-start:.35rem}.block-title{margin:0 0 var(--roxy-space-sm,.5rem);font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);font-weight:var(--roxy-weight-bold,600);text-transform:uppercase;letter-spacing:.06em}.letters{flex-wrap:wrap;gap:.35rem;display:flex}.letter{border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-sm,4px);justify-items:center;gap:.1rem;min-width:3rem;padding:.3rem .45rem;display:grid}.letter .glyph{font-size:var(--roxy-text-lg,1.125rem);line-height:1.3}.letter .name{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-secondary,#475569)}.letter .num{font-size:var(--roxy-text-xs,.75rem);font-variant-numeric:tabular-nums;color:var(--roxy-fg,#0a0a0a);font-weight:var(--roxy-weight-bold,600)}.letter.is-final{background:color-mix(in srgb, var(--roxy-accent,#f59e0b) 12%, var(--roxy-surface,#fff))}.legend{margin:var(--roxy-space-sm,.5rem) 0 0;font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a)}.legend .swatch{vertical-align:middle;border:1px solid var(--roxy-border,#e4e4e7);background:color-mix(in srgb, var(--roxy-accent,#f59e0b) 12%, var(--roxy-surface,#fff));border-radius:2px;width:10px;height:10px;margin-right:4px;display:inline-block}.scroll{min-width:0;overflow-x:auto}table{border-collapse:collapse;width:100%;font-size:var(--roxy-text-sm,.875rem)}th,td{text-align:left;border-bottom:1px solid var(--roxy-border,#e4e4e7);vertical-align:top;padding:.35rem .5rem}th{color:var(--roxy-muted,#71717a);font-size:var(--roxy-text-xs,.75rem);text-transform:uppercase;letter-spacing:.06em;white-space:nowrap}td.num{font-variant-numeric:tabular-nums;white-space:nowrap}.provenance{margin:var(--roxy-space-sm,.5rem) 0 0;font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);line-height:var(--roxy-leading-normal,1.5)}.lineage{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-secondary,#475569);white-space:normal;margin:.15rem 0 0}a{color:var(--roxy-accent-ink,#b45309)}.forms{gap:var(--roxy-space-md,1rem);margin:0;padding:0;list-style:none;display:grid}.form{border-top:1px solid var(--roxy-border,#e4e4e7);padding-top:var(--roxy-space-sm,.5rem);gap:.35rem;min-width:0;display:grid}.form:first-child{border-top:0;padding-top:0}.chosen{border-radius:var(--roxy-radius-sm,4px);font-size:var(--roxy-text-xs,.75rem);background:color-mix(in srgb, var(--roxy-success,#16a34a) 12%, var(--roxy-surface,#fff));color:var(--roxy-fg,#0a0a0a);padding:.1rem .4rem;display:inline-block}.match-note{font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-secondary,#475569);white-space:normal;margin:.15rem 0 0}`,\n\t];\n\n\tprotected renderData(d: Gematria) {\n\t\tconst locale = this.effectiveLang();\n\t\tconst chosen = d.chosen;\n\t\tconst input = d.input?.text ?? d.input?.textHebrew ?? '';\n\t\treturn html`<article class=\"card\" part=\"card\" aria-labelledby=\"gematria-title\"><header class=\"head\" part=\"header\"><h2 class=\"title\" id=\"gematria-title\">${input ? `${this.t('Gematria')} · ${input}` : this.t('Gematria')}</h2>${\n\t\t\t\t\tchosen?.hebrew\n\t\t\t\t\t\t? html`<span class=\"hebrew\" lang=\"he\" dir=\"rtl\">${chosen.hebrew}</span>`\n\t\t\t\t\t\t: nothing\n\t\t\t\t} ${\n\t\t\t\t\tthis.chosenForm(d)?.romanization\n\t\t\t\t\t\t? html`<span class=\"roman\">${this.chosenForm(d)?.romanization}</span>`\n\t\t\t\t\t\t: nothing\n\t\t\t\t} ${chosen?.rule ? html`<p class=\"rule\">${chosen.rule}</p>` : nothing}</header>${this.renderLetters(locale, this.chosenForm(d)?.letters)} ${this.renderValues(locale, d.values, this.t('Cipher values'))} ${this.renderForms(locale, d)} ${this.renderTransformations(locale, d.transformations)} ${this.renderLatin(locale, d.latinValues)} ${this.renderMatches(locale, d.matches)} ${this.renderConventions(d.conventions)}</article>`;\n\t}\n\n\t/** The spelling the totals were taken from, matched back to the form that carries its letters. */\n\tprivate chosenForm(d: Gematria): HebrewForm | undefined {\n\t\tconst forms = d.hebrewForms ?? [];\n\t\treturn forms.find((f) => f.hebrew === d.chosen?.hebrew) ?? forms[0];\n\t}\n\n\t/**\n\t * The per letter breakdown of the chosen spelling.\n\t *\n\t * @remarks\n\t * `dir=\"rtl\"` on the strip is the correctness half: the response lists letters in string order and\n\t * Hebrew reads right to left, so without it the first letter would sit where a reader looks for\n\t * the last. Each tile is `dir=\"ltr\"` so its Latin name and number are not reordered with it.\n\t */\n\tprivate renderLetters(\n\t\tlocale: string | undefined,\n\t\tletters: HebrewForm['letters'] | undefined,\n\t) {\n\t\tconst rows = letters ?? [];\n\t\tif (rows.length === 0) return nothing;\n\t\treturn html`<section part=\"section letters\"><h3 class=\"block-title\">${this.t('Letters')}</h3><div class=\"letters\" part=\"chart\" dir=\"rtl\">${rows.map(\n\t\t\t\t\t(l) => html`<div class=\"${`letter${l.isFinal ? ' is-final' : ''}`}\" dir=\"ltr\" title=\"${ifDefined(l.isFinal ? this.t('Final form') : undefined)}\"><span class=\"glyph\" lang=\"he\">${l.glyph ?? ''}</span> <span class=\"name\">${l.name ?? ''}</span> <span class=\"num\">${formatInteger(locale, l.value)}</span></div>`,\n\t\t\t\t)}</div>${\n\t\t\t\t// A tint plus a hover title is no marker at all on a phone, so the key is\n\t\t\t\t// drawn whenever a final form is on the strip and never when none is.\n\t\t\t\trows.some((l) => l.isFinal)\n\t\t\t\t\t? html`<p class=\"legend\" part=\"legend\"><span class=\"swatch\"></span>${this.t('Final form')}</p>`\n\t\t\t\t\t: nothing\n\t\t\t}</section>`;\n\t}\n\n\t/** Every cipher applied to one spelling, with the provenance the whole block shares beneath it. */\n\tprivate renderValues(\n\t\tlocale: string | undefined,\n\t\tvalues: Gematria['values'] | undefined,\n\t\theading: string,\n\t) {\n\t\t// A cipher this API does not compute carries a null value, which is not a\n\t\t// zero and not a blank, so the row is dropped rather than given a number.\n\t\tconst rows = (values ?? []).filter((v) => typeof v.value === 'number');\n\t\tif (rows.length === 0) return nothing;\n\t\t// The spec says a second published total is present only where the cipher is\n\t\t// not single valued, so the column is drawn on presence for the same reason a\n\t\t// null cipher is dropped: a column that says nothing on every row is not data.\n\t\tconst alternates = rows.some((v) => (v.alternateValues ?? []).length > 0);\n\t\treturn html`<section part=\"section values\"><h3 class=\"block-title\">${heading}</h3><div class=\"scroll\"><table><thead><tr><th>${this.t('Cipher')}</th><th>${this.t('Value')}</th>${alternates ? html`<th>${this.t('Also published')}</th>` : nothing}</tr></thead><tbody>${rows.map(\n\t\t\t\t\t\t\t(v) => html`<tr><td>${humanize(v.id ?? '')}</td><td class=\"num\">${formatInteger(locale, v.value)}</td>${\n\t\t\t\t\t\t\t\t\talternates\n\t\t\t\t\t\t\t\t\t\t? html`<td class=\"num\">${(v.alternateValues ?? [])\n\t\t\t\t\t\t\t\t\t\t\t\t.map((n) => formatInteger(locale, n))\n\t\t\t\t\t\t\t\t\t\t\t\t.join(', ')}</td>`\n\t\t\t\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t\t\t\t}</tr>`,\n\t\t\t\t\t\t)}</tbody></table></div>${this.renderProvenance(rows)}</section>`;\n\t}\n\n\t/** The distinct tradition and source behind a block of ciphers, once rather than on every row. */\n\tprivate renderProvenance(rows: readonly CipherValue[]) {\n\t\tconst seen = new Map<string, string | undefined>();\n\t\tfor (const r of rows) {\n\t\t\tif (r.tradition && !seen.has(r.tradition))\n\t\t\t\tseen.set(r.tradition, r.source);\n\t\t}\n\t\tif (seen.size === 0) return nothing;\n\t\treturn html`<p class=\"provenance\"><span class=\"lbl\">${this.t('Tradition')}</span> ${[...seen].map(\n\t\t\t\t([tradition, source], i) =>\n\t\t\t\t\thtml`${i > 0 ? ' · ' : ''}${humanize(tradition)}${\n\t\t\t\t\t\tsource\n\t\t\t\t\t\t\t? html`<a class=\"src\" href=\"${source}\" target=\"_blank\" rel=\"noopener noreferrer\">${this.t('Source')}</a>`\n\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t}`,\n\t\t\t)}</p>`;\n\t}\n\n\t/**\n\t * Every Hebrew spelling the input can be written as.\n\t *\n\t * @remarks\n\t * Rendered only when there is a choice to show. One spelling is not a set of candidates, and a\n\t * heading over a single row that repeats the word already at the top of the card reads as a bug.\n\t */\n\tprivate renderForms(locale: string | undefined, d: Gematria) {\n\t\tconst forms = d.hebrewForms ?? [];\n\t\tif (forms.length < 2) return nothing;\n\t\treturn html`<section part=\"section spellings\"><h3 class=\"block-title\">${this.t('Spellings')}</h3><ul class=\"forms\">${forms.map(\n\t\t\t\t\t(f) => html`<li class=\"form\"><div><span class=\"hebrew\" lang=\"he\" dir=\"rtl\">${f.hebrew ?? ''}</span> ${\n\t\t\t\t\t\t\t\tf.hebrew === d.chosen?.hebrew\n\t\t\t\t\t\t\t\t\t? html`<span class=\"chosen\">${this.t('Chosen')}</span>`\n\t\t\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t\t\t}</div><span class=\"roman\">${f.romanization ?? ''}</span> ${f.rule ? html`<p class=\"rule\">${f.rule}</p>` : nothing} ${this.renderFormTotals(locale, f)}</li>`,\n\t\t\t\t)}</ul></section>`;\n\t}\n\n\t/** The standard reading of one candidate spelling, which is what a reader compares the spellings on. */\n\tprivate renderFormTotals(\n\t\tlocale: string | undefined,\n\t\tform: HebrewForm,\n\t): unknown {\n\t\tconst first = (form.values ?? []).find((v) => typeof v.value === 'number');\n\t\tif (!first) return nothing;\n\t\treturn html`<p class=\"rule\"><span class=\"lbl\">${humanize(first.id ?? '')}</span> ${formatInteger(locale, first.value)}</p>`;\n\t}\n\n\t/** AtBash and Albam: the substituted word and what it scores. */\n\tprivate renderTransformations(\n\t\tlocale: string | undefined,\n\t\trows: Gematria['transformations'] | undefined,\n\t) {\n\t\tconst table = rows ?? [];\n\t\tif (table.length === 0) return nothing;\n\t\treturn html`<section part=\"section substitutions\"><h3 class=\"block-title\">${this.t('Substitutions')}</h3><div class=\"scroll\"><table><thead><tr><th>${this.t('Cipher')}</th><th>${this.t('Output')}</th><th>${this.t('Value')}</th></tr></thead><tbody>${table.map(\n\t\t\t\t\t\t\t(r) => html`<tr><td>${humanize(r.id ?? '')}</td><td>${r.output ? html`<span lang=\"he\" dir=\"rtl\">${r.output}</span>` : nothing} ${r.outputRomanization ? html`<span class=\"roman\">${r.outputRomanization}</span>` : nothing}</td><td class=\"num\">${formatInteger(locale, r.value)}</td></tr>`,\n\t\t\t\t\t\t)}</tbody></table></div></section>`;\n\t}\n\n\t/**\n\t * The Latin alphabet ciphers.\n\t *\n\t * @remarks\n\t * Each carries its own lineage sentence and it is kept: it says where the cipher comes from, which\n\t * is what stops a Renaissance Christian or modern cipher being read as a rabbinic one. That is a\n\t * fact about the column rather than a claim about the word, so it is data.\n\t */\n\tprivate renderLatin(\n\t\tlocale: string | undefined,\n\t\trows: Gematria['latinValues'] | undefined,\n\t) {\n\t\tconst table = rows ?? [];\n\t\tif (table.length === 0) return nothing;\n\t\treturn html`<section part=\"section latin-ciphers\"><h3 class=\"block-title\">${this.t('Latin ciphers')}</h3><div class=\"scroll\"><table class=\"stacked\"><thead><tr><th>${this.t('Cipher')}</th><th>${this.t('Value')}</th><th>${this.t('Tradition')}</th></tr></thead><tbody>${table.map(\n\t\t\t\t\t\t\t(r) => html`<tr><td data-label=\"${this.t('Cipher')}\">${humanize(r.id ?? '')} ${r.lineage ? html`<p class=\"lineage\">${r.lineage}</p>` : nothing}</td><td class=\"num\" data-label=\"${this.t('Value')}\">${formatInteger(locale, r.value)}</td><td data-label=\"${this.t('Tradition')}\">${humanize(r.tradition ?? '')}</td></tr>`,\n\t\t\t\t\t\t)}</tbody></table></div></section>`;\n\t}\n\n\t/** Curated words whose standard value equals the chosen spelling. */\n\tprivate renderMatches(\n\t\tlocale: string | undefined,\n\t\trows: Gematria['matches'] | undefined,\n\t) {\n\t\tconst table = rows ?? [];\n\t\tif (table.length === 0) return nothing;\n\t\treturn html`<section part=\"section matches\"><h3 class=\"block-title\">${this.t('Equal values')}</h3><div class=\"scroll\"><table class=\"stacked\"><thead><tr><th>${this.t('Word')}</th><th>${this.t('Meaning')}</th><th>${this.t('Value')}</th></tr></thead><tbody>${table.map(\n\t\t\t\t\t\t\t(m) => html`<tr><td data-label=\"${this.t('Word')}\"><span lang=\"he\" dir=\"rtl\">${m.hebrew ?? ''}</span> <span class=\"roman\">${m.romanization ?? ''}</span></td><td data-label=\"${this.t('Meaning')}\">${m.meaning ?? ''} ${\n\t\t\t\t\t\t\t\t\t\tm.note && !this.hideReadings\n\t\t\t\t\t\t\t\t\t\t\t? html`<p class=\"match-note\" part=\"reading\">${m.note}</p>`\n\t\t\t\t\t\t\t\t\t\t\t: nothing\n\t\t\t\t\t\t\t\t\t}</td><td class=\"num\" data-label=\"${this.t('Value')}\">${formatInteger(locale, m.value)}</td></tr>`,\n\t\t\t\t\t\t)}</tbody></table></div></section>`;\n\t}\n\n\t/**\n\t * The switches this answer was computed under.\n\t *\n\t * @remarks\n\t * Provenance rather than decoration, the same reason a Vedic chart names its frame: the name\n\t * mispar gadol is used for two different methods, and a total printed without saying which one\n\t * produced it cannot be reconciled against any other calculator.\n\t */\n\tprivate renderConventions(conventions: Gematria['conventions'] | undefined) {\n\t\tconst locale = this.effectiveLang();\n\t\t// Both switches are REQUEST fields, so the published field-label payload\n\t\t// already names each one and each of its options in the reader's language.\n\t\t// Reading it is what stops a second translation of the same choice.\n\t\tconst pairs: Array<[string, string]> = [];\n\t\tfor (const key of ['transliteration', 'misparGadol'] as const) {\n\t\t\tconst value = conventions?.[key];\n\t\t\tif (!value) continue;\n\t\t\tpairs.push([\n\t\t\t\tdisplayField(locale, key),\n\t\t\t\tdisplayOption(locale, key, value),\n\t\t\t]);\n\t\t}\n\t\tif (pairs.length === 0) return nothing;\n\t\treturn html`<p class=\"provenance\">${pairs.map(\n\t\t\t\t([label, value], i) =>\n\t\t\t\t\thtml`${i > 0 ? ' · ' : ''}<span class=\"lbl\">${label}</span>${value}`,\n\t\t\t)}</p>`;\n\t}\n}\n\ndeclare global {\n\tinterface HTMLElementTagNameMap {\n\t\t'roxy-gematria': RoxyGematria;\n\t}\n}\n", "import {\n\ttype ComplexAttributeConverter,\n\ttype CSSResultGroup,\n\thtml,\n\tnothing,\n\ttype PropertyValues,\n} from 'lit';\nimport { property, state } from 'lit/decorators.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport type { ChromeString } from '../i18n/chrome-strings.js';\nimport { apiLang } from '../i18n/lang.js';\nimport { RoxyLocalizedElement } from '../i18n/localized-element.js';\nimport { baseStyles } from './base-styles.js';\nimport { expandCompact } from './compact.js';\nimport {\n\ttype ApiIssue,\n\tapiFetch,\n\tbuildRequest,\n\tFetchController,\n\ttype RoxyRequest,\n} from './fetch-controller.js';\nimport {\n\ttype InterpSection,\n\trenderInterpAccordion,\n} from './interp-accordion.js';\nimport { MarkupDataController } from './markup-data.js';\n\n/**\n * Read the `submit-context` attribute into the object a proxied submit carries.\n *\n * @remarks\n * Hand-written rather than `type: Object`, which resolves malformed JSON to `null` in silence: a page whose context never left has nothing to look at, and the route it was meant for reports only that the value it expected is not there. One warning covers both refusals (unparseable, or parsed to something that is not an object) because both leave the request without a context, which is the fact worth reading.\n */\nconst submitContextConverter: ComplexAttributeConverter<\n\tRecord<string, unknown> | undefined\n> = {\n\tfromAttribute: (value) => {\n\t\tif (value == null) return undefined;\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(value);\n\t\t\tif (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n\t\t\t\treturn parsed as Record<string, unknown>;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Both refusals share the warning below.\n\t\t}\n\t\tconsole.warn(\n\t\t\t'[roxy-ui] submit-context must be a JSON object; sending the request without it.',\n\t\t);\n\t\treturn undefined;\n\t},\n};\n\n/**\n * Shared base for every data-driven Roxy component. Carries once what every component needs, rather than per component, and adds the self-contained, drop-in behavior: controlled-mode hydration, an opt-in self-fetch (form, request, loading, error, empty), the typed `data` slot, and the render switch. A subclass implements one method, {@link RoxyDataElement.renderData}.\n *\n * @remarks\n * Two render modes, one component, which is the whole drop-in contract:\n *\n * - Controlled: a server (WordPress, JSX SSR, static HTML) fetches the response and injects it as a direct-child `<script type=\"application/json\" class=\"roxy-data\">`. {@link MarkupDataController} hydrates `data` from it on connect. No key reaches the browser. This is the path the WordPress plugin drives, and it is unchanged by the base class.\n * - Uncontrolled: no data is injected, but a `data-endpoint` and a `pk_` `publishable-key` are set. The component renders its own `<roxy-endpoint-form>` (an internal detail, never placed by the consumer), and on submit fetches through {@link FetchController}, which refuses any non-publishable key. The result populates `data` and the component renders it.\n *\n * The JavaScript `data` property always wins over markup, so a host that assigns `el.data = …` after upgrade is authoritative.\n *\n * A list component can open one of its rows in place: it declares {@link RoxyDataElement.rowDetail} (the element that draws one row and the path that fetches it) and calls {@link RoxyDataElement.openRow} on a pick. In self-fetch mode the base creates that element, hands it the key and the settings this element already holds, and {@link RoxyDataElement.load}s the row into it, so a hosted embed completes the flow with no host code. In controlled mode nothing is created and the pick reaches the host as the same `roxy-symbol-select` event it always sent, because the host holds the key and owns the navigation.\n *\n * Self-fetch needs `<roxy-endpoint-form>` (and `<roxy-location-search>`) registered. The CDN bundle and the full `@roxyapi/ui` entry register everything; per-component ESM consumers that want self-fetch import the form component too.\n *\n * Two things every subclass inherits for the host page to shape the render from outside the shadow root, with no JavaScript: the `hide-readings` attribute ({@link RoxyDataElement.hideReadings}), and the `part` names on the base's own branches (`form`, `loading`, `error`, `empty`, `edit-bar`, `attribution`). A component adds `part` to its own structural blocks, drawn from the published part vocabulary.\n *\n * Translation is inherited rather than defined here: `t()`, `translator` and `effectiveLang()` live on {@link RoxyLocalizedElement}, which the two declared widgets extend as well, so the form a visitor fills and the card it produces read the same catalogue.\n *\n * @example\n * ```ts\n * @customElement('roxy-dream-card')\n * export class RoxyDreamCard extends RoxyDataElement<GetDreamSymbolResponse> {\n * static styles = [baseStyles, css`.card { … }`];\n * protected renderData(d: GetDreamSymbolResponse) {\n * return html`<article class=\"card\">…</article>`;\n * }\n * }\n * ```\n */\nexport abstract class RoxyDataElement<\n\tT = unknown,\n> extends RoxyLocalizedElement {\n\tstatic styles: CSSResultGroup = [baseStyles];\n\n\t/** Typed RoxyAPI response. Assigned in JavaScript, hydrated from the roxy-data island, or set by a self-fetch. */\n\t@property({ attribute: false })\n\tdata: T | null = null;\n\n\t/** Endpoint path for self-fetch, e.g. \"astrology/natal-chart\" or \"dreams/symbols/{id}\". Empty disables self-fetch (controlled mode only). */\n\t@property({ type: String, attribute: 'data-endpoint' })\n\tendpoint = '';\n\n\t/** HTTP method for self-fetch. */\n\t@property({ type: String })\n\tmethod: 'GET' | 'POST' = 'POST';\n\n\t/** Browser-safe publishable key (pk_) for self-fetch. A secret key is refused client-side. */\n\t@property({ type: String, attribute: 'publishable-key' })\n\tpublishableKey?: string;\n\n\t/** Override the API origin for self-hosted or proxied deployments. Absolute, or relative to the page for a same-origin route. */\n\t@property({ type: String, attribute: 'base-url' })\n\tbaseUrl?: string;\n\n\t/** Override the OpenAPI spec URL the self-fetch form introspects. */\n\t@property({ type: String, attribute: 'spec-url' })\n\tspecUrl?: string;\n\n\t/** Consumer backend route that proxies the request (holds the secret key). When set, self-fetch POSTs the request here instead of calling RoxyAPI directly, so no key reaches the browser. The server-rendered (WordPress) path. */\n\t@property({ type: String, attribute: 'submit-url' })\n\tsubmitUrl?: string;\n\n\t/**\n\t * Data the host page chooses, as a JSON object, sent to the {@link RoxyDataElement.submitUrl} route as `context` beside the request. The place a page attaches its own verification data to a proxied submission.\n\t *\n\t * @remarks\n\t * Shapeless by design and never read here: the component parses the attribute, hands the object to the request, and leaves every key of it to the page and the route that answers it. Nothing is sent when it is unset, when the JSON does not parse, and when it parses to anything but an object, so a route written before this existed goes on receiving exactly the request it always did.\n\t *\n\t * It rides the proxy path only. A direct call with a `publishable-key` sends what the endpoint declares, so setting this without a `submit-url` does nothing.\n\t *\n\t * @example\n\t * ```html\n\t * <roxy-natal-chart\n\t * data-endpoint=\"astrology/natal-chart\"\n\t * submit-url=\"/api/roxy/proxy\"\n\t * submit-context='{\"token\":\"...\"}'\n\t * ></roxy-natal-chart>\n\t * ```\n\t */\n\t@property({ attribute: 'submit-context', converter: submitContextConverter })\n\tsubmitContext?: Record<string, unknown>;\n\n\t/**\n\t * Where the self-fetch form's city search sends its request, absolute or relative to the page.\n\t *\n\t * @remarks\n\t * The companion of {@link RoxyDataElement.submitUrl}, and it is separate because the two requests have different shapes: the proxy route takes one POSTed `{ path, method, body, query }`, while the city search is a GET the search issues on its own while a visitor types. A birth-data form makes both, so a page that routes its API traffic through its own server names that route here as well. It is forwarded to the internal form, which forwards it to the search; unset, the search keeps its own default.\n\t */\n\t@property({ type: String, attribute: 'location-url' })\n\tlocationUrl?: string;\n\n\t/** Persist the last self-fetch form values in sessionStorage (keyed by endpoint) and prefill the form on reload. */\n\t@property({ type: Boolean })\n\tremember = false;\n\n\t/**\n\t * Render the chart and the data, and omit the written interpretation. Off by default, so a component that does not set it is byte-identical to before.\n\t *\n\t * @remarks\n\t * The suppressed content is the prose an endpoint returns ABOUT the result: the interpretation accordion, the interpretive paragraphs, and the keyword chips that belong to them. Everything a practitioner reads the numbers off stays: wheels, tables, grids, legends, pills, counts and dates. The reading is dropped from the DOM rather than hidden with CSS, so a page that publishes the chart alone never ships the prose it is not showing.\n\t *\n\t * Set it when the page supplies its own words, which is the common case for a practitioner site that wants the graphic under its own writing.\n\t */\n\t@property({ type: Boolean, attribute: 'hide-readings', reflect: true })\n\thideReadings = false;\n\n\t/**\n\t * Remove named structural blocks from this component, as a comma-separated list of `part` names.\n\t *\n\t * @remarks\n\t * The sibling of {@link RoxyDataElement.hideReadings} and deliberately a different tool. `hide-readings` drops the PROSE an endpoint returns about a result; this drops a whole block whatever it contains, which is what a page wants when the block is measurement rather than writing. Hiding the chart-pattern list on a teaching page is the case it exists for: a T-square is data, so `hide-readings` leaves it standing on purpose.\n\t *\n\t * Any name in `components-catalog.json` works, on any component that publishes it, because the rule is generated from the name rather than from a list of components that opted in. A name no block carries costs nothing and hides nothing.\n\t *\n\t * **This hides with CSS, it does not remove from the DOM, and the difference is the reason both exist.** A part name is a rendering concern the base can act on generically; whether a block is prose is a question only the component can answer. So a page that must not SHIP the words uses `hide-readings`, and a page that just should not SHOW a block uses this.\n\t *\n\t * @example\n\t * ```html\n\t * <roxy-natal-chart hide-sections=\"patterns\"></roxy-natal-chart>\n\t * <roxy-natal-chart hide-sections=\"patterns, aspects\"></roxy-natal-chart>\n\t * <roxy-natal-chart data-endpoint=\"astrology/natal-chart\" hide-sections=\"hint\"></roxy-natal-chart>\n\t * ```\n\t */\n\t@property({ type: String, attribute: 'hide-sections', reflect: true })\n\thideSections = '';\n\n\t/** Override the self-fetch form's submit-button label. Empty derives one from the endpoint. */\n\t@property({ type: String, attribute: 'submit-label' })\n\tsubmitLabel?: string;\n\n\t/** The host page's own words for a failed self-fetch the API did not word (a dropped connection, a body with no message); a failure the API explains reads as the API worded it. */\n\t@property({ type: String, attribute: 'error-message' })\n\terrorMessage?: string;\n\n\t/** Render a small \"Spiritual data by RoxyAPI\" credit under a self-fetch or auto-mount result. Off by default; any value except \"off\"/\"false\" enables it. The one-tag widgets script forwards data-attribution as this attribute. Never shown in controlled mode. */\n\t@property({ type: String })\n\tattribution?: string;\n\n\t/** True while an uncontrolled self-fetch is in flight. Public so {@link FetchController} can drive it. */\n\t@state()\n\tloading = false;\n\n\t/** Message from a failed self-fetch, or null. Public so {@link FetchController} can drive it. */\n\t@state()\n\terror: string | null = null;\n\n\t/** The fields a rejected self-fetch named, or null. Public so {@link FetchController} can drive it; the form prints each under its input. */\n\t@state()\n\tissues: ApiIssue[] | null = null;\n\n\t/**\n\t * True once a self-fetch (not a consumer-assigned or island-hydrated `data`) produced the current result. It gates the interactive result affordances, so controlled mode never shows an Edit control or a sticky picker.\n\t */\n\t@state()\n\tprivate selfFetched = false;\n\n\t/** True when the visitor asked to edit a self-fetch result, so the form is restored over the result. */\n\t@state()\n\tprivate editing = false;\n\n\t/** True when the last self-fetch form stays above its result (a sole choice, or a form that opened on load), so a change refetches under it. */\n\t@state()\n\tprivate sticky = false;\n\n\t/** Last submitted form values (nested per group), kept in memory to restore the form on Edit and to prefill the sticky picker. */\n\tprivate lastValues?: Record<string, unknown>;\n\n\tprivate fetcher: FetchController<T>;\n\n\t/** The element that draws one row of this list and the path that fetches it, `{id}` standing for the picked row. Declared by a list component; absent on everything else, so {@link openRow} is a no-op there. */\n\tprotected rowDetail?: { tag: string; path: string };\n\n\t/** The opened row, or undefined until a pick. A list component renders it under its rows, inside its own `part=\"detail\"` block, so the name is scanned onto that component and not onto every card the base draws. */\n\t@state()\n\tprotected openedRow?: RoxyDataElement;\n\n\t/** The id of the opened row, so a list can mark the picked tile. */\n\t@state()\n\tprotected openedRowId?: string;\n\n\t/** The response key a list draws its rows from (`symbols`, `crystals`, `cards`); declared by a list component so the base can page it with {@link renderMore}. */\n\tprotected listKey?: string;\n\n\t/** The request behind the data this element fetched for itself, kept so a list can ask for the page after it. */\n\tprivate lastRequest?: RoxyRequest;\n\n\t/** True while the next page of a list is in flight. */\n\t@state()\n\tprivate moreLoading = false;\n\n\t/** Message from a failed next-page read, printed under the button that asked for it. */\n\t@state()\n\tprivate moreError: string | null = null;\n\n\tconstructor() {\n\t\tsuper();\n\t\t// Controlled mode: hydrate `data` from a direct-child roxy-data island when\n\t\t// no JS property was assigned. Keyless; the server already fetched.\n\t\tnew MarkupDataController<T>(this);\n\t\tthis.fetcher = new FetchController<T>(this);\n\t}\n\n\tprotected willUpdate(changed: PropertyValues): void {\n\t\t// A result asked for in compact form arrives with its same-shaped arrays\n\t\t// columnar, so it is decoded once here and every component goes on\n\t\t// rendering the plain shape. `expandCompact` hands back the same object\n\t\t// when nothing is encoded, so an ordinary response is neither copied nor\n\t\t// re-rendered, and Lit records a property set here inside the update in\n\t\t// progress rather than scheduling another one.\n\t\tif (changed.has('data') && this.data != null) {\n\t\t\tconst expanded = expandCompact(this.data);\n\t\t\tif (expanded !== this.data) this.data = expanded;\n\t\t}\n\t\tif (\n\t\t\tchanged.has('publishableKey') ||\n\t\t\tchanged.has('baseUrl') ||\n\t\t\tchanged.has('submitUrl') ||\n\t\t\tchanged.has('submitContext')\n\t\t) {\n\t\t\tthis.syncFetcher();\n\t\t}\n\t}\n\n\t/** Hand the request settings to the controller. Called on any change of them, and by {@link load} before it runs, because a host that sets the properties and loads in the same tick has not been through an update yet. */\n\tprivate syncFetcher(): void {\n\t\tthis.fetcher.publishableKey = this.publishableKey;\n\t\tif (this.baseUrl) this.fetcher.baseUrl = this.baseUrl;\n\t\tthis.fetcher.submitUrl = this.submitUrl;\n\t\tthis.fetcher.submitContext = this.submitContext;\n\t}\n\n\trender(): unknown {\n\t\treturn html`${this.hiddenSectionsStyle()}${this.renderState()}`;\n\t}\n\n\t/**\n\t * A bespoke card that throws while drawing a response degrades to the generic renderer instead of a dead skeleton.\n\t *\n\t * @remarks\n\t * A response the card was not written for (a sibling endpoint's shape, a field the spec grew) reaches `renderData` as data the type system cannot check at runtime, and a render that throws leaves whatever was on screen before it, which for a self-fetch is the loading placeholder, forever. The library already promises that an endpoint nothing draws falls back to `<roxy-data>`, so a card that cannot draw falls back the same way: the visitor reads the response as a table, the page hears `roxy-render-error` with the exception, and the console names the element. When the generic renderer is not registered (a per-component import), the empty state stands in.\n\t */\n\tprivate drawn(data: T): unknown {\n\t\ttry {\n\t\t\treturn this.renderData(data);\n\t\t} catch (err) {\n\t\t\tconsole.warn(\n\t\t\t\t`[roxy-ui] ${this.localName} could not draw its response`,\n\t\t\t\terr,\n\t\t\t);\n\t\t\tthis.dispatchEvent(\n\t\t\t\tnew CustomEvent('roxy-render-error', {\n\t\t\t\t\tdetail: { error: err },\n\t\t\t\t\tbubbles: true,\n\t\t\t\t\tcomposed: true,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn customElements.get('roxy-data')\n\t\t\t\t? html`<roxy-data .data=\"${data}\" lang=\"${ifDefined(this.effectiveLang())}\"></roxy-data>`\n\t\t\t\t: this.renderEmpty();\n\t\t}\n\t}\n\n\t/**\n\t * The one rule set that acts on {@link RoxyDataElement.hideSections}, generated from the names rather than from a list of components.\n\t *\n\t * @remarks\n\t * `[part~=\"name\"]` is the selector because `part` is a space-separated list: the natal chart's aspect grid carries `section aspects table aspect-grid`, so a `~=` match reaches it by any one of its names while `=` would reach it by none. It is emitted INSIDE the shadow root, which is the only place a rule can see a `part` attribute on the element that declares it.\n\t *\n\t * Names are filtered to the same `[a-z][a-z0-9-]*` shape the catalog and the WordPress setting both use, so nothing a page passes can close the rule or inject a second one. An unknown name compiles to a selector that matches nothing, which is why there is no validation error and no list of legal names to keep in sync.\n\t *\n\t * A `<style>` element in the template rather than a static stylesheet, because static styles are evaluated once and shared across every instance, so two charts on one page could not hide different blocks. Lit supports per-instance style elements; the documented cost is a re-parse when the expression changes, which is irrelevant here because the value is set once from a page attribute and effectively never changes after that.\n\t *\n\t * **`!important` is load-bearing and is not a shortcut around specificity.** Lit puts static `styles` in `adoptedStyleSheets`, and the scoping spec applies those AFTER any `<style>` element inside the same shadow root, so an in-tree rule loses to the component's own stylesheet at equal specificity no matter how it is written. Measured: `patterns` is a bare `section` with no declared display and hid correctly without it, while `legend` carries `display:flex` from the static sheet and stayed visible. The WordPress site-wide rule needs no `!important` for the opposite reason, that an outer-tree `::part()` rule already outranks anything inside.\n\t */\n\tprivate hiddenSectionsStyle(): unknown {\n\t\tconst names = this.hideSections\n\t\t\t.split(',')\n\t\t\t.map((n) => n.trim().toLowerCase())\n\t\t\t.filter((n) => /^[a-z][a-z0-9-]*$/.test(n));\n\t\tif (names.length === 0) return nothing;\n\t\t// The second selector reaches a part the self-fetch form forwards through `exportparts`.\n\t\tconst rules = names\n\t\t\t.map(\n\t\t\t\t(n) =>\n\t\t\t\t\t`[part~=\"${n}\"],roxy-endpoint-form::part(${n}){display:none!important}`,\n\t\t\t)\n\t\t\t.join('');\n\t\treturn html`<style>${rules}</style>`;\n\t}\n\n\t/** The state machine every render goes through, split out so {@link render} can pair it with the per-instance rules above. */\n\tprivate renderState(): unknown {\n\t\tif (this.endpoint && this.sticky && this.selfFetched && !this.editing)\n\t\t\treturn this.renderWithForm(this.stickyBody());\n\t\tif (this.loading) return this.renderLoading();\n\t\tif (this.error != null) return this.renderError(this.error);\n\t\tif (this.data != null) {\n\t\t\t// Controlled mode (consumer-assigned or island-hydrated data) renders the\n\t\t\t// result alone, byte-identical to before: no picker, no Edit. The one\n\t\t\t// exception is the widgets auto-mount attrs-complete path, which assigns\n\t\t\t// data directly AND sets `attribution`; a real controlled consumer never\n\t\t\t// sets the attribute, so this stays byte-identical for them.\n\t\t\tif (!this.selfFetched) {\n\t\t\t\treturn this.showAttribution()\n\t\t\t\t\t? html`${this.drawn(this.data)}${this.renderAttribution()}`\n\t\t\t\t\t: this.drawn(this.data);\n\t\t\t}\n\t\t\tif (this.editing) return this.renderForm();\n\t\t\treturn this.renderResult(this.data);\n\t\t}\n\t\treturn this.renderNoData();\n\t}\n\n\t/** Render the populated response. The single method every component implements. */\n\tprotected abstract renderData(data: T): unknown;\n\n\t/**\n\t * The interpretation accordion, gated by {@link RoxyDataElement.hideReadings}. Every component that shows a written reading routes through here instead of calling {@link renderInterpAccordion} directly.\n\t *\n\t * @remarks\n\t * The gate lives on the base rather than in each component because the property does, and a plain render function cannot read component state. One call site per accordion, one place that decides whether prose renders, and the section it emits carries the same `readings` part in every component.\n\t *\n\t * Prose that is NOT in an accordion (a summary paragraph, a per-item interpretation) is still the component's own to gate, since only the component knows which of its blocks are readings.\n\t *\n\t * @param heading - English source copy, translated here. Typed as {@link ChromeString} so the compiler, not a reviewer, rejects a heading no catalogue carries.\n\t */\n\tprotected renderInterpretation(\n\t\tsections: InterpSection[],\n\t\tname: string,\n\t\theading?: ChromeString,\n\t): unknown {\n\t\tif (this.hideReadings) return nothing;\n\t\t// Localized HERE rather than in the accordion: that is a plain render\n\t\t// function with no host, so it cannot read a language, and this is the one\n\t\t// call site every component routes through.\n\t\treturn renderInterpAccordion(sections, name, this.t(heading ?? 'Reading'));\n\t}\n\n\t/** A self-fetch result under a compact Edit control that restores the form with the previous values. */\n\tprotected renderResult(data: T): unknown {\n\t\tconst body = html`<div class=\"roxy-edit-bar\" part=\"edit-bar\"><button type=\"button\" class=\"roxy-edit\" @click=\"${this.onEdit}\">${this.t('Edit query')}</button></div>${this.drawn(data)}`;\n\t\treturn this.showAttribution()\n\t\t\t? html`${body}${this.renderAttribution()}`\n\t\t\t: body;\n\t}\n\n\t/** The form with what stands under it, from ONE call site, so the form element and the choices it read survive every refetch of a form that stays above its result. */\n\tprivate renderWithForm(body: unknown): unknown {\n\t\treturn html`${this.renderForm()}${body}`;\n\t}\n\n\t/** What a form that stays above its result shows under it: the skeleton while a refetch is in flight, the failure, or the result. */\n\tprivate stickyBody(): unknown {\n\t\tif (this.loading) return this.renderLoading();\n\t\tif (this.error != null)\n\t\t\treturn this.issues ? nothing : this.renderErrorBanner(this.error);\n\t\tif (this.data == null) return nothing;\n\t\treturn this.showAttribution()\n\t\t\t? html`${this.drawn(this.data)}${this.renderAttribution()}`\n\t\t\t: this.drawn(this.data);\n\t}\n\n\t/**\n\t * The next page of a list this element fetched for itself, appended under its rows: a list component places it after its rows, and it draws nothing in controlled mode, once every row is in, or for a response that reports no total.\n\t */\n\tprotected renderMore(): unknown {\n\t\tconst rows = this.listRows();\n\t\tconst total = (this.data as { total?: unknown } | null)?.total;\n\t\tif (!this.lastRequest || !rows || typeof total !== 'number') return nothing;\n\t\tif (rows.length >= total) return nothing;\n\t\treturn html`<div class=\"roxy-more\" part=\"more\"><button type=\"button\" class=\"roxy-edit\" ?disabled=\"${this.moreLoading}\" aria-busy=\"${this.moreLoading ? 'true' : 'false'}\" @click=\"${this.onMore}\">${this.t('Show more')}</button> ${this.moreError ? html`<p class=\"roxy-error\" role=\"alert\">${this.t(this.moreError)}</p>` : nothing}</div>`;\n\t}\n\n\t/** The rows of a list response, or undefined when this element is not a list or the response has none. */\n\tprivate listRows(): unknown[] | undefined {\n\t\tconst rows = this.listKey\n\t\t\t? (this.data as Record<string, unknown> | null)?.[this.listKey]\n\t\t\t: undefined;\n\t\treturn Array.isArray(rows) ? rows : undefined;\n\t}\n\n\tprivate onMore = async () => {\n\t\tconst req = this.lastRequest;\n\t\tconst key = this.listKey;\n\t\tconst rows = this.listRows();\n\t\tif (!req || !key || !rows) return;\n\t\tthis.moreLoading = true;\n\t\tthis.moreError = null;\n\t\ttry {\n\t\t\tconst next = await apiFetch<Record<string, unknown>>(this.fetcher, {\n\t\t\t\t...req,\n\t\t\t\tquery: { ...req.query, offset: rows.length },\n\t\t\t});\n\t\t\t// A new search replaced the list while this page was in flight; it belongs to the old one.\n\t\t\tif (this.lastRequest !== req) return;\n\t\t\tconst added = next[key];\n\t\t\tthis.data = {\n\t\t\t\t...(this.data as Record<string, unknown>),\n\t\t\t\t...next,\n\t\t\t\t[key]: [...rows, ...(Array.isArray(added) ? added : [])],\n\t\t\t} as T;\n\t\t} catch (err) {\n\t\t\tif (this.lastRequest === req)\n\t\t\t\tthis.moreError = err instanceof Error ? err.message : String(err);\n\t\t} finally {\n\t\t\tthis.moreLoading = false;\n\t\t}\n\t};\n\n\t/** Start a request that REPLACES the data: the row a previous list opened and the page state it reached belong to the old data, so they go with it. */\n\tprivate fetchFresh(req: RoxyRequest): Promise<void> {\n\t\tthis.lastRequest = req;\n\t\tthis.openedRow = undefined;\n\t\tthis.openedRowId = undefined;\n\t\tthis.moreError = null;\n\t\treturn this.fetcher.run(req);\n\t}\n\n\tprivate onEdit = () => {\n\t\tthis.editing = true;\n\t};\n\n\t/**\n\t * Fetch one request into this element from a host that already holds the key. The result renders as assigned data (no form, no edit bar), which is what a list component needs when it opens one of its rows in place, and the key guard is the same one every self-fetch passes through: a secret key is refused before anything is sent.\n\t */\n\tload(req: RoxyRequest): Promise<void> {\n\t\tthis.syncFetcher();\n\t\treturn this.fetchFresh(req);\n\t}\n\n\t/** A visitor picked a row of this list: emit `roxy-symbol-select` with it for a host that pairs its own detail, then open it here when this element can fetch. */\n\tprotected pickRow(detail: { id: string } & Record<string, unknown>): void {\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent('roxy-symbol-select', {\n\t\t\t\tdetail,\n\t\t\t\tbubbles: true,\n\t\t\t\tcomposed: true,\n\t\t\t}),\n\t\t);\n\t\tthis.openRow(detail.id);\n\t}\n\n\t/**\n\t * Open one row of this list in place. Only when this element can fetch for itself, a publishable key or a proxy route; a controlled host receives the select event and owns the navigation, so the DOM it was given stays byte-identical. The detail element is created once and reused across picks, carries the key, origin, proxy, section and reading switches and language of this element, and asks the API for the row in the language of the page.\n\t */\n\tprotected openRow(id: string): void {\n\t\tif (!this.rowDetail || !(this.publishableKey || this.submitUrl)) return;\n\t\tconst el =\n\t\t\tthis.openedRow ??\n\t\t\t(document.createElement(this.rowDetail.tag) as RoxyDataElement);\n\t\tel.publishableKey = this.publishableKey;\n\t\tel.baseUrl = this.baseUrl;\n\t\tel.submitUrl = this.submitUrl;\n\t\tel.submitContext = this.submitContext;\n\t\tel.hideReadings = this.hideReadings;\n\t\tel.hideSections = this.hideSections;\n\t\tconst lang = this.effectiveLang();\n\t\tif (lang) el.setAttribute('lang', lang);\n\t\tthis.openedRow = el;\n\t\tthis.openedRowId = id;\n\t\tvoid el\n\t\t\t.load({\n\t\t\t\tpath: `/${this.rowDetail.path.replace('{id}', encodeURIComponent(id))}`,\n\t\t\t\tmethod: 'GET',\n\t\t\t\tquery: { lang: apiLang(this) },\n\t\t\t})\n\t\t\t// The card lands under the whole list, so a tile picked near the top of a\n\t\t\t// phone would otherwise open it out of sight. Nearest keeps a visible card still.\n\t\t\t.then(() => el.scrollIntoView?.({ block: 'nearest' }));\n\t}\n\n\t/** True when the attribution credit renders: the attribute is present and not explicitly disabled. */\n\tprivate showAttribution(): boolean {\n\t\treturn (\n\t\t\tthis.attribution != null &&\n\t\t\tthis.attribution !== 'off' &&\n\t\t\tthis.attribution !== 'false'\n\t\t);\n\t}\n\n\t/** Small muted credit under a self-fetch or auto-mount result. Reached only from the result path, so controlled mode never renders it. */\n\tprotected renderAttribution(): unknown {\n\t\treturn html`<div class=\"roxy-attribution\" part=\"attribution\"><a href=\"https://roxyapi.com/?utm_source=widget&utm_medium=embed\" target=\"_blank\" rel=\"noopener\">${this.t('Spiritual data by RoxyAPI')}</a></div>`;\n\t}\n\n\t/** The data-absent branch: the self-fetch form when an endpoint is set, otherwise the empty state. */\n\tprotected renderNoData(): unknown {\n\t\treturn this.endpoint ? this.renderWithForm(nothing) : this.renderEmpty();\n\t}\n\n\t/**\n\t * Internal self-fetch form. Reuses the introspecting `<roxy-endpoint-form>`; the consumer never places it.\n\t *\n\t * @remarks\n\t * `exportparts` forwards exactly one inner name, `hint`, so the same `::part(hint)` rule works whether the page places the form itself or runs a component in self-fetch mode. The rest of the form parts stay inside: this element is an internal detail, and a name is forwarded only when hiding or restyling that block is a decision a host page makes about ITS page rather than about our form. Field help is that case, because the text is API reference prose and a page written for a client wants its own words or none.\n\t */\n\tprotected renderForm(): unknown {\n\t\treturn html`<roxy-endpoint-form part=\"form\" exportparts=\"hint\" data-endpoint=\"${this.endpoint}\" method=\"${this.method}\" spec-url=\"${ifDefined(this.specUrl)}\" publishable-key=\"${ifDefined(this.publishableKey)}\" location-url=\"${ifDefined(this.locationUrl)}\" submit-label=\"${ifDefined(this.submitLabel)}\" lang=\"${ifDefined(this.effectiveLang())}\" .initialValues=\"${this.formInitialValues()}\" .serverIssues=\"${this.issues}\" .apiRoute=\"${this.fetcher}\" .autoload=\"${!this.selfFetched}\" .fullPages=\"${!!this.listKey}\" @roxy-submit=\"${this.onFormSubmit}\"></roxy-endpoint-form>`;\n\t}\n\n\t/** Prefill source for the form: the last submission (Edit / sticky refetch) wins over remembered storage. */\n\tprivate formInitialValues(): Record<string, unknown> | undefined {\n\t\treturn (\n\t\t\tthis.lastValues ?? (this.remember ? this.readRemembered() : undefined)\n\t\t);\n\t}\n\n\tprivate onFormSubmit = (e: Event) => {\n\t\tconst detail = (e as CustomEvent).detail as {\n\t\t\tvalues: Record<string, unknown>;\n\t\t\tqueryKeys?: string[];\n\t\t\tsticky?: boolean;\n\t\t};\n\t\tthis.lastValues = detail.values;\n\t\tthis.sticky = !!detail.sticky;\n\t\tthis.selfFetched = true;\n\t\tthis.editing = false;\n\t\tif (this.remember) this.writeRemembered(detail.values);\n\t\tvoid this.fetchFresh(\n\t\t\tbuildRequest(\n\t\t\t\tthis.endpoint,\n\t\t\t\tthis.method,\n\t\t\t\tdetail.values,\n\t\t\t\tdetail.queryKeys ?? [],\n\t\t\t),\n\t\t);\n\t};\n\n\t/** sessionStorage key for this component's remembered form values, scoped by endpoint. */\n\tprivate rememberKey(): string {\n\t\treturn `roxy-ui:form:${this.endpoint}`;\n\t}\n\n\tprivate readRemembered(): Record<string, unknown> | undefined {\n\t\ttry {\n\t\t\tconst raw = sessionStorage.getItem(this.rememberKey());\n\t\t\treturn raw ? (JSON.parse(raw) as Record<string, unknown>) : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate writeRemembered(values: Record<string, unknown>): void {\n\t\ttry {\n\t\t\tsessionStorage.setItem(this.rememberKey(), JSON.stringify(values));\n\t\t} catch {\n\t\t\t// Private mode / disabled storage: remembering is best-effort, never fatal.\n\t\t}\n\t}\n\n\t/** Terminal empty state: one translated message for every component, addressable as `::part(empty)`. Override only where an empty state must DO something a message cannot. */\n\tprotected renderEmpty(): unknown {\n\t\treturn html`<div class=\"roxy-empty\" role=\"status\" part=\"empty\">${this.t('No data')}</div>`;\n\t}\n\n\t/** Loading placeholder shown during a self-fetch. */\n\tprotected renderLoading(): unknown {\n\t\treturn html`<div class=\"roxy-skeleton\" style=\"height:8rem\" role=\"status\" aria-label=\"${this.t('Loading')}\" part=\"loading\"></div>`;\n\t}\n\n\t/**\n\t * Error state shown when a self-fetch fails. Keeps the form in view so the request can be retried.\n\t *\n\t * The message goes through `t()` because the key refusal messages that reach here are ours: `KEY_REFUSALS` (`utils/key-guard.ts`), which {@link FetchController} assigns when a site owner leaves a secret or sample key in a browser page, and which `<roxy-location-search>` and the form render in their own shadow roots from the same constants. Translating it in one place and not the other would put two languages on one page. Everything else that lands here is a wire fact (an HTTP status, a browser network error), misses the catalogue and renders unchanged.\n\t */\n\tprotected renderError(message: string): unknown {\n\t\t// A rejected request that names its fields is answered on the form, field by\n\t\t// field, and needs no banner repeating the same words over it.\n\t\tif (this.endpoint && this.issues) return this.renderForm();\n\t\tconst banner = this.renderErrorBanner(message);\n\t\treturn this.endpoint ? html`${banner}${this.renderForm()}` : banner;\n\t}\n\n\t/** The failure line: the message the request failed with, or the host page's own {@link errorMessage} in place of a failure the API did not word. */\n\tprivate renderErrorBanner(message: string): unknown {\n\t\treturn html`<div class=\"roxy-error\" role=\"alert\" part=\"error\">${(!this.fetcher.worded && this.errorMessage) || this.t(message)}</div>`;\n\t}\n}\n", "// Generated by scripts/sync-bindings.ts (the `lang` query enum in specs/openapi.json). Do not edit.\n\n/**\n * Every language tag the API accepts on `?lang=`.\n *\n * @remarks\n * A self-fetch resolves the site language from the DOM, which means ANY value a\n * host page happens to carry can reach the query string. The API rejects an\n * unlisted tag with a 400, so a page in a language we do not translate would\n * stop working the moment the language chain was completed. Membership is\n * checked against this list before `lang` is sent, and a miss simply omits the\n * parameter, leaving the endpoint on its English default.\n */\nexport const API_LANGUAGES: readonly string[] = [\"de\",\"en\",\"es\",\"fr\",\"hi\",\"pt\",\"ru\",\"tr\",\"zh-Hans\",\"zh-Hant\"];\n", "/**\n * Where a component's language comes from, and what is safe to send to the API.\n *\n * @remarks\n * Two different answers, and conflating them is the whole reason this file is separate from the catalogue:\n *\n * - {@link resolveLang} answers \"what language is this PAGE in\", and keeps the full tag, because `es-AR` is a legitimate thing for a catalogue to want to differ on.\n * - {@link apiLang} answers \"what may go on the query string\", which is a narrower question with a hard edge: `?lang=es-AR` is a 400, `?lang=es` is a 200.\n *\n * The full tag is not a nicety the catalogue happens to tolerate: `utils/format.ts` hands it to `Intl`, which reads the region and writes `15 de ene de 1990` for `es-AR` where it writes `15 ene 1990` for `es`. Passing the API answer to a formatter demotes every regional visitor to the base language and nothing fails, so the two values are never interchangeable.\n */\n\nimport { API_LANGUAGES } from '../generated/api-languages.js';\n\n/**\n * The site-owner language for an element, resolved through the four-link chain the revamp design specifies.\n *\n * @remarks\n * 1. the element's own `lang` attribute (the explicit per-embed override),\n * 2. the nearest ancestor carrying `lang`, so one wrapper localizes a whole section,\n * 3. `document.documentElement.lang`, which is what makes this work on a real CMS with no markup change at all: WordPress emits `<html lang=\"es-AR\">` on every page of a Spanish site,\n * 4. nothing, which the callers read as English.\n *\n * All four links matter: with only the first, a component on a fully Spanish page renders English chrome and the only remedy is hand-editing every embed.\n *\n * `navigator.language` is deliberately NOT in the chain. It is the VISITOR's preference, not the site's: it fragments the API cache across every locale a visitor might carry and silently serves two people different content from the same URL.\n *\n * Link 2 uses `closest`, which stops at a shadow boundary. A component composed INSIDE another component's shadow root therefore cannot see the host page, which is why every composing component forwards `lang` to its children explicitly.\n */\nexport function resolveLang(el: HTMLElement): string | undefined {\n\t// Native accessor, never a Lit @property: declaring one would shadow\n\t// HTMLElement.lang and break the platform attribute for every consumer.\n\tif (el.lang) return el.lang;\n\tif (typeof document === 'undefined') return undefined;\n\tconst inherited = el.closest?.('[lang]')?.getAttribute('lang');\n\tif (inherited) return inherited;\n\treturn document.documentElement.lang || undefined;\n}\n\n/**\n * Which script a Chinese page is written in, read off the region it names.\n *\n * @remarks\n * Chinese is the one language the API keys by SCRIPT rather than by language alone, because `zh`\n * on its own does not say which of the two a reader can actually read. Real pages almost never\n * write the script: a Taiwanese site writes `zh-TW` and a mainland site writes `zh-CN`, which is\n * what the region-to-script correspondence every internationalisation library ships is for.\n * Without this step both of those degrade to English, which takes the whole Chinese audience off\n * the domains the API answers in Chinese at all.\n *\n * A bare `zh` with neither region nor script resolves to nothing on purpose: guessing a script for\n * a reader who did not name one picks characters half of them cannot read.\n */\nconst ZH_SCRIPT_BY_REGION: Readonly<Record<string, string>> = {\n\ttw: 'hant',\n\thk: 'hant',\n\tmo: 'hant',\n\tcn: 'hans',\n\tsg: 'hans',\n\tmy: 'hans',\n};\n\n/** The API's own spelling of a tag, matched case-insensitively, or undefined when it serves no such language. */\nfunction asApiLang(tag: string): string | undefined {\n\tconst wanted = tag.toLowerCase();\n\treturn API_LANGUAGES.find((l) => l.toLowerCase() === wanted);\n}\n\n/**\n * The value safe to put on `?lang=`, or `undefined` to leave the request on the API default.\n *\n * @remarks\n * Three steps, and the order is load-bearing the moment {@link resolveLang} starts reading `<html lang>`:\n *\n * - **A tag the API serves goes as it is**, matched without regard to case, so `zh-Hant` and `ZH-HANT` both send the spelling the API declares. This comes first because the next step would throw away the very subtag those tags are identified by.\n * - **Chinese resolves its script**, from an explicit script subtag or from the region ({@link ZH_SCRIPT_BY_REGION}), because that is where the language actually lives.\n * - **Everything else drops its region.** A regional tag is a 400, so a Spanish WordPress site would go from English-but-working to broken the day the language chain was completed. `es-AR`, `es-419` and `ES` all send `es`.\n *\n * **An unsupported language is omitted, not sent.** The chain surfaces whatever the host page carries, including languages the API does not translate, and an unlisted tag is the same 400. Omitting it degrades to English, which is the behaviour those pages already had.\n */\nexport function apiLang(el: HTMLElement): string | undefined {\n\tconst tag = resolveLang(el);\n\tif (!tag) return undefined;\n\tconst exact = asApiLang(tag);\n\tif (exact) return exact;\n\tconst parts = tag.toLowerCase().split('-');\n\tconst base = parts[0] as string;\n\tif (base === 'zh') {\n\t\tconst script =\n\t\t\tparts.find((p) => p === 'hans' || p === 'hant') ??\n\t\t\tZH_SCRIPT_BY_REGION[parts[1] ?? ''];\n\t\treturn script ? asApiLang(`zh-${script}`) : undefined;\n\t}\n\treturn asApiLang(base);\n}\n", "import { LitElement } from 'lit';\nimport { resolveLang } from './lang.js';\nimport { LocaleController } from './locale-controller.js';\nimport { translate } from './registry.js';\n\n/**\n * The base every element that writes WORDS extends: it resolves the page language and translates its own chrome.\n *\n * @remarks\n * This is deliberately smaller than {@link RoxyDataElement}, and the split is what makes the widgets translatable at all. `<roxy-endpoint-form>` and `<roxy-location-search>` are the two declared widgets: they fetch, they hold state, and they are NOT data components, so they cannot inherit the data base without dragging its controlled-mode hydration, its self-fetch controller and its own form rendering (which renders the form, so the form inheriting it would compose itself). They extended `LitElement` directly instead, which meant they had no `t()` and no {@link LocaleController}, so a Spanish page rendered a Spanish result card over an English form and neither widget re-rendered when a deferred locale payload landed.\n *\n * So the mechanism lives here ONCE and all three inherit it. There is no second translator, no second registry and no second way to resolve a language: adding one is how a catalogue entry and a call site drift apart.\n *\n * Two costs are why this is its own module rather than a second export of `utils/base-element.ts`. Every `dist/cdn/components/*.js` is a self-contained IIFE, so importing the data base into the city search would compile `FetchController`, `MarkupDataController` and the interpretation accordion into a bundle that uses none of them. And `utils/base-element.ts` imports THIS file, so putting the class there would close a cycle the moment a widget imported it.\n */\nexport abstract class RoxyLocalizedElement extends LitElement {\n\tconstructor() {\n\t\tsuper();\n\t\t// Re-render if a chrome-string catalogue lands after this element upgraded.\n\t\t// A host page loads the payload as its own script tag, so it can arrive\n\t\t// after first paint and there is nothing the site owner could do about it.\n\t\tnew LocaleController(this);\n\t}\n\n\t/**\n\t * The chrome string for this element's language, keyed by its own English source text.\n\t *\n\t * @remarks\n\t * Pass the English copy, never a key. With no catalogue registered the source string is returned unchanged, so an English page pays nothing and a language we do not ship degrades to English rather than to a visible key.\n\t *\n\t * Chrome only. A value the API returned (a planet, a sign, an aspect, a house system) is NOT translated here: it is rendered as the response carries it, so the words on the chart and the words in the response can never disagree. The same holds for a label derived from a spec field NAME through `humanize()`: a catalogue keyed on English source text cannot reach a string computed per response. A derived name is catalogued only where the set it comes from is CLOSED and small enough to enumerate against the spec, which is true of the nine form group names and of nothing else so far.\n\t *\n\t * @example\n\t * ```ts\n\t * this.t('Aspect grid'); // 'Cuadricula de aspectos' under lang=\"es\"\n\t * this.t('{{count}} planets', { count: 12 }); // '12 planetas'\n\t * ```\n\t */\n\tprotected t(source: string, vars?: Record<string, string | number>): string {\n\t\treturn translate(this.effectiveLang(), source, vars);\n\t}\n\n\t/** {@link RoxyLocalizedElement.t} as a value, bound once, for a shared render helper that has no host of its own and therefore cannot resolve a page language (`utils/hd-reading.ts`). Named `translator` and not `translate` because `HTMLElement.translate` is a real DOM property and shadowing it with a protected member makes every `@customElement` decorator in the library fail to typecheck. */\n\tprotected readonly translator = (\n\t\tsource: string,\n\t\tvars?: Record<string, string | number>,\n\t): string => this.t(source, vars);\n\n\t/**\n\t * Site-owner language for this element: the `lang` attribute, the nearest ancestor carrying one, or the document. Protected so a component that composes another can forward it (a child inside this shadow root cannot reach the host page on its own).\n\t *\n\t * Full tag, region included. The truncation to what `?lang=` accepts happens where the request is built, in `<roxy-endpoint-form>`.\n\t */\n\tprotected effectiveLang(): string | undefined {\n\t\treturn resolveLang(this);\n\t}\n}\n", "/**\n * Shared string helpers used across components. Single source of truth so the\n * same formatting rules apply to every key/label/title that surfaces in the\n * shadow tree.\n *\n * - `lookupKey`: the ONE normalizer every lookup table in this library is keyed\n * and read by (`tokens/index.ts` glyphs and abbreviations, `i18n/` chrome\n * strings).\n * - `capitalize`: title-cases the first character, lowercases the rest. A\n * DISPLAY helper only; it is not a lookup key (see `lookupKey`).\n * - `humanize`: turns an API key (`birth_date`, `birthDate`, `mahadasha-end`)\n * into a label suitable for display (\"Birth date\", \"Mahadasha end\").\n */\n\n/**\n * Fold a name to the canonical key its lookup table is stored under: lower case, every run of spaces, underscores and hyphens collapsed to one space, trimmed.\n *\n * @remarks\n * This exists because a GUESSED key spelling is a defect class this repo has now shipped twice. The glyph tables were keyed off whatever {@link capitalize} happened to produce (`North node`), while the API returns `North Node`, so every call site that reached the table without first calling `capitalize` missed and fell through to a fabricated abbreviation. Aspects hit the same wall from the other side: `/aspects` returns `SEMI SEXTILE` where synastry returns `SEMI_SEXTILE`.\n *\n * One normalizer, applied when a table is DEFINED and again when it is READ, removes the whole class: no call site has to remember a convention, and no table has to guess a spelling. Use it for every new table keyed by an API-supplied name.\n *\n * @example\n * ```ts\n * lookupKey('North Node'); // 'north node'\n * lookupKey('SEMI_SEXTILE'); // 'semi sextile'\n * lookupKey('semi-sextile'); // 'semi sextile'\n * ```\n */\nexport function lookupKey(s: string): string {\n\treturn s\n\t\t.toLowerCase()\n\t\t.replace(/[\\s_-]+/g, ' ')\n\t\t.trim();\n}\n\nexport function capitalize(s: string): string {\n\tif (!s) return '';\n\treturn s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();\n}\n\nexport function humanize(s: string): string {\n\treturn (\n\t\ts\n\t\t\t.replace(/[_-]+/g, ' ')\n\t\t\t.replace(/([a-z])([A-Z])/g, '$1 $2')\n\t\t\t// Split a trailing/embedded digit off a word so \"person1\" reads \"Person 1\"\n\t\t\t// and every group legend and field label spaces its ordinal.\n\t\t\t.replace(/([a-z])([0-9])/g, '$1 $2')\n\t\t\t.replace(/^\\w/, (c) => c.toUpperCase())\n\t);\n}\n", "/**\n * The chrome-string catalogue: one resolver reading one registry, so a translation can arrive from anywhere without a component changing.\n *\n * @remarks\n * **The key IS the canonical English string**, folded through {@link lookupKey}. There is no invented key vocabulary to keep in sync with the copy, which is the same rule the glyph tables in `tokens/index.ts` follow (they key off the exact value the API returns). Two consequences that are the whole point:\n *\n * - **English costs zero bytes.** A miss returns the source string, so the English build ships no catalogue at all, and a site that never loads a locale payload is byte-identical to one built before this file existed.\n * - **A missing translation degrades to English, never to a key.** The failure mode of a keyed catalogue is a raw `natal.tabs.wheel` on the page; here the worst case is the English word.\n *\n * **The registry lives on `globalThis`, not in module scope, because it has to.** Every `dist/cdn/components/*.js` is a self-contained IIFE with its own copy of this module, so a `Map` here would be invisible to the second component on the page. One global object, written by the locale payload and read by every bundle, is what makes `dist/cdn/locales/es.js` a single download that translates all of them.\n *\n * Load order is not guaranteed on a real host (WordPress enqueues scripts in an order the plugin does not fully control, and a payload may be deferred), so {@link onLocaleChange} lets an element that has already rendered in English re-render when its catalogue lands.\n */\n\nimport { lookupKey } from '../utils/string.js';\n\n/** Shared mutable state, addressed by a name rather than a module binding so every bundle on the page reaches the same object. */\ninterface LocaleRegistry {\n\t/** Language tag (lower case) to catalogue, keyed by {@link lookupKey} of the English source string. */\n\tcatalogs: Record<string, Record<string, string>>;\n\t/**\n\t * Language tag (lower case) to the API's field-label map: `fields` keyed by wire name,\n\t * `enums` keyed `{fieldName}.{value}`.\n\t *\n\t * A SEPARATE key space from `catalogs` on purpose. A chrome string is keyed by the English\n\t * text a component writes, which is a constant in our source; a field label is keyed by a\n\t * name that only the OpenAPI spec knows, computed per operation, so no catalogue keyed on\n\t * English source text can ever reach it. Same registry because the delivery problem is\n\t * identical (a payload that may land after first paint), so it reuses one global object and\n\t * one listener set rather than growing a second of each.\n\t */\n\tfieldLabels: Record<string, FieldLabels>;\n\t/** Language tags whose fetch is in flight or done, so N forms on a page cost ONE request. */\n\trequested: Set<string>;\n\t/** Elements waiting to re-render when a catalogue arrives. */\n\tlisteners: Set<() => void>;\n}\n\n/** The `/languages/field-labels` payload, minus the echoed `lang`. */\nexport interface FieldLabels {\n\tfields: Record<string, string>;\n\tenums: Record<string, string>;\n}\n\nconst GLOBAL_KEY = '__ROXY_UI_I18N__';\n\nfunction registry(): LocaleRegistry {\n\tconst holder = globalThis as unknown as Record<string, LocaleRegistry>;\n\tconst existing = holder[GLOBAL_KEY];\n\tif (existing) return existing;\n\tconst created: LocaleRegistry = {\n\t\tcatalogs: {},\n\t\tfieldLabels: {},\n\t\trequested: new Set(),\n\t\tlisteners: new Set(),\n\t};\n\tholder[GLOBAL_KEY] = created;\n\treturn created;\n}\n\n/**\n * Publish a catalogue for a language tag and wake every mounted element.\n *\n * @remarks\n * The catalogue is authored keyed by the English source string, exactly as it appears at the call site, and normalized here. That keeps the source file readable and diffable against the component that renders it, while the runtime lookup stays a single property read.\n *\n * This is the ONLY way into the registry, so a catalogue can later come from a static file, a server response, or a host page inlining a script tag, without a component knowing the difference.\n */\nexport function registerLocale(\n\tlang: string,\n\tcatalog: Record<string, string>,\n): void {\n\tconst reg = registry();\n\tconst normalized: Record<string, string> = {};\n\tfor (const [source, translated] of Object.entries(catalog)) {\n\t\tnormalized[lookupKey(source)] = translated;\n\t}\n\treg.catalogs[lang.toLowerCase()] = normalized;\n\tfor (const listener of reg.listeners) listener();\n}\n\n/**\n * Replace `{{name}}` placeholders. Copied from the API-side translator so both sides of the product interpolate identically; an unknown placeholder is left verbatim rather than blanked, so a typo in a catalogue is visible instead of silently eating the value.\n */\nexport function interpolate(\n\ttemplate: string,\n\tvars?: Record<string, string | number>,\n): string {\n\tif (!vars) return template;\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key: string) =>\n\t\tkey in vars ? String(vars[key] ?? '') : match,\n\t);\n}\n\n/**\n * The chrome string for `lang`, falling back to the English `source` it is keyed by.\n *\n * @remarks\n * A regional tag resolves against its base language, so `es-AR` and `es-419` both read the `es` catalogue and a site does not have to know which tags we happen to ship. An exact regional catalogue still wins if one is ever registered.\n */\nexport function translate(\n\tlang: string | undefined,\n\tsource: string,\n\tvars?: Record<string, string | number>,\n): string {\n\treturn interpolate(chromeLabel(lang, source) ?? source, vars);\n}\n\n/** A published chrome label, including translations equal to the source; absent on a miss. */\nexport function chromeLabel(\n\tlang: string | undefined,\n\tsource: string,\n): string | undefined {\n\tif (!lang) return undefined;\n\tconst { catalogs } = registry();\n\tconst tag = lang.toLowerCase();\n\tconst catalog = catalogs[tag] ?? catalogs[tag.split('-')[0] as string];\n\treturn catalog?.[lookupKey(source)];\n}\n\n/**\n * Publish a field-label map for a language tag and wake every mounted element.\n *\n * @remarks\n * Exported so a host that already has the payload (a server-rendered page, a test, a WordPress\n * plugin inlining it) can supply it without a network call, exactly as {@link registerLocale}\n * allows for chrome strings.\n */\nexport function registerFieldLabels(lang: string, labels: FieldLabels): void {\n\tconst reg = registry();\n\treg.fieldLabels[lang.toLowerCase()] = labels;\n\tfor (const listener of reg.listeners) listener();\n}\n\n/**\n * Read the registered field-label payload for `lang`, resolving regional tags against their base.\n *\n * @remarks\n * Shared by browser label lookups and build-time manifest generation after importing the locale\n * modules. Returns `undefined` when no payload is registered, leaving English fallback to callers.\n */\nexport function labelsFor(lang: string | undefined): FieldLabels | undefined {\n\tif (!lang) return undefined;\n\tconst { fieldLabels } = registry();\n\tconst tag = lang.toLowerCase();\n\treturn fieldLabels[tag] ?? fieldLabels[tag.split('-')[0] as string];\n}\n\n/**\n * The label for a request field name, or `undefined` when nothing has been published.\n *\n * @remarks\n * Returning `undefined` rather than the name is deliberate: the caller owns the fallback, which is\n * `humanize()`, and that keeps this resolver honest about what it actually knows. A form renders\n * identically to before until a payload arrives.\n */\nexport function fieldLabel(\n\tlang: string | undefined,\n\tname: string,\n): string | undefined {\n\treturn labelsFor(lang)?.fields[name];\n}\n\n/** The label for one selectable option, keyed `{fieldName}.{value}` as the API publishes it. */\nexport function optionLabel(\n\tlang: string | undefined,\n\tfield: string,\n\tvalue: string,\n): string | undefined {\n\treturn labelsFor(lang)?.enums[`${field}.${value}`];\n}\n\n/** Subscribe to catalogue arrivals. Returns the unsubscribe, so an element can drop it on disconnect. */\nexport function onLocaleChange(listener: () => void): () => void {\n\tconst { listeners } = registry();\n\tlisteners.add(listener);\n\treturn () => {\n\t\tlisteners.delete(listener);\n\t};\n}\n", "import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport { onLocaleChange } from './registry.js';\n\n/**\n * Re-renders its host when a chrome-string catalogue arrives.\n *\n * @remarks\n * Without this the catalogue would have to be on the page BEFORE the elements upgrade, which is not something a component can require of a real host. WordPress orders enqueued scripts by dependency and a site owner can add `defer` to any of them; a CDN embed is two independent `<script src>` tags. Any of those can land the locale payload after the first paint, and the visible result would be a chart that renders in English on a Spanish page for no reason the site owner can see or fix.\n *\n * Mirrors `MarkupDataController`: constructed in {@link RoxyDataElement}'s constructor, subscribes on connect, drops the subscription on disconnect. Registration is idempotent and a re-register of the same language simply re-renders, so a payload loaded twice is harmless.\n */\nexport class LocaleController implements ReactiveController {\n\tprivate readonly host: ReactiveControllerHost;\n\tprivate unsubscribe?: () => void;\n\n\tconstructor(host: ReactiveControllerHost) {\n\t\tthis.host = host;\n\t\thost.addController(this);\n\t}\n\n\thostConnected(): void {\n\t\tthis.unsubscribe = onLocaleChange(() => this.host.requestUpdate());\n\t}\n\n\thostDisconnected(): void {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t}\n}\n", "import { css } from 'lit';\n\n/**\n * Shared host styles every component pulls in. Sets default font, color,\n * container query support, and the entry fade-in.\n */\nexport const baseStyles = css`:host{--roxy-label-col:minmax(0, 25%);--_success-fg:var(--roxy-success-fg,#09632a);--_warning-fg:var(--roxy-warning-fg,#913304);--_danger-fg:var(--roxy-danger-fg,#881313);--_info-fg:var(--roxy-info-fg,#014f7a);font-family:var(--roxy-font-sans,system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif);color:var(--roxy-fg,#0a0a0a);font-size:var(--roxy-text-base,1rem);line-height:var(--roxy-leading-normal,1.5);animation:roxy-fade-in var(--roxy-motion-duration,.2s) var(--roxy-motion-easing,cubic-bezier(.4, 0, .2, 1)) both;background:0 0;display:block;container-type:inline-size}:host([hidden]){display:none}:host([bare]){--roxy-surface:transparent;--roxy-shadow-sm:none;--roxy-shadow-md:none}*,:before,:after{box-sizing:border-box}h1,h2,h3,h4{font-family:var(--roxy-font-display,var(--roxy-font-sans,system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif))}@keyframes roxy-fade-in{0%{transform:translateY(2px)}to{transform:translateY(0)}}@media (prefers-reduced-motion:reduce){:host{animation:none}}.roxy-skeleton{background:linear-gradient(90deg, var(--roxy-border,#e4e4e7) 0%, color-mix(in srgb, var(--roxy-border,#e4e4e7) 60%, transparent) 50%, var(--roxy-border,#e4e4e7) 100%);border-radius:var(--roxy-radius-md,8px);background-size:200% 100%;animation:1.4s ease-in-out infinite roxy-shimmer}@keyframes roxy-shimmer{0%{background-position:200% 0}to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){.roxy-skeleton{animation:none}}.roxy-sr-only{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:0;padding:0;position:absolute;overflow:hidden}.roxy-empty{padding:var(--roxy-space-lg,1.5rem);color:var(--roxy-muted,#71717a);text-align:center;font-size:var(--roxy-text-sm,.875rem)}.roxy-error{gap:var(--roxy-space-sm,.5rem);padding:var(--roxy-space-lg,1.5rem);background:var(--roxy-surface,#fff);border:1px solid var(--roxy-danger,#dc2626);border-radius:var(--roxy-radius-md,8px);color:var(--_danger-fg);font-size:var(--roxy-text-sm,.875rem);justify-items:start;display:grid}:host(:focus-within) .roxy-card{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px}.roxy-attribution{margin-top:var(--roxy-space-sm,.5rem);font-size:var(--roxy-text-xs,.75rem);color:var(--roxy-muted,#71717a);text-align:right}.roxy-attribution a{color:inherit;text-decoration:none}.roxy-attribution a:hover{color:var(--roxy-accent-ink,#b45309);text-decoration:underline}.roxy-attribution a:focus-visible{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px}.roxy-edit-bar{margin-bottom:var(--roxy-space-sm,.5rem);justify-content:flex-end;display:flex}.roxy-edit{padding:var(--roxy-space-xs,.25rem) var(--roxy-space-md,1rem);border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-md,8px);color:var(--roxy-fg,#0a0a0a);font-family:inherit;font-size:var(--roxy-text-sm,.875rem);cursor:pointer;background:0 0}.roxy-edit:hover{border-color:var(--roxy-accent,#f59e0b);color:var(--roxy-accent-ink,#b45309)}.roxy-edit:focus-visible{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px}.roxy-edit:disabled{cursor:progress;color:var(--roxy-muted,#71717a)}roxy-endpoint-form+*{margin-top:var(--roxy-space-md,1rem)}.roxy-more{justify-items:center;gap:var(--roxy-space-sm,.5rem);margin-top:var(--roxy-space-md,1rem);display:grid}.roxy-more .roxy-edit{min-height:44px}:host{font-variant-emoji:text}`;\n", "const COLS = '__cols';\nconst ROWS = '__rows';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Walk a value, rebuilding only the branches that actually hold an encoded array.\n *\n * @remarks\n * The identity return is the contract, not an optimisation: a response with nothing encoded in it comes back as the same object, so every render path that existed before this decoder sees the exact bytes it always saw.\n */\nfunction decode(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\tlet rebuilt = false;\n\t\tconst out = value.map((item) => {\n\t\t\tconst next = decode(item);\n\t\t\tif (next !== item) rebuilt = true;\n\t\t\treturn next;\n\t\t});\n\t\treturn rebuilt ? out : value;\n\t}\n\tif (!isPlainObject(value)) return value;\n\n\tconst cols = value[COLS];\n\tconst rows = value[ROWS];\n\t// Exactly the two keys and nothing else: a real payload that happens to carry\n\t// a field of either name is left alone.\n\tif (\n\t\tArray.isArray(cols) &&\n\t\tArray.isArray(rows) &&\n\t\tObject.keys(value).length === 2\n\t) {\n\t\treturn rows.map((row) => {\n\t\t\tconst item: Record<string, unknown> = {};\n\t\t\t(cols as string[]).forEach((col, i) => {\n\t\t\t\titem[col] = decode((row as unknown[])[i]);\n\t\t\t});\n\t\t\treturn item;\n\t\t});\n\t}\n\n\tlet rebuilt = false;\n\tconst out: Record<string, unknown> = {};\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tconst next = decode(item);\n\t\tif (next !== item) rebuilt = true;\n\t\tout[key] = next;\n\t}\n\treturn rebuilt ? out : value;\n}\n\n/**\n * Turn a compact API response back into the plain shape the components render.\n *\n * @remarks\n * Asking a Remote MCP tool for a compact result trades repeated field names for a header: an array of same-shaped objects arrives as `{ __cols: [names], __rows: [[values]] }`, which costs an agent far fewer tokens to read and carries exactly the same data. This is the decoder, applied at every depth, so a compact result renders in a component with nothing else to do.\n *\n * Every data component runs it on the way in, so a page that sets `data` from a tool result needs no call of its own. It is exported for the paths that hold the JSON before an element does.\n *\n * A value with nothing encoded in it is returned unchanged, by reference.\n *\n * @example\n * ```ts\n * expandCompact({ aspects: { __cols: ['a', 'b'], __rows: [['sun', 'moon'], ['sun', 'mars'], ['moon', 'mars']] } });\n * // { aspects: [{ a: 'sun', b: 'moon' }, { a: 'sun', b: 'mars' }, { a: 'moon', b: 'mars' }] }\n * ```\n */\nexport function expandCompact<T>(value: T): T {\n\treturn decode(value) as T;\n}\n", "/**\n * The one place the \"publishable key only\" rule lives. Every client-side fetch boundary ({@link ../components/location-search.ts}, {@link ./fetch-controller.ts}) and the self-fetch form ({@link ../components/endpoint-form.ts}) call through here so a refused key is refused identically: no network call, the same visible message, the same `roxy-validation-error` event. Centralising it is what stops the paths drifting into different answers for the same key, one warning and fetching where another refuses.\n */\n\n/** The sample key every copy-paste snippet ships with; pages that offer a live key input search snippets for this exact string, so changing it breaks them. */\nexport const SAMPLE_PUBLISHABLE_KEY = 'pk_live_YOUR_KEY';\n\n/** Each reason a key is refused: the `roxy-validation-error` detail reason and the English source of the message, translated where it renders. */\nexport const KEY_REFUSALS = {\n\tsecret: {\n\t\treason: 'possible-secret-key',\n\t\tmessage:\n\t\t\t'Client-side components accept a pk_ publishable key only. Use a publishable key with an origin allowlist, or render server-side.',\n\t},\n\tsample: {\n\t\treason: 'sample-key',\n\t\tmessage:\n\t\t\t'Replace the sample key with your own publishable key from your RoxyAPI account.',\n\t},\n} as const;\n\nexport type KeyRefusal = (typeof KEY_REFUSALS)[keyof typeof KEY_REFUSALS];\n\n/** Why a present key may not be sent (a secret or unprefixed key, or the snippet sample no account owns), or undefined when it may, an absent key included. */\nexport function keyRefusal(\n\tkey: string | undefined | null,\n): KeyRefusal | undefined {\n\tif (!key) return undefined;\n\tif (key === SAMPLE_PUBLISHABLE_KEY) return KEY_REFUSALS.sample;\n\treturn key.startsWith('pk_') ? undefined : KEY_REFUSALS.secret;\n}\n\n/** Dispatch the shared bubbling `roxy-validation-error` for a refused key, and log it once when `warn` is set; the caller shows the message and skips the fetch. */\nexport function dispatchKeyRefusal(\n\thost: EventTarget,\n\trefusal: KeyRefusal,\n\topts: { warn?: boolean } = {},\n): void {\n\tif (opts.warn) console.warn(refusal.message);\n\thost.dispatchEvent(\n\t\tnew CustomEvent('roxy-validation-error', {\n\t\t\tdetail: { reason: refusal.reason, message: refusal.message },\n\t\t\tbubbles: true,\n\t\t\tcomposed: true,\n\t\t}),\n\t);\n}\n", "import type { ReactiveController, ReactiveControllerHost } from 'lit';\nimport {\n\tdispatchKeyRefusal,\n\ttype KeyRefusal,\n\tkeyRefusal,\n} from './key-guard.js';\n\n/**\n * Host slots the controller drives. {@link RoxyDataElement} satisfies this, so the form mixin can attach a controller without the component wiring state by hand.\n *\n * @remarks\n * Intersected with `HTMLElement` because the controller dispatches events on the host. Lit's `ReactiveControllerHost` is the update-lifecycle contract only (`addController`, `requestUpdate`, `updateComplete`) and carries no DOM surface, even though every real host is a `LitElement` and therefore an `HTMLElement`. Declaring the DOM half is what the controller actually needs, and it is declared rather than reached through a `this.host as unknown as EventTarget` double cast, which would assert a capability the type never promised.\n */\ntype FetchHost<T> = ReactiveControllerHost &\n\tHTMLElement & {\n\t\tdata: T | null;\n\t\tloading: boolean;\n\t\terror: string | null;\n\t\t/** The field-level issues of a rejected request, or null when the failure was not about the request body. */\n\t\tissues: ApiIssue[] | null;\n\t};\n\n/** One field the API rejected, as the API reports it: the wire path of the field (`year`, `person1.date`, `members.0.date`) and the reason. */\nexport interface ApiIssue {\n\tpath: string;\n\tmessage: string;\n}\n\n/** A failed request, read once: the message every failure carries and the per-field issues a validation failure adds. */\ninterface ApiFailure {\n\tmessage: string;\n\tissues: ApiIssue[] | null;\n\t/** False when the body carried no `error` sentence and the message is the status line. */\n\tworded: boolean;\n}\n\n/** The public API root, which a component overrides per instance through its `base-url` attribute; exported so every request names one origin. */\nexport const DEFAULT_BASE_URL = 'https://roxyapi.com/api/v2';\n\n/**\n * Turn a failed `Response` into the message to show: the API's own `{ error }` string when the body carries one, else the status line.\n *\n * @remarks\n * Exported so every client-side fetch boundary renders the same words for the same failure, the way {@link keyRefusal} centralizes the key refusal. A boundary that discards the response body cannot tell a rejected request from an empty result, and renders the two identically.\n */\nexport async function readApiError(res: Response): Promise<string> {\n\treturn (await readApiFailure(res)).message;\n}\n\n/**\n * The failure a response carries.\n *\n * @remarks\n * A rejected request answers `{ error, code, issues }`, and `issues` is what makes the error actionable: each names the field by its wire path, which is the same identity the form keys its inputs by, so the message can sit under the input it is about instead of in a banner quoting a path. Only a `validation_error` carries them; every other failure keeps the message alone.\n */\nasync function readApiFailure(res: Response): Promise<ApiFailure> {\n\ttry {\n\t\tconst body = (await res.json()) as {\n\t\t\terror?: string;\n\t\t\tcode?: string;\n\t\t\tissues?: Array<{ path?: unknown; message?: unknown }>;\n\t\t};\n\t\tif (body?.error) {\n\t\t\tconst issues =\n\t\t\t\tbody.code === 'validation_error' && Array.isArray(body.issues)\n\t\t\t\t\t? body.issues\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(i) =>\n\t\t\t\t\t\t\t\t\ttypeof i.path === 'string' && typeof i.message === 'string',\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.map((i) => ({\n\t\t\t\t\t\t\t\tpath: i.path as string,\n\t\t\t\t\t\t\t\tmessage: i.message as string,\n\t\t\t\t\t\t\t}))\n\t\t\t\t\t: null;\n\t\t\treturn {\n\t\t\t\tmessage: body.error,\n\t\t\t\tissues: issues?.length ? issues : null,\n\t\t\t\tworded: true,\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// Non-JSON error body: fall through to the status line.\n\t}\n\treturn {\n\t\tmessage: `Request failed (${res.status})`,\n\t\tissues: null,\n\t\tworded: false,\n\t};\n}\n\n/** A single request the controller issues on the component's behalf. */\nexport interface RoxyRequest {\n\t/** Path under the API base, e.g. \"/dreams/symbols/water\" or \"/astrology/natal-chart\". */\n\tpath: string;\n\tmethod?: 'GET' | 'POST';\n\t/** JSON body for POST endpoints. */\n\tbody?: unknown;\n\t/** Query string parameters; nullish values are dropped. */\n\tquery?: Record<string, string | number | undefined>;\n}\n\n/**\n * Where an element sends its requests: the key it may present, the API origin, and the host route that proxies them.\n *\n * @remarks\n * Every element that fetches holds these four, and {@link apiFetch} is the one function that turns them into a request, so a list that loads its next page, a form that loads its choices and a component that loads its result reach the API, or the host route standing in for it, the same way.\n */\nexport interface ApiRoute {\n\t/** Browser-safe publishable key; anything else is refused before a request is made. */\n\tpublishableKey?: string;\n\t/** API origin, absolute or relative to the page; {@link DEFAULT_BASE_URL} when unset. */\n\tbaseUrl?: string;\n\t/** Host route that holds the secret key. When set, the request is POSTed there as `{ path, method, body, query }` and no key leaves the browser. */\n\tsubmitUrl?: string;\n\t/** Object the host page attaches to a proxied request as `context`, passed through unread. */\n\tsubmitContext?: Record<string, unknown>;\n}\n\n/** A request the API answered with a failure: its own message, plus the fields it named when it rejected the request, and whether the message is a sentence it wrote rather than the status line. */\nexport class ApiError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly issues: ApiIssue[] | null = null,\n\t\treadonly worded = true,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\n/** The key refusal that applies to a route, or undefined when it may send; a proxy route holds its own key, so none applies there. */\nexport function routeRefusal(route: ApiRoute): KeyRefusal | undefined {\n\treturn route.submitUrl ? undefined : keyRefusal(route.publishableKey);\n}\n\n/** True when a route can reach the API at all: it carries a publishable key it may send, or a proxy route that holds one. */\nexport function canFetch(route: ApiRoute): boolean {\n\treturn !!(route.submitUrl || (route.publishableKey && !routeRefusal(route)));\n}\n\n/**\n * Send one request through a route and resolve to the JSON it answered.\n *\n * @remarks\n * The one place a request is built, so the key refusal, the proxy body and the failure reading cannot drift between the elements that fetch. A refused key throws before anything is sent; a failed response throws an {@link ApiError} carrying the API message and, for a rejected body, the fields it named.\n */\nexport async function apiFetch<T>(\n\troute: ApiRoute,\n\treq: RoxyRequest,\n\tsignal?: AbortSignal,\n): Promise<T> {\n\tconst refusal = routeRefusal(route);\n\tif (refusal) throw new ApiError(refusal.message);\n\tconst res = route.submitUrl\n\t\t? await fetch(route.submitUrl, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\tAccept: 'application/json',\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t},\n\t\t\t\tbody: proxyBody(req, route.submitContext),\n\t\t\t\tsignal,\n\t\t\t})\n\t\t: await callApi(route, req, signal);\n\tif (!res.ok) {\n\t\tconst failure = await readApiFailure(res);\n\t\tthrow new ApiError(failure.message, failure.issues, failure.worded);\n\t}\n\treturn (await res.json()) as T;\n}\n\n/**\n * The body of a proxied POST: the request, plus the host context under `context` when one is set.\n *\n * @remarks\n * The context is appended rather than declared on {@link RoxyRequest}, so with none set the payload is the request object itself and every route already written against it keeps receiving the same four keys in the same order. A `null` or an empty object would be a fifth key such a route never agreed to read.\n */\nfunction proxyBody(\n\treq: RoxyRequest,\n\tcontext?: Record<string, unknown>,\n): string {\n\treturn JSON.stringify(context ? { ...req, context } : req);\n}\n\n/** Direct call against RoxyAPI with the publishable key (the no-backend path). */\nfunction callApi(\n\troute: ApiRoute,\n\treq: RoxyRequest,\n\tsignal?: AbortSignal,\n): Promise<Response> {\n\t// Resolved against the page, so a same-origin base (\"/api/roxy\") is as valid as an\n\t// absolute one. Every route a host page can name resolves the same way, and a bare\n\t// `new URL()` would reject the relative shape with an opaque \"Invalid URL\".\n\tconst url = new URL(\n\t\t`${route.baseUrl ?? DEFAULT_BASE_URL}${req.path}`,\n\t\tdocument.baseURI,\n\t);\n\tfor (const [k, v] of Object.entries(req.query ?? {})) {\n\t\tif (v != null) url.searchParams.set(k, String(v));\n\t}\n\tconst headers: Record<string, string> = { Accept: 'application/json' };\n\tif (route.publishableKey) headers['X-API-Key'] = route.publishableKey;\n\tif (req.body != null) headers['Content-Type'] = 'application/json';\n\treturn fetch(url, {\n\t\tmethod: req.method ?? 'GET',\n\t\theaders,\n\t\tbody: req.body != null ? JSON.stringify(req.body) : undefined,\n\t\tsignal,\n\t});\n}\n\n/**\n * Client-side fetch for uncontrolled (self-fetching) components: drives `host.data` / `host.loading` / `host.error` and cancels a stale request when a newer one starts or the host disconnects.\n *\n * @remarks\n * Security boundary. The only credential this ever sends is a `pk_` publishable key, which carries a server-side origin allowlist. A secret (`sk_`), legacy unprefixed or sample key is refused before any network call and surfaced as an error, so a server secret cannot leak into a browser request. The request itself goes through {@link apiFetch}, which every other fetch on an element shares.\n *\n * Controlled-mode components never construct this. When a server injects the response as a `<script class=\"roxy-data\">` island, there is no key and no fetch, which is the path server-rendered consumers (WordPress, JSX SSR, static HTML) rely on.\n */\nexport class FetchController<T = unknown>\n\timplements ReactiveController, ApiRoute\n{\n\tprivate readonly host: FetchHost<T>;\n\tprivate abort?: AbortController;\n\n\t/** Browser-safe publishable key. Set by the host from its `publishable-key` attribute. */\n\tpublishableKey?: string;\n\t/** API origin, overridable for self-hosted or proxied deployments. */\n\tbaseUrl = DEFAULT_BASE_URL;\n\t/** Consumer backend route that holds the secret key, set from the host `submit-url` attribute; see {@link ApiRoute.submitUrl}. */\n\tsubmitUrl?: string;\n\t/** Object the host page attaches to the proxied request, set from its `submit-context` attribute; see {@link ApiRoute.submitContext}. */\n\tsubmitContext?: Record<string, unknown>;\n\t/** False when the last failure carried no sentence of its own: a dropped connection, or a body with no `error`. */\n\tworded = true;\n\n\tconstructor(host: FetchHost<T>) {\n\t\tthis.host = host;\n\t\thost.addController(this);\n\t}\n\n\thostDisconnected() {\n\t\tthis.abort?.abort();\n\t\tthis.abort = undefined;\n\t}\n\n\t/**\n\t * Issue the request and resolve once `host.data` (success) or `host.error`\n\t * (failure) is set. A no-op return when the key is refused: the error is\n\t * already surfaced and nothing is sent.\n\t */\n\tasync run(req: RoxyRequest): Promise<void> {\n\t\tthis.worded = true;\n\t\tconst refusal = routeRefusal(this);\n\t\tif (refusal) {\n\t\t\tthis.host.error = refusal.message;\n\t\t\tdispatchKeyRefusal(this.host, refusal);\n\t\t\treturn;\n\t\t}\n\t\tthis.abort?.abort();\n\t\tconst controller = new AbortController();\n\t\tthis.abort = controller;\n\t\tthis.host.loading = true;\n\t\tthis.host.error = null;\n\t\tthis.host.issues = null;\n\t\ttry {\n\t\t\tconst json = await apiFetch<T>(this, req, controller.signal);\n\t\t\tif (controller.signal.aborted) return;\n\t\t\tthis.host.data = json;\n\t\t} catch (err) {\n\t\t\tif (controller.signal.aborted) return;\n\t\t\tif ((err as { name?: string })?.name === 'AbortError') return;\n\t\t\tif (err instanceof ApiError) this.host.issues = err.issues;\n\t\t\tthis.worded = err instanceof ApiError && err.worded;\n\t\t\tthis.host.error = err instanceof Error ? err.message : String(err);\n\t\t} finally {\n\t\t\tif (this.abort === controller) this.abort = undefined;\n\t\t\tif (!controller.signal.aborted) this.host.loading = false;\n\t\t}\n\t}\n}\n\n/**\n * Translate flat form values into a {@link RoxyRequest} for an endpoint. The `{name}` segments in the endpoint template are substituted from the values and removed; the rest become the JSON body for POST or query parameters for GET. This is the spec-light request builder the base element uses to turn a `<roxy-endpoint-form>` submission into a self-fetch, so a component needs no per-endpoint glue.\n *\n * @param queryKeys - Names the spec declares as `in: query` for this operation, which `<roxy-endpoint-form>` reports on its `roxy-submit` event. A POST operation can still take query parameters (every localized endpoint takes `?lang=`), and sending one in the JSON body silently drops it, so those names are routed to the query string on POST as well as GET.\n */\nexport function buildRequest(\n\tendpoint: string,\n\tmethod: 'GET' | 'POST',\n\tvalues: Record<string, unknown>,\n\tqueryKeys: readonly string[] = [],\n): RoxyRequest {\n\tconst rest: Record<string, unknown> = { ...values };\n\tconst path = `/${endpoint.replace(/^\\//, '')}`.replace(\n\t\t/\\{([^}]+)\\}/g,\n\t\t(_match, name: string) => {\n\t\t\tconst v = rest[name];\n\t\t\tdelete rest[name];\n\t\t\treturn encodeURIComponent(String(v ?? ''));\n\t\t},\n\t);\n\tconst inQuery = new Set(queryKeys);\n\tconst query: Record<string, string | number | undefined> = {};\n\tconst body: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(rest)) {\n\t\tif (v === undefined || v === '') continue;\n\t\tif (method === 'GET' || inQuery.has(k)) query[k] = v as string | number;\n\t\telse body[k] = v;\n\t}\n\treturn { path, method, query, body: method === 'POST' ? body : undefined };\n}\n", "/**\n * The interpretation accordion: the one way this library shows a label, a short value, and a body of prose behind a disclosure.\n *\n * @remarks\n * Exclusive by construction (`<details name>`), so a card grows by at most one open section and never becomes a wall of text. Callers pass their own group `name` so two accordions on one page do not fight over which section is open.\n *\n * This lives here rather than in a component because the same accordion is the right shape wherever an endpoint returns a labelled reading: the Human Design bodygraph and type card use it for strategy, authority, and aura; `roxy-hexagram` uses it for the changing lines. A card that draws its own disclosure, because its summary carries more than a label and an aside, still renders the shared body and imports {@link readingDetailStyles} for it rather than restating those rules.\n *\n * **Call it through `RoxyDataElement.renderInterpretation`, never directly.** That method is where `hide-readings` is honoured, so a direct call renders prose a host asked to be left out. The section it emits carries `part=\"section readings\"` and each row `part=\"reading\"`, which is what makes the readings of EVERY component addressable under one name from outside the shadow root.\n */\n\nimport { css, html, nothing } from 'lit';\nimport type { ChromeString } from '../i18n/chrome-strings.js';\nimport { chevron } from './disclosure.js';\nimport type { Translate } from './hd-reading.js';\n\n/** One row: the label, the short value shown as the aside, and the interpretation body. `extra` renders under the body for a section that carries more than prose. */\nexport interface InterpSection {\n\tlabel: string;\n\taside?: string;\n\tbody: string;\n\textra?: unknown;\n}\n\n/**\n * Styles for the markup {@link renderReadingDetail} emits. Import this wherever that helper is called; {@link interpAccordionStyles} already embeds it, so an accordion caller needs only the one.\n *\n * @remarks\n * Separate from the accordion shell because the two are needed independently: a card can draw its own disclosure and still render the shared reading body, and hand-copying these rules is how the chip colour and spacing drifted apart across five components.\n *\n * No margin-top on the chip row. The body above already spaces its children, so a margin here would set the chips twice as far out as every other row.\n */\nexport const readingDetailStyles = css`.interp-keywords{flex-wrap:wrap;gap:.25rem;display:flex}.interp-keywords .kw{border-radius:var(--roxy-radius-full,9999px);background:color-mix(in srgb, var(--roxy-accent,#f59e0b) 14%, transparent);color:var(--roxy-fg,#0a0a0a);font-size:var(--roxy-text-xs,.75rem);padding:1px 8px}`;\n\nexport const interpAccordionStyles = css`.block{border-top:1px solid var(--roxy-border,#e4e4e7);padding-top:var(--roxy-space-md,1rem)}.block h3{margin:0 0 var(--roxy-space-sm,.5rem);font-size:var(--roxy-text-sm,.875rem);font-weight:var(--roxy-weight-bold,600);color:var(--roxy-muted,#71717a);text-transform:uppercase;letter-spacing:.06em}.interp-card{border:1px solid var(--roxy-border,#e4e4e7);border-radius:var(--roxy-radius-md,8px);padding:var(--roxy-space-sm,.5rem) var(--roxy-space-md,1rem);margin-bottom:var(--roxy-space-xs,.25rem)}.interp-card summary{cursor:pointer;color:var(--roxy-fg,#0a0a0a);align-items:center;gap:var(--roxy-space-sm,.5rem);font-weight:500;font-size:var(--roxy-text-sm,.875rem);display:flex}.interp-card summary:focus-visible{outline:2px solid var(--roxy-ring,#f59e0b66);outline-offset:2px;border-radius:var(--roxy-radius-sm,4px)}.interp-lead{flex-wrap:wrap;flex:auto;order:1;align-items:baseline;gap:.4rem;min-width:0;display:inline-flex}.interp-aside{flex-shrink:0;order:2;align-items:center;gap:.5rem;display:inline-flex}.roxy-chevron{order:3}.interp-aside small{color:var(--roxy-muted,#71717a);white-space:nowrap;font-weight:400}@container (width<=26rem){.interp-card summary{flex-wrap:wrap}.roxy-chevron{order:2}.interp-aside{flex-basis:100%;order:3;justify-content:flex-end}}.interp-body{margin-top:var(--roxy-space-sm,.5rem);gap:var(--roxy-space-sm,.5rem);color:var(--roxy-fg,#0a0a0a);font-size:var(--roxy-text-sm,.875rem);overflow-wrap:anywhere;line-height:1.6;display:grid}.interp-body p{margin:0}${readingDetailStyles}`;\n\n/** The keyword chips a reading carries, or nothing. One renderer because four components drew the identical row, and the markup has to match {@link readingDetailStyles}, which is the pairing that drifts when it is copied. */\nexport function renderKeywordChips(keywords: readonly string[] | undefined) {\n\tif (!keywords?.length) return nothing;\n\treturn html`<div class=\"interp-keywords\">${keywords.map((k) => html`<span class=\"kw\">${k}</span>`)}</div>`;\n}\n\n/** The prose an endpoint returns ABOUT one contact: a summary, up to three labelled lines, and the keyword chips under them. Every field is optional, so a narrower response renders fewer rows rather than empty ones. */\nexport interface ReadingDetail {\n\tsummary?: string;\n\timpact?: string;\n\ttiming?: string;\n\tguidance?: string;\n\tkeywords?: readonly string[];\n}\n\n/** Render one {@link ReadingDetail}. The three labels are copy, so this takes the translator, and they are typed {@link ChromeString} because the lookup is one indirection from the call: a scan of `t(...)` sites cannot follow that, and the compiler can. */\nexport function renderReadingDetail(\n\td: ReadingDetail | undefined,\n\tt: Translate,\n) {\n\tif (!d) return nothing;\n\tconst line = (label: ChromeString, value: string | undefined) =>\n\t\tvalue ? html`<p><strong>${t(label)}</strong> ${value}</p>` : nothing;\n\treturn html`${d.summary ? html`<p>${d.summary}</p>` : nothing} ${line('Impact:', d.impact)}${line('Timing:', d.timing)}${line('Guidance:', d.guidance)} ${renderKeywordChips(d.keywords)}`;\n}\n\n/**\n * Render the accordion. Sections with no body are dropped, so a caller can pass the full set and let a narrower response render only what it carries. `name` groups the `<details>` exclusively, so opening one closes the last.\n */\nexport function renderInterpAccordion(\n\tsections: InterpSection[],\n\tname: string,\n\theading: string,\n) {\n\tconst shown = sections.filter((s) => Boolean(s.body));\n\tif (shown.length === 0) return nothing;\n\n\treturn html`<section class=\"block\" part=\"section readings\"><h3>${heading}</h3>${shown.map(\n\t\t\t(\n\t\t\t\ts,\n\t\t\t\ti,\n\t\t\t) => html`<details class=\"interp-card\" part=\"reading\" name=\"${name}\" ?open=\"${i === 0}\"><summary><span class=\"interp-lead\">${s.label}</span> ${chevron()} ${s.aside ? html`<span class=\"interp-aside\"><small>${s.aside}</small></span>` : nothing}</summary><div class=\"interp-body\"><p>${s.body}</p>${s.extra ?? nothing}</div></details>`,\n\t\t)}</section>`;\n}\n", "import type { TemplateResult } from 'lit';\nimport { css, html } from 'lit';\n\n/**\n * Disclosure chevron for `<details>`/`<summary>` accordions. Replaces the\n * browser default triangle with a thin chevron that rotates when the host\n * `<details>` opens. Render it inside the `<summary>` and pair with\n * {@link disclosureStyles}.\n */\nexport function chevron(): TemplateResult {\n\treturn html`<svg class=\"roxy-chevron\" viewBox=\"0 0 16 16\" width=\"14\" height=\"14\" aria-hidden=\"true\"><path d=\"M4 6l4 4 4-4\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>`;\n}\n\n/**\n * Shared `<details>` accordion styling: hides the native disclosure triangle\n * and rotates the {@link chevron} 180 degrees when the accordion is open.\n * Import into any component that renders disclosure accordions so the chevron\n * looks and behaves identically.\n */\nexport const disclosureStyles = css`summary{list-style:none}summary::-webkit-details-marker{display:none}.roxy-chevron{aspect-ratio:auto;width:14px;height:14px;color:var(--roxy-muted,#71717a);transition:transform var(--roxy-motion-duration,.2s) var(--roxy-motion-easing,ease);flex-shrink:0}details[open]>summary .roxy-chevron{transform:rotate(180deg)}@media (prefers-reduced-motion:reduce){.roxy-chevron{transition:none}}`;\n", "import type { ReactiveController, ReactiveControllerHost } from 'lit';\n\n/**\n * Marker class on the inline JSON script a server emits inside a component.\n *\n * @example\n * ```html\n * <roxy-natal-chart>\n * <script type=\"application/json\" class=\"roxy-data\">{ ...response... }</script>\n * </roxy-natal-chart>\n * ```\n */\nconst ROXY_DATA_CLASS = 'roxy-data';\n\n/**\n * Serialize a RoxyAPI response for embedding inside an inline `<script type=\"application/json\" class=\"roxy-data\">`. This is the safe writer counterpart to {@link MarkupDataController}, the reader: server-rendered and cached consumers (WordPress, JSX SSR, static HTML) emit the script with this, and the component hydrates `data` from it on connect.\n *\n * @remarks\n * Use this instead of a bare `JSON.stringify`. A raw stringify of a response that contains the literal text `</script>` (common in long interpretation prose) closes the script element early, corrupting the page and creating an HTML-injection vector. This escapes the script-unsafe characters to their `\\uXXXX` JSON escapes, which `JSON.parse` restores to the original characters, so the value the component receives is identical to the response you passed.\n *\n * `<` is the load-bearing escape (it defeats `</script>` and `<!--`). `>` and `&` are escaped for defence in depth, and U+2028 / U+2029 because they are valid in JSON yet are line terminators in a `<script>` context and break some parsers. The escapes introduce only `\\uXXXX` sequences, so the replacements never feed each other and order is irrelevant.\n *\n * Pass the unwrapped RoxyAPI response, the same shape you would assign to `element.data`. Do not pass the SDK envelope (`{ data, error, request, response }`).\n *\n * @example\n * ```ts\n * import { serializeRoxyData } from '@roxyapi/ui';\n *\n * const { data } = await roxy.dreams.getDreamSymbol({ path: { id: 'water' } });\n * const html = `<roxy-dream-card><script type=\"application/json\" class=\"roxy-data\">${serializeRoxyData(data)}</script></roxy-dream-card>`;\n * ```\n */\nexport function serializeRoxyData(data: unknown): string {\n\treturn JSON.stringify(data)\n\t\t.replace(/</g, '\\\\u003c')\n\t\t.replace(/>/g, '\\\\u003e')\n\t\t.replace(/&/g, '\\\\u0026')\n\t\t.replace(/\\u2028/g, '\\\\u2028')\n\t\t.replace(/\\u2029/g, '\\\\u2029');\n}\n\n/**\n * Build the complete `<script type=\"application/json\" class=\"roxy-data\">…</script>` element a server nests inside a `roxy-*` component for the no-JavaScript hydration path. The payload is escaped via {@link serializeRoxyData}, so it is safe to drop straight into HTML output.\n *\n * @remarks\n * The element carries both `type=\"application/json\"` and `class=\"roxy-data\"` because {@link MarkupDataController} reads only a direct-child script that has both. Emit one of these inside the target component; the JavaScript `data` property still wins if it is later assigned.\n *\n * @example\n * ```ts\n * import { roxyDataScript } from '@roxyapi/ui';\n *\n * const { data } = await roxy.crystals.getCrystal({ path: { id: 'amethyst' } });\n * const html = `<roxy-crystal-grid>${roxyDataScript(data)}</roxy-crystal-grid>`;\n * ```\n */\nexport function roxyDataScript(data: unknown): string {\n\treturn `<script type=\"application/json\" class=\"${ROXY_DATA_CLASS}\">${serializeRoxyData(data)}</script>`;\n}\n\n/**\n * True when the element is a `<script type=\"application/json\">`. Uses tag name and attribute rather than `instanceof HTMLScriptElement` so the check holds in every DOM implementation, including server-rendered and hydration runtimes where the constructor global may be absent.\n */\nfunction isJsonScript(el: Element): boolean {\n\treturn (\n\t\tel.nodeName === 'SCRIPT' && el.getAttribute('type') === 'application/json'\n\t);\n}\n\n/**\n * Host shape the controller drives: any reactive element that exposes a public `data` slot. The controller only writes `data` when the host left it unset, so the JavaScript property path always wins.\n */\ninterface DataHost extends ReactiveControllerHost, HTMLElement {\n\tdata?: unknown;\n}\n\n/**\n * Reactive controller that lets a component hydrate its `data` from embedded markup when no `data` property was assigned in JavaScript.\n *\n * @remarks\n * The server-side and cached-render model: a backend renders the RoxyAPI response into a direct-child `<script type=\"application/json\" class=\"roxy-data\">` element, ships static HTML, and never runs per-element JavaScript to assign a property. On connect this controller reads that script, parses it, and feeds the result to the host. The JavaScript property path is untouched and authoritative: if `host.data` already holds a value when the host connects, the controller does nothing and the markup is ignored.\n *\n * Source resolution order on connect, first hit wins:\n *\n * 1. `host.data` already set in JavaScript -> leave it, read nothing.\n * 2. A direct-child `<script type=\"application/json\" class=\"roxy-data\">` -> parse and use. Direct-child only, so a nested component's own script is never read by an ancestor.\n *\n * Fetching from a URL is intentionally unsupported: that would require a browser-visible key and breaks the server-rendered, cached model these consumers rely on.\n *\n * Timing: {@link hostConnected} runs inside the host `connectedCallback`. For an element parsed from server HTML, its direct children are present by the time the custom element upgrades and connects, so the script is readable here. For an element created with `document.createElement` and connected before any child is appended, there is nothing to read and the property path is the only source, which is exactly the existing behavior.\n *\n * Failure is safe: malformed JSON or a missing script leaves `host.data` untouched, so the host renders its normal empty state.\n *\n * Reading the script never mutates it, and only the marked script is touched, so any sibling fallback markup a server nested inside the element (for no-JavaScript, AMP, or crawler rendering) is left in place.\n *\n * @example\n * ```ts\n * import { MarkupDataController } from '../utils/markup-data.js';\n *\n * export class RoxyExample extends LitElement {\n * constructor() {\n * super();\n * new MarkupDataController(this);\n * }\n *\n * @property({ attribute: false })\n * data: ExampleResponse | null = null;\n * }\n * ```\n */\nexport class MarkupDataController<T = unknown> implements ReactiveController {\n\tprivate readonly host: DataHost;\n\n\tconstructor(host: DataHost) {\n\t\tthis.host = host;\n\t\thost.addController(this);\n\t}\n\n\thostConnected() {\n\t\t// Property path wins. If the consumer (React, vanilla `.data =`, the\n\t\t// widgets script, an MCP agent) already set data, never look at markup.\n\t\tif (this.host.data != null) return;\n\n\t\tconst parsed = this.read();\n\t\tif (parsed === undefined) return;\n\n\t\tthis.host.data = parsed as T;\n\t\tthis.host.requestUpdate();\n\t}\n\n\t/**\n\t * Resolve the embedded payload. Returns `undefined` when there is nothing valid to read so the caller can leave `host.data` untouched.\n\t */\n\tprivate read(): T | undefined {\n\t\tconst inline = this.findInlineScript();\n\t\treturn inline ? this.parse(inline.textContent) : undefined;\n\t}\n\n\t/**\n\t * Direct-child `<script type=\"application/json\" class=\"roxy-data\">`. Scoped to immediate children so a nested data-driven component never has its script read by an ancestor, and so sibling fallback markup is ignored.\n\t */\n\tprivate findInlineScript(): Element | null {\n\t\tfor (const child of Array.from(this.host.children)) {\n\t\t\tif (isJsonScript(child) && child.classList.contains(ROXY_DATA_CLASS)) {\n\t\t\t\treturn child;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate parse(text: string | null): T | undefined {\n\t\tif (!text?.trim()) return undefined;\n\t\ttry {\n\t\t\treturn JSON.parse(text) as T;\n\t\t} catch {\n\t\t\t// Malformed embedded JSON: fail safe, leave the host empty state in\n\t\t\t// place rather than throwing during connect.\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n", "/**\n * Display formatters for ISO timestamps and floats coming back from the API.\n * Every helper returns \"\" for nullish or unparseable input so it falls out of\n * template literals cleanly.\n *\n * @remarks\n * **This file is the ONLY place in the library that may call `Intl` or a `toLocale*` method, and every helper that does takes the locale as its first argument, required.** Both halves are enforced by a source scan in `tests/i18n.test.ts`.\n *\n * The locale is the DISPLAY locale, the full tag `resolveLang` returns, region included. It is NOT the value that goes on `?lang=`: that one is truncated to a supported two-letter code because the API rejects anything else, and handing THAT to Intl would render every Argentine visitor's dates in Castilian conventions. `es-AR` is exactly the tag Intl wants.\n *\n * It is required rather than optional because the failure it prevents is an omission: `toLocaleDateString(undefined, ...)` means the locale of whoever is looking, so a Spanish page renders `Carta natal` above `Jan 15, 1990, 2:30 PM` and two visitors to one page see two different strings. An optional parameter defaults straight back to that. A missing argument is now a typecheck failure at every call site.\n */\n\nimport { capitalize, humanize } from './string.js';\n\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** A bare `YYYY-MM`, which several payloads use to name the month a forecast covers. */\nconst MONTH_ONLY = /^\\d{4}-\\d{2}$/;\nconst BARE_TIME = /^\\d{2}:\\d{2}(:\\d{2})?$/;\n/** An ISO datetime with NO timezone designator: a wall clock, not an instant. */\nconst NAIVE_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/;\n\n/** Canonical form per tag seen, so a page carrying an unparseable `lang` does not throw once per rendered date. */\nconst CANONICAL: Map<string, string> = new Map();\n\n/**\n * The locale list to hand Intl: the page's tag first, English behind it.\n *\n * @remarks\n * Two failure modes, both reachable from a `lang` attribute a site owner typed by hand and neither of which may reach a visitor:\n *\n * - **A structurally invalid tag throws.** `lang=\"english\"` or `lang=\"en_US\"` makes every `toLocale*` call raise a RangeError, which inside a render is a blank component rather than a wrong date. Canonicalizing behind a try/catch degrades it to English instead.\n * - **A valid-but-unknown tag falls back to the RUNTIME default**, which is the viewer's browser again, so the bug reappears for exactly the pages least likely to notice. Naming `en` as the second entry makes the fallback the page's, not the visitor's.\n *\n * No language signal at all resolves to English for the same reason the chrome catalogue does: a page that never declares a language is English as far as this library is concerned, and English chrome over German dates is the inconsistency this whole file exists to remove. `navigator.language` is deliberately absent from the chain here as it is in `resolveLang`: it is the VISITOR's preference, not the site's.\n */\nfunction intlLocales(locale: string | undefined): string[] {\n\tif (!locale) return ['en'];\n\tconst cached = CANONICAL.get(locale);\n\tif (cached) return [cached, 'en'];\n\tlet canonical = 'en';\n\ttry {\n\t\tcanonical = Intl.getCanonicalLocales(locale)[0] ?? 'en';\n\t} catch {\n\t\tcanonical = 'en';\n\t}\n\tCANONICAL.set(locale, canonical);\n\treturn [canonical, 'en'];\n}\n\nconst CLOCK = new Map<string, Intl.DateTimeFormatOptions>();\n\n/** The hour and minute fields in the locale's own short-time style, so a 24-hour locale pads `09:52` and a 12-hour one keeps `9:52 AM`. */\nfunction clock(locale: string | undefined): Intl.DateTimeFormatOptions {\n\tconst key = locale ?? '';\n\tconst cached = CLOCK.get(key);\n\tif (cached) return cached;\n\tconst hour = new Intl.DateTimeFormat(intlLocales(locale), {\n\t\ttimeStyle: 'short',\n\t\ttimeZone: 'UTC',\n\t})\n\t\t.formatToParts(new Date(Date.UTC(2000, 0, 1, 1)))\n\t\t.find((p) => p.type === 'hour')?.value;\n\tconst fields: Intl.DateTimeFormatOptions = {\n\t\thour: hour?.length === 2 ? '2-digit' : 'numeric',\n\t\tminute: '2-digit',\n\t};\n\tCLOCK.set(key, fields);\n\treturn fields;\n}\n\n/** Two formatted ends as one label, falling back to whichever end is present. */\nfunction joinRange(a: string, b: string): string {\n\treturn a && b ? `${a} - ${b}` : a || b;\n}\n\n/**\n * Resolve an API timestamp to a Date plus the timezone it must be RENDERED in.\n *\n * @remarks\n * The API returns chart times naive (`2026-07-13T04:36:00`): that is 04:36 in the CHART's timezone, not UTC and not the viewer's. A wall clock must read the same for every viewer on earth, so hora at sunrise says 04:36 in Tokyo and in Chicago alike.\n *\n * Handing a naive string to `new Date()` makes the runtime interpret it in the VIEWER's zone, which is a silent corruption whenever that wall clock lands in the viewer's DST gap. In America/New_York `2026-03-08T02:30:00` does not exist, so the clock jumps and it renders as `3:30 AM`. Pinning the wall clock to UTC, which has no DST and therefore no gap, preserves the digits exactly while Intl still writes them in the PAGE locale conventions.\n *\n * An offset-bearing timestamp (`...Z`, `...+05:30`) IS a real instant, so it keeps the normal behaviour and converts to the viewer's local time.\n *\n * A DATE_ONLY value (`2026-08-01`) is the same wall clock with the time left off, and it is normalised HERE rather than at each call site because leaving it to the caller is a defect that formats correctly for whoever writes the code: the platform parses a bare date as UTC midnight, and Intl then renders that instant in the VIEWER's zone, so every viewer west of Greenwich reads the previous day. Three helpers pinned it inline and {@link formatDateGrain} did not, which nothing caught because its only caller passes full datetimes.\n *\n * A bare `YYYY-MM` is the same case one grain coarser and carries the same trap, so it is normalised to the first of the month here. Without it a monthly forecast labelled `2026-08` renders as July for every viewer west of Greenwich, or as the raw string wherever a caller decided not to risk it.\n *\n * Deliberately NOT exported. Exporting it lets a component needing a shape these helpers do not offer pin its own wall clock and call Intl itself, which is how a boundary date ends up hardcoded to one locale. A missing shape is added here, beside the locale handling, not reimplemented in a component.\n */\nfunction resolveDisplayDate(input: string): {\n\td: Date;\n\ttimeZone?: string;\n} {\n\tconst naive = BARE_TIME.test(input)\n\t\t? `1970-01-01T${input}`\n\t\t: DATE_ONLY.test(input)\n\t\t\t? `${input}T00:00:00`\n\t\t\t: MONTH_ONLY.test(input)\n\t\t\t\t? `${input}-01T00:00:00`\n\t\t\t\t: NAIVE_DATETIME.test(input)\n\t\t\t\t\t? input\n\t\t\t\t\t: null;\n\treturn naive\n\t\t? { d: new Date(`${naive}Z`), timeZone: 'UTC' }\n\t\t: { d: new Date(input) };\n}\n\n/**\n * The clock, in the page locale: `2:30 PM` in English, `14:30` in German.\n *\n * @remarks\n * The hour cycle is the locale's, never ours. Pinning `hour12: true` puts an AM/PM clock on every page in Europe and Latin America while the embedded form beside it labels its own input \"formato de 24 horas\". CLDR already knows which convention each locale reads, including the ones that surprise you (`es` is 24-hour, `es-AR` is 12-hour with `p. m.`), so asserting a cycle here is asserting we know better than the locale data.\n */\nexport function formatTime(locale: string | undefined, input: unknown): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tif (DATE_ONLY.test(input)) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleTimeString(intlLocales(locale), {\n\t\t...clock(locale),\n\t\ttimeZone,\n\t});\n}\n\nexport function formatDate(locale: string | undefined, input: unknown): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleDateString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\tyear: 'numeric',\n\t\ttimeZone,\n\t});\n}\n\nexport function formatTimeRange(\n\tlocale: string | undefined,\n\tt: { start?: string; end?: string } | undefined,\n): string {\n\tif (!t) return '';\n\treturn joinRange(formatTime(locale, t.start), formatTime(locale, t.end));\n}\n\n/** Two dates as one label: `Jan 1, 2026 - Jan 7, 2026`. Falls back to whichever end parses when the other is absent. */\nexport function formatDateRange(\n\tlocale: string | undefined,\n\tstart: unknown,\n\tend: unknown,\n): string {\n\treturn joinRange(formatDate(locale, start), formatDate(locale, end));\n}\n\n/** How much of a timestamp a label shows. `time` is the whole date plus the clock. */\nexport type DateGrain = 'year' | 'month' | 'day' | 'time';\n\n/**\n * A timestamp at a chosen granularity, for an axis or a bar end where the full date would not fit.\n *\n * @remarks\n * Every grain below `year` carries the year, because a period routinely straddles new year and a label reading `28 Dec - 3 Jan` says nothing about which side moved. `year` is sliced off the string rather than formatted, since a bare four-digit year is the same in every locale this library ships and running it through Intl would introduce era and numbering-system differences into an axis tick.\n */\nexport function formatDateGrain(\n\tlocale: string | undefined,\n\tinput: unknown,\n\tgrain: DateGrain,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tif (grain === 'year') {\n\t\tconst m = input.match(/^(\\d{4})/);\n\t\treturn m?.[1] ?? input;\n\t}\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleString(intlLocales(locale), {\n\t\tday: grain === 'month' ? undefined : 'numeric',\n\t\tmonth: 'short',\n\t\tyear: 'numeric',\n\t\t...(grain === 'time' ? clock(locale) : {}),\n\t\ttimeZone,\n\t});\n}\n\n/**\n * A day inside a month already named elsewhere: `Aug 3`, `3 ago`, `3. Aug.`.\n *\n * @remarks\n * Deliberately WITHOUT the year, which is the one thing {@link formatDateGrain} will not do at any grain below `year`, and for a good reason there: a period can straddle new year and `28 Dec - 3 Jan` says nothing about which side moved. This shape exists for the opposite case, a payload whose own fields pin the month (a monthly ephemeris carries `year` and `month` at the top level and prints them in its header), where repeating the year on thirty-one rows and a dozen chips is noise rather than safety. Do not reach for it where the month is not already on screen.\n *\n * A date-only string is pinned to UTC like every other naive value, so the digits read the same for every viewer instead of rolling back a day west of Greenwich.\n */\nexport function formatMonthDay(\n\tlocale: string | undefined,\n\tinput: unknown,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleDateString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\ttimeZone,\n\t});\n}\n\n/**\n * A day of the month with its weekday: `1 Sat`, `sáb 1`, `Sa., 1.`.\n *\n * @remarks\n * The row label a printed ephemeris uses (`01 Sa`, `02 Su`), and it carries neither the month nor the year because the page header already names both. The weekday is not decoration: half of what a practitioner asks a monthly ephemeris is which DAY of the week a placement falls on, and deriving it from a bare number is exactly the arithmetic a table exists to save. Order and separator belong to the locale, which is why this is one Intl call rather than a join.\n *\n * A date-only string is pinned to UTC like every other naive value, so the weekday cannot roll backwards west of Greenwich.\n */\nexport function formatWeekdayDay(\n\tlocale: string | undefined,\n\tinput: unknown,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d, timeZone } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleDateString(intlLocales(locale), {\n\t\tweekday: 'short',\n\t\tday: 'numeric',\n\t\ttimeZone,\n\t});\n}\n\n/**\n * A calendar month and its year: `August 2026`, `agosto de 2026`, `August 2026`.\n *\n * @remarks\n * Takes the two NUMBERS an endpoint returns rather than a timestamp, because that is the shape a monthly payload echoes, and anchors them at UTC noon for the same reason {@link monthName} does: no timezone can roll the anchor into the neighbouring month. The connective belongs to the locale (`de` in Spanish, nothing in English), which is why this is one Intl call rather than a join of {@link monthName} and the year.\n */\nexport function formatMonthYear(\n\tlocale: string | undefined,\n\tyear: unknown,\n\tmonth: unknown,\n): string {\n\tif (typeof year !== 'number' || !Number.isFinite(year)) return '';\n\tif (typeof month !== 'number' || !Number.isInteger(month)) return '';\n\tif (month < 1 || month > 12) return '';\n\treturn new Date(Date.UTC(year, month - 1, 1, 12)).toLocaleDateString(\n\t\tintlLocales(locale),\n\t\t{ month: 'long', year: 'numeric', timeZone: 'UTC' },\n\t);\n}\n\n/**\n * Month name from a 1-based month number: `January`, `enero`, `janvier`.\n *\n * @remarks\n * Two components carried a byte-identical array of twelve English month names, which is both a duplicated table and a table of something the platform already knows in every language. Anchored to a UTC noon so no timezone can roll the date into the neighbouring month.\n */\nexport function monthName(locale: string | undefined, month: unknown): string {\n\tif (typeof month !== 'number' || !Number.isInteger(month)) return '';\n\tif (month < 1 || month > 12) return '';\n\treturn new Date(Date.UTC(2000, month - 1, 1, 12)).toLocaleDateString(\n\t\tintlLocales(locale),\n\t\t{ month: 'long', timeZone: 'UTC' },\n\t);\n}\n\n/**\n * A whole number with the page locale's digit grouping: `12,345` in English, `12.345` in Spanish.\n *\n * @remarks\n * Rounds rather than truncating, so a caller testing the magnitude (`Math.round(km) === 0`) and this label agree about which side of a boundary a value fell.\n */\nexport function formatInteger(\n\tlocale: string | undefined,\n\tvalue: unknown,\n): string {\n\tif (typeof value !== 'number' || !Number.isFinite(value)) return '';\n\treturn value.toLocaleString(intlLocales(locale), {\n\t\tmaximumFractionDigits: 0,\n\t});\n}\n\n/**\n * A list of names joined the way the reader's language joins one: `Mercury and Jupiter`, `Mercury und Jupiter`, `Меркурий и Юпитер`.\n *\n * @remarks\n * Several responses pack a list into one space separated string, which reads as a typo once it is\n * printed beside other values. The conjunction, the serial comma and the spacing are all CLDR's, and\n * they differ per language, which is exactly why this cannot be a `join(', ')` at a call site.\n *\n * Empty entries are dropped, so a trailing separator in the wire value cannot produce a dangling\n * conjunction, and a single entry comes back as itself.\n *\n * @example\n * ```ts\n * formatList('en', ['Mercury', 'Jupiter']); // 'Mercury and Jupiter'\n * formatList('de', ['Mercury', 'Jupiter']); // 'Mercury und Jupiter'\n * ```\n */\nexport function formatList(\n\tlocale: string | undefined,\n\titems: readonly string[],\n): string {\n\tconst parts = items.filter(Boolean);\n\tif (parts.length < 2) return parts[0] ?? '';\n\treturn new Intl.ListFormat(intlLocales(locale), {\n\t\tstyle: 'long',\n\t\ttype: 'conjunction',\n\t}).format(parts);\n}\n\n/**\n * A number to at most `dp` decimals in the reader's notation: `2.5` in English, `2,5` in German.\n *\n * @remarks Trailing zeros drop on the fractional side only, so `100` at `dp = 0` stays `100`.\n *\n * @example\n * ```ts\n * formatNumber('en', 2.5, 1); // '2.5'\n * formatNumber('de', 2.5, 1); // '2,5'\n * ```\n */\nexport function formatNumber(\n\tlocale: string | undefined,\n\tvalue: unknown,\n\tdp = 1,\n): string {\n\tif (typeof value !== 'number' || !Number.isFinite(value)) return '';\n\treturn value.toLocaleString(intlLocales(locale), {\n\t\tmaximumFractionDigits: dp,\n\t});\n}\n\n/**\n * A 0-to-100 value as a percentage in the reader's notation, which places the sign: `82.5%` in English, `%82,5` in Turkish.\n *\n * @remarks `style: 'percent'` takes a fraction, so the value is divided first.\n */\nexport function formatPercent(\n\tlocale: string | undefined,\n\tvalue: unknown,\n\tdp = 1,\n): string {\n\tif (typeof value !== 'number' || !Number.isFinite(value)) return '';\n\treturn (value / 100).toLocaleString(intlLocales(locale), {\n\t\tstyle: 'percent',\n\t\tmaximumFractionDigits: dp,\n\t});\n}\n\n/**\n * CSS class name per aspect type. Used by natal and synastry chart aspect\n * lines so the same color encoding (harmonious vs challenging) applies in\n * both wheels. Keys are lowercase canonical names, values are CSS class\n * suffixes the chart components define in their `:host` styles.\n */\nexport const ASPECT_CLASS: Record<string, string> = {\n\tconjunction: 'aspect-conjunction',\n\tsextile: 'aspect-sextile',\n\tsquare: 'aspect-square',\n\ttrine: 'aspect-trine',\n\topposition: 'aspect-opposition',\n};\n\n/**\n * Normalize the `type` field on an aspect entry to a lowercase, hyphen-separated canonical name (`SEMI_SEXTILE` and `SEMI SEXTILE` both become `semi-sextile`). Accepts any aspect-shaped object so both natal and synastry inter-aspect entries can share this.\n *\n * @remarks\n * Spaces are folded as well as underscores because the endpoints do not agree on the separator: aspects returns `SEMI SEXTILE` where synastry returns `SEMI_SEXTILE`. Handling only the underscore left the space form failing every {@link ASPECT_CLASS} and `ASPECT_SYMBOL` lookup, so the same aspect rendered hyphenated and correctly coloured in one component and space-separated in the neutral fallback colour in another.\n */\nexport function normalizeAspect(a: { type?: string }): string {\n\treturn (a.type ?? '')\n\t\t.toLowerCase()\n\t\t.trim()\n\t\t.replace(/[\\s_]+/g, '-');\n}\n\n/**\n * Display label for an aspect: `SEMI_SEXTILE` -> `Semi-sextile`.\n *\n * The raw value is an API enum and the table column it lands in is read by practitioners, not parsers. {@link normalizeAspect} stays the lookup key for classes and glyphs; this is the human-facing form.\n */\nexport function formatAspectName(a: { type?: string }): string {\n\treturn capitalize(normalizeAspect(a));\n}\n\n/**\n * Display label for an ayanamsa identifier. `kp-newcomb` -> `KP Newcomb`.\n *\n * The raw values are API enums, and every one of them needs a human form that {@link humanize} cannot derive: KP is an initialism that must stay uppercase, and `raman` is a person, B.V. Raman, not a word. Anything unmapped degrades to a humanized slug rather than rendering the enum. That fallback is a safety net, not a licence to skip the map, since a humanized slug reads as a bare surname where a full name belongs. A test fails if the committed spec gains a frame this map lacks.\n */\nexport const AYANAMSA_LABEL: Record<string, string> = {\n\t'kp-newcomb': 'KP Newcomb',\n\t'kp-old': 'KP Old',\n\tlahiri: 'Lahiri',\n\traman: 'B.V. Raman',\n\n\tcustom: 'Custom',\n};\n\nexport function formatAyanamsa(\n\tlocale: string | undefined,\n\ttype: unknown,\n\tdegrees?: unknown,\n): string {\n\tconst label =\n\t\ttypeof type === 'string' ? (AYANAMSA_LABEL[type] ?? humanize(type)) : '';\n\tconst deg =\n\t\ttypeof degrees === 'number'\n\t\t\t? `${formatNumber(locale, degrees, 2)}\\u00b0`\n\t\t\t: '';\n\tif (label && deg) return `${label} (${deg})`;\n\treturn label || deg;\n}\n\n/**\n * Date plus time in one label: `Jan 15, 1990, 2:30 PM`.\n *\n * @remarks\n * Components were concatenating a raw date and a raw time (`1990-01-15 \\u00b7 14:30:00`) while siblings rendered the same instant through {@link formatDate}. One helper keeps every card reading the same way.\n *\n * Birth details arrive as two fields rather than one timestamp, so `time` may be passed separately; it is merged into a naive datetime, pinned to UTC so the wall clock renders identically for every viewer.\n *\n * @example\n * ```ts\n * formatDateTime('en', '1990-01-15T14:30:00'); // 'Jan 15, 1990, 2:30 PM'\n * formatDateTime('en', '1990-01-15', '14:30:00'); // 'Jan 15, 1990, 2:30 PM'\n * formatDateTime('de', '1990-01-15T14:30:00'); // '15. Jan. 1990, 14:30'\n * formatDateTime('en', '1990-01-15'); // 'Jan 15, 1990'\n * ```\n */\nexport function formatDateTime(\n\tlocale: string | undefined,\n\tinput: unknown,\n\ttime?: unknown,\n): string {\n\tconst merged =\n\t\ttypeof input === 'string' &&\n\t\tDATE_ONLY.test(input) &&\n\t\ttypeof time === 'string' &&\n\t\tBARE_TIME.test(time)\n\t\t\t? `${input}T${time}`\n\t\t\t: input;\n\tif (typeof merged !== 'string' || merged.length === 0) return '';\n\tif (DATE_ONLY.test(merged)) return formatDate(locale, merged);\n\tconst { d, timeZone } = resolveDisplayDate(merged);\n\tif (Number.isNaN(d.getTime())) return merged;\n\t// One Intl call, so the locale joins the date and the clock (Turkish writes no comma).\n\treturn d.toLocaleString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\tyear: 'numeric',\n\t\t...clock(locale),\n\t\ttimeZone,\n\t});\n}\n\n/** Two timestamps as one label, each through {@link formatDateTime}. */\nexport function formatDateTimeRange(\n\tlocale: string | undefined,\n\tstart: unknown,\n\tend: unknown,\n): string {\n\treturn joinRange(formatDateTime(locale, start), formatDateTime(locale, end));\n}\n\n/**\n * An instant on the UTC clock, with the zone named: `Apr 4, 2021, 1:24 PM UTC`.\n *\n * @remarks\n * {@link formatDateTime} converts an offset-bearing timestamp to the viewer's zone, which is right for an event the viewer is living through and wrong for a value that exists to be compared against a printed reference: the Design moment on a bodygraph is published to the minute in UTC, so a reader in Kolkata and one in Chicago must see the same digits. The zone name comes from Intl rather than a typed suffix, so it follows the locale like every other unit here.\n */\nexport function formatDateTimeUtc(\n\tlocale: string | undefined,\n\tinput: unknown,\n): string {\n\tif (typeof input !== 'string' || input.length === 0) return '';\n\tconst { d } = resolveDisplayDate(input);\n\tif (Number.isNaN(d.getTime())) return input;\n\treturn d.toLocaleString(intlLocales(locale), {\n\t\tmonth: 'short',\n\t\tday: 'numeric',\n\t\tyear: 'numeric',\n\t\t...clock(locale),\n\t\ttimeZone: 'UTC',\n\t\ttimeZoneName: 'short',\n\t});\n}\n\n/**\n * The Sanskrit form of a name, but only when it actually differs from the English one.\n *\n * @remarks\n * Several endpoints pair an English `name` with a `sanskritName` that is sometimes the SAME string, because the tradition and the translation coincide (a nakshatra is `Ashwini` either way). Rendering the pair unconditionally then prints `Ashwini (Ashwini)`. That guard is the whole reason this exists: it is one comparison, it is easy to leave out, and leaving it out is invisible until a reader hits a name where the two agree.\n *\n * Presentation deliberately stays with the caller, since the same fact is drawn as a parenthetical in a table cell and as a middot-separated span on a chart heading.\n */\nexport function distinctSanskrit(\n\tname: unknown,\n\tsanskritName: unknown,\n): string | undefined {\n\tif (typeof sanskritName !== 'string' || !sanskritName) return undefined;\n\treturn sanskritName === name ? undefined : sanskritName;\n}\n\n/**\n * `English (Sanskrit)` for a value that carries both, falling back to whichever one exists.\n *\n * @example\n * ```ts\n * formatWithSanskrit('Tuesday', 'Mangalavara'); // 'Tuesday (Mangalavara)'\n * formatWithSanskrit('Ashwini', 'Ashwini'); // 'Ashwini'\n * ```\n */\nexport function formatWithSanskrit(\n\tname: unknown,\n\tsanskritName: unknown,\n): string {\n\tconst english = typeof name === 'string' ? name : '';\n\tconst sanskrit = distinctSanskrit(english, sanskritName);\n\tif (!english) return sanskrit ?? '';\n\treturn sanskrit ? `${english} (${sanskrit})` : english;\n}\n", "/**\n * The value a READER sees, for a response field the API returns twice.\n *\n * @remarks\n * Several endpoints now echo a display translation beside the canonical value: `nameLocalized` next to `name`, `signLocalized` next to `sign`, `typeLocalized` next to `type`. **The canonical field is deliberately always English, whatever `?lang=` says, so it stays safe to compare against in code**, and the localized one is deliberately absent from an English response.\n *\n * That split is the whole contract, and inverting it breaks charts silently rather than loudly: `planetGlyph`, `signGlyph`, `aspectSymbol`, `ASPECT_CLASS`, `SIGNS_ORDER.indexOf`, every `Map` key and every CSS class fragment is keyed on the English name, so pointing one of them at `nameLocalized` resolves to nothing on a translated page and to the same value on an English one, which is exactly the shape of defect that passes every gate (lesson 24). **The lookup stays on the canonical value; only the printed text node, the `title` and the `aria-label` move.**\n *\n * These two helpers exist so that rule lives in one place rather than as a `??` at every call site, and so an English response, where the localized field simply is not there, degrades by construction instead of by remembering. Both take the KEY of the canonical field and derive its partner, so a mistyped key or a field that is not a display string is a compile error rather than a silent empty string.\n */\n\nimport { fieldLabel, optionLabel } from '../i18n/registry.js';\nimport { humanize } from './string.js';\n\n/**\n * The label for a field NAME, which is a different problem from a field VALUE.\n *\n * @remarks\n * A catalogue keyed on English source text cannot reach a name computed per response, so these read the published field-label payload instead and fall back to {@link humanize}, which is exactly what every caller printed before one existed. A name the payload does not carry therefore renders as it always did rather than as a gap.\n *\n * Here rather than in each component because three of them need the identical pairing: the form that asks for a field, and the two generic renderers that label what came back.\n *\n * @param english - The API English label to print where the payload carries none, INSTEAD of the humanized name; the form passes it, so a field reads as the API names it on an English page too.\n */\nexport function displayField(\n\tlang: string | undefined,\n\tname: string,\n\tenglish?: string,\n): string {\n\treturn fieldLabel(lang, name) ?? english ?? humanize(name);\n}\n\n/**\n * The label for one selectable VALUE of a field, same fallback rule.\n *\n * @param fallback - What to print where the payload carries no label, INSTEAD of the humanized value.\n * The default suits a word (`81-pada` reads as `81 pada`) and not an identifier that carries a number\n * a reader checks against a published table: `humanize` turns `gmt-584283` into `Gmt 584283`, which\n * is neither the label nor the identifier. Pass the raw value for those, so an English page prints\n * what a caller stores and a translated one prints the published word.\n */\nexport function displayOption(\n\tlang: string | undefined,\n\tfield: string,\n\tvalue: string,\n\tfallback?: string,\n): string {\n\treturn optionLabel(lang, field, value) ?? fallback ?? humanize(value);\n}\n\n/** The one naming convention every helper here derives from. Ratified by the API and spreading to more operations, so it is matched as a convention and never as a list of field names. */\nconst LOCALIZED = 'Localized';\n\n/** A response row carrying a canonical English `K` plus the optional localized partner the API writes beside it. */\nexport type Localizable<K extends string> = Partial<\n\tRecord<K | `${K}Localized`, string>\n>;\n\n/** The same pairing where the value is a LIST of names, e.g. `retrogradePlanets`. */\nexport type LocalizableList<K extends string> = Partial<\n\tRecord<K | `${K}Localized`, string[]>\n>;\n\n/**\n * The text to print for `key`: the localized value when the response carried one, else the English one.\n *\n * @param english - What to print in the English case INSTEAD of the raw field, for a canonical value that is an API enum with a display form of its own (`type` is `SEMI_SEXTILE` on the wire and `Semi-sextile` on screen). Omit it wherever the canonical value is already the readable one.\n *\n * @example\n * ```ts\n * display(planet, 'name'); // 'Sol' on ?lang=es, 'Sun' on English\n * planetGlyph(planet.name) ?? display(planet, 'name'); // the lookup stays English, the fallback TEXT does not\n * display(aspect, 'type', formatAspectName(aspect)); // 'Trígono', else 'Trine' and never 'TRINE'\n * ```\n */\nexport function display<\n\tT extends Localizable<K>,\n\tK extends Extract<keyof T, string>,\n>(row: T | null | undefined, key: K, english?: string): string {\n\tconst rec = row as Record<string, unknown> | null | undefined;\n\tconst localized = rec?.[`${key}${LOCALIZED}`];\n\tif (typeof localized === 'string' && localized !== '') return localized;\n\tif (english !== undefined) return english;\n\tconst canonical = rec?.[key];\n\treturn typeof canonical === 'string' ? canonical : '';\n}\n\n/**\n * A list field as `{ value, label }` pairs: the English `value` every lookup is keyed on, and the `label` a reader sees.\n *\n * @remarks\n * The localized array is INDEX-ALIGNED with the canonical one, which is the only thing that makes the pairing possible, so it is zipped by position and neither side is ever sorted, filtered or deduped on its own. A list that is short or absent falls back per item, so a partial translation still resolves every glyph.\n */\nexport function displayList<\n\tT extends LocalizableList<K>,\n\tK extends Extract<keyof T, string>,\n>(row: T | null | undefined, key: K): Array<{ value: string; label: string }> {\n\tconst rec = row as Record<string, unknown> | null | undefined;\n\tconst canonical = rec?.[key];\n\tif (!Array.isArray(canonical)) return [];\n\tconst localized = rec?.[`${key}${LOCALIZED}`];\n\tconst labels = Array.isArray(localized) ? localized : [];\n\treturn canonical.map((value, i) => {\n\t\tconst label = labels[i];\n\t\treturn {\n\t\t\tvalue: String(value),\n\t\t\tlabel: typeof label === 'string' && label !== '' ? label : String(value),\n\t\t};\n\t});\n}\n\n/**\n * Fold every `XLocalized` field into its `X` partner: the reader's value under the canonical NAME, and the duplicate key gone.\n *\n * @remarks\n * For a renderer that has no idea what its fields MEAN and derives its columns from `Object.keys(row)`, which is how `<roxy-data>` started drawing `Planet | Planet Localized | Longitude | Sign | Sign Localized` the day the API began sending both. Two extra columns, headed in English, carrying the same fact twice, on a page whose owner changed nothing. That is a regression rather than a missing feature, so it is repaired at the key layer every render path already funnels through rather than at each of them.\n *\n * Three rules, and each has a way of going wrong:\n *\n * - **A `*Localized` key with no canonical partner stays put.** Suppressing on the name alone deletes data the response carries and nothing else is rendering.\n * - **The canonical key keeps its POSITION**, so a translated response and an English one lay out identically, column for column.\n * - **A row with nothing to fold is returned as the same object**, so the English path is not merely equivalent but untouched.\n *\n * The English value is dropped rather than shown beside its translation because the two are the same fact, and the caller here is generic: it cannot know that `sign` is the value a lookup would be keyed on. A component that needs both halves reads them itself with {@link display}.\n */\nexport function foldLocalized<V>(row: Record<string, V>): Record<string, V> {\n\tlet folded: Record<string, V> | undefined;\n\tfor (const key of Object.keys(row)) {\n\t\tif (!key.endsWith(LOCALIZED)) continue;\n\t\tconst base = key.slice(0, -LOCALIZED.length);\n\t\tif (base === '' || !(base in row)) continue;\n\t\tfolded ??= { ...row };\n\t\tconst value = row[key];\n\t\tif (value !== undefined && value !== null && value !== '')\n\t\t\tfolded[base] = value;\n\t\tdelete folded[key];\n\t}\n\treturn folded ?? row;\n}\n", "import { css } from 'lit';\n\n/**\n * A data table that stacks into rows of label and value once its card is too narrow to hold its columns.\n *\n * @remarks\n * **The case it exists for is a table carrying a PROSE column.** Three columns share a card happily\n * until one of them holds a sentence: on a phone the sentence gets whatever is left after the other\n * two, which is around a third of 250 pixels, and a paragraph rendered five characters wide is a\n * column of one word lines. A horizontal scroll box does not answer it either, because the reader is\n * then scrolling a paragraph rather than reading it.\n *\n * Stacked, each cell takes the full width with its column heading in front of it, and the prose gets\n * the whole card. The heading comes from `data-label` on the cell, painted through `content`, so the\n * markup stays ONE table and there is no second render path to keep in step. Two consequences worth\n * knowing: the label is translated copy, so it goes through `t()` like any other string and the i18n\n * scan reads that attribute; and painted text is not selectable, which is why the value stays a real\n * text node and only the heading is painted.\n *\n * Opt in with `class=\"stacked\"` on the table plus a `data-label` per cell, and import this beside the\n * component's own styles. Everything above the breakpoint is untouched, so a card that has room keeps\n * its table.\n */\nexport const stackedTableStyles = css`@container (width<=30rem){table.stacked,table.stacked caption,table.stacked tbody,table.stacked tr,table.stacked td{width:100%;min-width:0;display:block}table.stacked thead{display:none}table.stacked tr{border-bottom:1px solid var(--roxy-border,#e4e4e7);padding-block:var(--roxy-space-sm,.5rem)}table.stacked tr:last-child{border-bottom:0}table.stacked td{white-space:normal;border:0;padding:.1rem 0}table.stacked td:empty{display:none}table.stacked td[data-label]:before{content:attr(data-label) \" \";color:var(--roxy-muted,#71717a);font-size:var(--roxy-text-xs,.75rem);text-transform:uppercase;letter-spacing:.06em;font-weight:var(--roxy-weight-bold,600)}}`;\n"],
5
+ "mappings": "4MAAA,OAAS,OAAAA,GAAK,QAAAC,EAAM,WAAAC,MAAe,MACnC,OAAS,iBAAAC,OAAqB,oBAC9B,OAAS,aAAAC,OAAiB,+BCF1B,OAGC,QAAAC,EACA,WAAAC,MAEM,MACP,OAAS,YAAAC,EAAU,SAAAC,MAAa,oBAChC,OAAS,aAAAC,MAAiB,+BCKnB,IAAMC,EAAmC,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,UAAU,SAAS,ECgBrG,SAASC,EAAYC,EAAqC,CAGhE,GAAIA,EAAG,KAAM,OAAOA,EAAG,KACvB,GAAI,OAAO,SAAa,IAAa,OACrC,IAAMC,EAAYD,EAAG,UAAU,QAAQ,GAAG,aAAa,MAAM,EAC7D,OAAIC,GACG,SAAS,gBAAgB,MAAQ,MACzC,CAgBA,IAAMC,GAAwD,CAC7D,GAAI,OACJ,GAAI,OACJ,GAAI,OACJ,GAAI,OACJ,GAAI,OACJ,GAAI,MACL,EAGA,SAASC,EAAUC,EAAiC,CACnD,IAAMC,EAASD,EAAI,YA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E,KAAK,CAAC,YACzF,CAAC,kCACN,CAUQ,kBAAkBC,EAAkD,CAC3E,IAAM3B,EAAS,KAAK,cAAc,EAI5B4B,EAAiC,CAAC,EACxC,QAAWC,IAAO,CAAC,kBAAmB,aAAa,EAAY,CAC9D,IAAMC,EAAQH,IAAcE,CAAG,EAC1BC,GACLF,EAAM,KAAK,CACVG,GAAa/B,EAAQ6B,CAAG,EACxBG,GAAchC,EAAQ6B,EAAKC,CAAK,CACjC,CAAC,CACF,CACA,OAAIF,EAAM,SAAW,EAAUxB,EACxBD,0BAA6ByB,EAAM,IACxC,CAAC,CAACK,EAAOH,CAAK,EAAGT,IAChBlB,IAAOkB,EAAI,EAAI,MAAQ,EAAE,qBAAqBY,CAAK,UAAUH,CAAK,EACpE,CAAC,MACH,CACD,EAxMajC,EACL,OAAS,CACfqC,EACAC,GACAC,khHACD,EALYvC,EAANwC,EAAA,CADNC,GAAc,eAAe,GACjBzC",
6
6
  "names": ["css", "html", "nothing", "customElement", "ifDefined", "html", "nothing", "property", "state", "ifDefined", "API_LANGUAGES", "resolveLang", "el", "inherited", "ZH_SCRIPT_BY_REGION", "asApiLang", "tag", "wanted", "API_LANGUAGES", "l", "apiLang", "exact", "parts", "base", "script", "p", "LitElement", "lookupKey", "s", "humanize", "s", "c", "GLOBAL_KEY", "registry", "holder", "existing", "created", "interpolate", "template", "vars", "match", "key", "translate", "lang", "source", "chromeLabel", "catalogs", "registry", "tag", "lookupKey", "labelsFor", "lang", "fieldLabels", "registry", "tag", "fieldLabel", "name", "optionLabel", "field", "value", "onLocaleChange", "listener", "listeners", "LocaleController", "host", "onLocaleChange", "RoxyLocalizedElement", "LitElement", "source", "vars", "LocaleController", "translate", "resolveLang", "css", "baseStyles", "COLS", "ROWS", "isPlainObject", "value", "decode", "rebuilt", "out", "item", "next", "cols", "rows", "row", "col", "i", "key", "expandCompact", "SAMPLE_PUBLISHABLE_KEY", "KEY_REFUSALS", "keyRefusal", "key", "dispatchKeyRefusal", "host", "refusal", "opts", "DEFAULT_BASE_URL", "readApiFailure", "res", "body", "issues", "i", "ApiError", "message", "worded", "routeRefusal", "route", "keyRefusal", "apiFetch", "route", "req", "signal", "refusal", "routeRefusal", "ApiError", "res", "proxyBody", "callApi", "failure", "readApiFailure", "context", "url", "DEFAULT_BASE_URL", "k", "v", "headers", "FetchController", "host", "dispatchKeyRefusal", "controller", "json", "err", "buildRequest", "endpoint", "method", "values", "queryKeys", "rest", "path", "_match", "name", "inQuery", "query", "body", "css", "html", "nothing", "css", "html", "chevron", "disclosureStyles", "readingDetailStyles", "css", "interpAccordionStyles", "renderInterpAccordion", "sections", "name", "heading", "shown", "s", "nothing", "html", "i", "chevron", "ROXY_DATA_CLASS", "isJsonScript", "el", "MarkupDataController", "host", "parsed", "inline", "child", "ROXY_DATA_CLASS", "text", "submitContextConverter", "value", "parsed", "RoxyDataElement", "RoxyLocalizedElement", "req", "key", "rows", "next", "apiFetch", "added", "err", "e", "detail", "buildRequest", "MarkupDataController", "FetchController", "baseStyles", "changed", "expanded", "expandCompact", "html", "data", "ifDefined", "names", "nothing", "rules", "sections", "name", "heading", "renderInterpAccordion", "body", "total", "id", "el", "lang", "apiLang", "raw", "values", "message", "banner", "__decorateClass", "property", "state", "CANONICAL", "intlLocales", "locale", "cached", "canonical", "formatInteger", "locale", "value", "intlLocales", "displayField", "lang", "name", "english", "fieldLabel", "humanize", "displayOption", "field", "value", "fallback", "optionLabel", "css", "stackedTableStyles", "RoxyGematria", "RoxyDataElement", "d", "locale", "chosen", "input", "html", "nothing", "forms", "f", "letters", "rows", "l", "ifDefined", "formatInteger", "values", "heading", "v", "alternates", "humanize", "n", "seen", "tradition", "source", "i", "form", "first", "table", "r", "m", "conventions", "pairs", "key", "value", "displayField", "displayOption", "label", "baseStyles", "stackedTableStyles", "css", "__decorateClass", "customElement"]
7
7
  }