1
2export const listOf = (v) => (Array.isArray(v) ? v : String(v ?? '').split(/[,\n]+/)).map((s) => String(s ?? '').trim()).filter(Boolean);
3export const pad10 = (cik) => String(cik).replace(/\D/g, '').padStart(10, '0');
4
5
6export const METRICS = {
7 revenue: { kind: 'flow', gaap: ['RevenueFromContractWithCustomerExcludingAssessedTax', 'Revenues', 'SalesRevenueNet', 'RevenueFromContractWithCustomerIncludingAssessedTax', 'SalesRevenueGoodsNet', 'SalesRevenueServicesNet', 'RevenuesNetOfInterestExpense', 'OperatingLeasesIncomeStatementLeaseRevenue'], ifrs: ['Revenue', 'RevenueFromContractsWithCustomers'] },
8 costOfRevenue: { kind: 'flow', gaap: ['CostOfRevenue', 'CostOfGoodsAndServicesSold', 'CostOfGoodsSold', 'CostOfServices'], ifrs: ['CostOfSales'] },
9 grossProfit: { kind: 'flow', gaap: ['GrossProfit'], ifrs: ['GrossProfit'] },
10 researchAndDevelopment: { kind: 'flow', gaap: ['ResearchAndDevelopmentExpense', 'ResearchAndDevelopmentExpenseExcludingAcquiredInProcessCost'], ifrs: ['ResearchAndDevelopmentExpense'] },
11 sellingGeneralAdmin: { kind: 'flow', gaap: ['SellingGeneralAndAdministrativeExpense'], ifrs: ['SellingGeneralAndAdministrativeExpense'] },
12 operatingIncome: { kind: 'flow', gaap: ['OperatingIncomeLoss'], ifrs: ['ProfitLossFromOperatingActivities'] },
13 netIncome: { kind: 'flow', gaap: ['NetIncomeLoss', 'NetIncomeLossAvailableToCommonStockholdersBasic', 'ProfitLoss'], ifrs: ['ProfitLossAttributableToOwnersOfParent', 'ProfitLoss'] },
14 epsBasic: { kind: 'perShare', gaap: ['EarningsPerShareBasic', 'EarningsPerShareBasicAndDiluted'], ifrs: ['BasicEarningsLossPerShare'] },
15 epsDiluted: { kind: 'perShare', gaap: ['EarningsPerShareDiluted', 'EarningsPerShareBasicAndDiluted'], ifrs: ['DilutedEarningsLossPerShare'] },
16 dilutedSharesWeighted: { kind: 'shares', gaap: ['WeightedAverageNumberOfDilutedSharesOutstanding'], ifrs: ['AdjustedWeightedAverageShares'] },
17 operatingCashFlow: { kind: 'flow', gaap: ['NetCashProvidedByUsedInOperatingActivities', 'NetCashProvidedByUsedInOperatingActivitiesContinuingOperations'], ifrs: ['CashFlowsFromUsedInOperatingActivities'] },
18 capitalExpenditure: { kind: 'flow', gaap: ['PaymentsToAcquirePropertyPlantAndEquipment', 'PaymentsToAcquireProductiveAssets'], ifrs: ['PurchaseOfPropertyPlantAndEquipmentClassifiedAsInvestingActivities', 'PurchaseOfPropertyPlantAndEquipment'] },
19 cashAndEquivalents: { kind: 'instant', gaap: ['CashAndCashEquivalentsAtCarryingValue', 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents', 'Cash'], ifrs: ['CashAndCashEquivalents'] },
20 totalAssets: { kind: 'instant', gaap: ['Assets'], ifrs: ['Assets'] },
21 totalLiabilities: { kind: 'instant', gaap: ['Liabilities'], ifrs: ['Liabilities'] },
22 stockholdersEquity: { kind: 'instant', gaap: ['StockholdersEquity', 'StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest'], ifrs: ['EquityAttributableToOwnersOfParent', 'Equity'] },
23 longTermDebt: { kind: 'instant', gaap: ['LongTermDebtNoncurrent', 'LongTermDebt'], ifrs: ['NoncurrentPortionOfNoncurrentBorrowings', 'NoncurrentBorrowings'] },
24};
25export const METRIC_NAMES = Object.keys(METRICS);
26const ANNUAL_FORMS = new Set(['10-K', '10-KT', '20-F', '40-F', '10-K405']);
27const QUARTER_FORMS = new Set(['10-Q', '10-QT']);
28const base = (f) => String(f ?? '').replace(/\/A$/, '');
29const DAY = 86400000;
30export const days = (a, b) => Math.round((Date.parse(b) - Date.parse(a)) / DAY);
31export const addDays = (iso, n) => new Date(Date.parse(iso) + n * DAY).toISOString().slice(0, 10);
32
33
34export function pickTaxonomy(facts) {
35 const f = facts?.facts ?? {};
36 const gaapN = Object.keys(f['us-gaap'] ?? {}).length; const ifrsN = Object.keys(f['ifrs-full'] ?? {}).length;
37 if (!gaapN && !ifrsN) return null;
38 const tax = gaapN >= ifrsN ? 'us-gaap' : 'ifrs-full';
39 const counts = {};
40 for (const c of Object.values(f[tax])) for (const [u, arr] of Object.entries(c.units ?? {})) if (/^[A-Z]{3}$/.test(u)) counts[u] = (counts[u] ?? 0) + arr.length;
41 const currency = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] ?? 'USD';
42 return { tax, key: tax === 'us-gaap' ? 'gaap' : 'ifrs', currency };
43}
44
45function unitsFor(kind, currency) { return kind === 'perShare' ? [`${currency}/shares`] : kind === 'shares' ? ['shares'] : [currency]; }
46
47
48function factsOf(facts, tax, concept, kind, currency) {
49 const c = facts.facts?.[tax]?.[concept]; if (!c) return [];
50 for (const u of unitsFor(kind, currency)) if (c.units?.[u]) return c.units[u].map((x) => ({ ...x, concept }));
51 return [];
52}
53
54
55export function reportPeriods(facts, tx) {
56 const probe = ['netIncome', 'revenue', 'totalAssets', 'operatingIncome', 'stockholdersEquity'];
57 const byAccn = new Map();
58 for (const m of probe) for (const concept of METRICS[m][tx.key]) for (const x of factsOf(facts, tx.tax, concept, METRICS[m].kind, tx.currency)) {
59 const form = base(x.form); if (!ANNUAL_FORMS.has(form) && !QUARTER_FORMS.has(form)) continue;
60 if (String(x.form).endsWith('/A')) continue;
61 const p = byAccn.get(x.accn);
62 if (!p || x.end > p.end) byAccn.set(x.accn, { end: x.end, fy: x.fy ?? null, fp: x.fp ?? null, form: x.form, accn: x.accn, filed: x.filed });
63 }
64
65 const byEnd = new Map();
66 for (const p of byAccn.values()) { const q = byEnd.get(p.end); if (!q || p.filed < q.filed) byEnd.set(p.end, p); }
67 return [...byEnd.values()].sort((a, b) => (a.end < b.end ? -1 : 1));
68}
69
70
71export function periodWindows(facts, tx, periods) {
72 const flows = [];
73 for (const m of ['revenue', 'netIncome', 'operatingIncome', 'operatingCashFlow']) for (const concept of METRICS[m][tx.key]) flows.push(...factsOf(facts, tx.tax, concept, 'flow', tx.currency));
74 const startsFor = (end, lo, hi) => flows.filter((x) => x.start && x.end === end && days(x.start, x.end) >= lo && days(x.start, x.end) <= hi).map((x) => x.start);
75 const annual = []; const quarterly = [];
76 const annualP = periods.filter((p) => ANNUAL_FORMS.has(base(p.form)));
77 for (const p of annualP) {
78 const s = startsFor(p.end, 340, 390)[0];
79 annual.push({ ...p, periodType: 'annual', fiscalPeriod: 'FY', start: s ?? addDays(p.end, -364) });
80 }
81 const all = periods;
82 for (let i = 0; i < all.length; i++) {
83 const p = all[i]; const isAnnual = ANNUAL_FORMS.has(base(p.form));
84 if (isAnnual && base(p.form) !== '10-K' && base(p.form) !== '10-KT') continue;
85 let s = startsFor(p.end, 80, 100)[0];
86 const prev = all[i - 1];
87 if (!s && prev && days(prev.end, p.end) >= 80 && days(prev.end, p.end) <= 100) s = addDays(prev.end, 1);
88 if (!s) continue;
89 quarterly.push({ ...p, periodType: 'quarterly', fiscalPeriod: isAnnual ? 'Q4' : (p.fp && /^Q[1-3]$/.test(p.fp) ? p.fp : null), start: s });
90 }
91
92 for (const a of annual) a.fiscalYear = a.fy ?? (Number(a.end.slice(0, 4)) - (Number(a.end.slice(5, 7)) <= 1 ? 1 : 0));
93 for (const q of quarterly) {
94 const fyw = annual.find((a) => q.end > a.start && q.end <= a.end) ?? annual.find((a) => q.end > addDays(a.end, -1) && q.end <= addDays(a.end, 366));
95 q.fiscalYear = q.fy ?? (fyw && q.end <= fyw.end ? fyw.fiscalYear : null);
96 if (!q.fiscalPeriod && fyw) { const k = Math.round(days(fyw.start, q.end) / 91.3); q.fiscalPeriod = `Q${Math.min(4, Math.max(1, k))}`; }
97 }
98 for (const q of quarterly) if (q.fiscalYear == null) q.fiscalYear = q.fy ?? Number(q.end.slice(0, 4));
99 return { annual, quarterly };
100}
101
102const latest = (arr) => arr.reduce((a, b) => (!a || b.filed > a.filed ? b : a), null);
103const earliest = (arr) => arr.reduce((a, b) => (!a || b.filed < a.filed ? b : a), null);
104const near = (a, b, tol = 4) => Math.abs(days(a, b)) <= tol;
105
106
107export function metricValue(facts, tx, metric, w) {
108 const def = METRICS[metric];
109 for (const concept of def[tx.key]) {
110 const fs = factsOf(facts, tx.tax, concept, def.kind, tx.currency);
111 if (!fs.length) continue;
112 if (def.kind === 'instant') {
113 const hit = fs.filter((x) => !x.start && x.end === w.end);
114 if (hit.length) { const l = latest(hit); const o = earliest(hit); return { value: l.val, concept, derived: false, restated: l.val !== o.val }; }
115 continue;
116 }
117 const exact = fs.filter((x) => x.start && x.end === w.end && near(x.start, w.start));
118 if (exact.length) { const l = latest(exact); const o = earliest(exact); return { value: l.val, concept, derived: false, restated: l.val !== o.val }; }
119 if (def.kind !== 'flow') continue;
120
121 const ytd = fs.filter((x) => x.start && x.end === w.end && days(x.start, w.start) > 20);
122 for (const a of ytd.sort((p, q) => (p.start < q.start ? 1 : -1))) {
123 const b = fs.filter((x) => x.start && near(x.start, a.start) && near(x.end, addDays(w.start, -1)));
124 if (b.length) return { value: latest([a]).val - latest(b).val, concept, derived: true, restated: false };
125 }
126 }
127 return null;
128}
129
130function instantOf(facts, tx, concepts, end) {
131 for (const c of concepts) { const hit = factsOf(facts, tx.tax, c, 'instant', tx.currency).filter((x) => !x.start && x.end === end); if (hit.length) return latest(hit).val; }
132 return null;
133}
134const r4 = (x) => (x == null || !Number.isFinite(x) ? null : Math.round(x * 10000) / 10000);
135
136export function buildRow(facts, tx, w, { includeSources = false } = {}) {
137 const row = {}; const sources = {}; const derived = []; let restated = false;
138 for (const m of METRIC_NAMES) {
139 const v = metricValue(facts, tx, m, w);
140 row[m] = v ? v.value : null;
141 if (v) { sources[m] = v.concept; if (v.derived) derived.push(m); if (v.restated) restated = true; }
142 }
143 if (row.grossProfit == null && row.revenue != null && row.costOfRevenue != null) { row.grossProfit = row.revenue - row.costOfRevenue; derived.push('grossProfit'); sources.grossProfit = 'revenue - costOfRevenue'; }
144 if (row.totalLiabilities == null) {
145 const le = instantOf(facts, tx, tx.key === 'gaap' ? ['LiabilitiesAndStockholdersEquity'] : ['EquityAndLiabilities'], w.end);
146 const eq = instantOf(facts, tx, tx.key === 'gaap' ? ['StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest', 'StockholdersEquity'] : ['Equity'], w.end);
147 if (le != null && eq != null) { row.totalLiabilities = le - eq; derived.push('totalLiabilities'); sources.totalLiabilities = 'LiabilitiesAndStockholdersEquity - equity'; }
148 }
149 row.freeCashFlow = row.operatingCashFlow != null && row.capitalExpenditure != null ? row.operatingCashFlow - row.capitalExpenditure : null;
150 const div = (a, b) => (a != null && b ? r4(a / b) : null);
151 row.grossMargin = div(row.grossProfit, row.revenue); row.operatingMargin = div(row.operatingIncome, row.revenue); row.netMargin = div(row.netIncome, row.revenue);
152 const out = { periodType: w.periodType, fiscalYear: w.fiscalYear ?? null, fiscalPeriod: w.fiscalPeriod ?? null, periodStart: w.start, periodEnd: w.end, form: w.form, filed: w.filed, accessionNumber: w.accn, currency: tx.currency, taxonomy: tx.tax, ...row, revenueGrowthYoY: null, derivedMetrics: derived, restated };
153 if (includeSources) out.sources = sources;
154 out.metricsFound = METRIC_NAMES.filter((m) => row[m] != null).length;
155 return out;
156}
157
158
159export function addGrowth(rows) {
160 for (const r of rows) {
161 const prev = rows.find((p) => p.periodType === r.periodType && p.fiscalPeriod === r.fiscalPeriod && Math.abs(days(p.periodEnd, addDays(r.periodEnd, -365))) <= 10);
162 r.revenueGrowthYoY = prev && prev.revenue && r.revenue != null ? r4(r.revenue / prev.revenue - 1) : null;
163 }
164 return rows;
165}
166
167
168export function filingUrl(cik, accn) { return accn ? `https://www.sec.gov/Archives/edgar/data/${Number(cik)}/${accn.replace(/-/g, '')}/${accn}-index.htm` : null; }
169
170const norm = (s) => String(s ?? '').toLowerCase().replace(/&/g, ' and ').replace(/[.,'’()]/g, '').replace(/\b(inc|incorporated|corp|corporation|co|company|ltd|limited|plc|holdings?|group|sa|nv|ag|the|class [a-z])\b/g, ' ').replace(/[^a-z0-9]+/g, ' ').trim();
171
172export function resolveCompany(q, rows) {
173 const s = String(q).trim();
174 if (/^\d{1,10}$/.test(s)) { const cik = Number(s); const hit = rows.find((r) => r.cik === cik); return { match: hit ?? { cik, ticker: null, title: null }, how: 'cik' }; }
175 const t = s.toUpperCase().replace(/^\$/, '').replace(/\./g, '-');
176 const byTicker = rows.find((r) => r.ticker === t);
177 if (byTicker && /^[A-Z0-9-]{1,10}$/.test(t)) return { match: byTicker, how: 'ticker' };
178 const n = norm(s); if (!n) return { match: null, how: 'name', candidates: [] };
179 const seen = new Set(); const uniq = rows.filter((r) => (seen.has(r.cik) ? false : seen.add(r.cik)));
180 const exact = uniq.filter((r) => norm(r.title) === n);
181 if (exact.length === 1) return { match: exact[0], how: 'name' };
182 const pre = (exact.length ? exact : uniq.filter((r) => norm(r.title).startsWith(`${n} `) || norm(r.title) === n));
183 if (pre.length === 1) return { match: pre[0], how: 'name' };
184 const cands = (pre.length ? pre : uniq.filter((r) => norm(r.title).includes(n))).slice(0, 5);
185 if (cands.length === 1) return { match: cands[0], how: 'name' };
186 return { match: null, how: 'name', candidates: cands.map((r) => ({ cik: r.cik, ticker: r.ticker, name: r.title })) };
187}