railyard/apps/insights/scripts/check-missing-messages.js
caelum0x 1bc04fa81b feat(insights): the Insights fork behind the add-on, site entries, tenant summaries, caps that say what happens (PY1.3)
Railyard side of PY1.3 (RYP-D2, RYP-E1, SC-E3). Acceptance:
1. apps/insights: umami-software/umami v3.4.0 (MIT, commit ec0ff503),
   vendored --depth 1, LICENSE kept, NOTICE added. Fork additions only:
   src/railyard/{ingest,summary,tenancy,api-only}.ts, /v1/ingest/batch (the
   edge collector contract v1, bearer INSIGHTS_INGEST_TOKEN, no IP ever,
   retried batches de-duplicated by migration 90_railyard_ingest_receipts),
   /api/v1/tenants/{org}/summary (bearer INSIGHTS_API_TOKEN), src/proxy.ts
   (INSIGHTS_API_ONLY=1 serves only the Railyard API and the heartbeat).
   Tenant isolation is tested at the API level (an app id owned by another org
   is refused) and at the SQL level (upstream migrations 01-26 plus 90 on a
   throwaway cluster: org B never reads org A's rows, even naming its app).
   Upstream vitest suite: not run on the Mac (pnpm 12.3.4 pinned upstream,
   disk floor); it runs in the image build on box 2 or CI.
2. No upstream product name in anything a customer loads: the page tag, the
   console pages and the fork's additions (tests); the upstream dashboard is
   never served in API-only mode.
3. The console writes the collector's site entry on "Add app", on
   auto-created apps from deploys, and rewrites every entry on add-on, plan or
   pause changes (lib/sites.ts, SITES KV binding). The bridge gains
   `sites` (the project's app, site key, page tag and collector URLs, entry
   written) and the analytics proof is the first event from Insights. The
   console's Insights page shows visitors, events, first event and the
   visit -> signup -> first action funnel.
5. insights-edge/src/caps.ts: at 100% of the cap events are still counted and
   not stored until the next UTC month; the console shows the same message
   from a byte-identical copy (lib/caps.ts, tested).
4 (384 MB at 50 events a second for 10 min) is measured on staging before deploy.

Env: INSIGHTS_API_URL, INSIGHTS_API_TOKEN, SITES KV binding (console);
INSIGHTS_INGEST_TOKEN, INSIGHTS_API_TOKEN, INSIGHTS_API_ONLY (Insights).

Tests: console 54/54 (tsc clean), insights fork 7/7 (incl. SQL isolation),
insights-edge caps + collector + sim 14/14, tests/contract 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:23:38 +03:00

138 lines
3.9 KiB
JavaScript

import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const messagesDir = join(__dirname, '..', 'public', 'intl', 'messages');
const sourcePath = join(messagesDir, 'en-US.json');
const removeExtraKeys = process.argv.includes('--remove-extra-keys');
const help = process.argv.includes('--help') || process.argv.includes('-h');
if (help) {
console.log('Usage: node scripts/check-missing-messages.js [--remove-extra-keys]');
process.exit(0);
}
const enRaw = readFileSync(sourcePath, 'utf8');
const newline = enRaw.includes('\r\n') ? '\r\n' : '\n';
const en = JSON.parse(enRaw);
// Flatten nested structure: { label: { foo: 'bar' } } -> { 'label.foo': 'bar' }
function flatten(obj, prefix = '') {
const result = {};
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k;
if (typeof v === 'object' && v !== null) {
Object.assign(result, flatten(v, key));
} else {
result[key] = v;
}
}
return result;
}
function setNestedValue(target, flatKey, value) {
const parts = flatKey.split('.');
let current = target;
for (let index = 0; index < parts.length - 1; index++) {
current[parts[index]] ??= {};
current = current[parts[index]];
}
current[parts.at(-1)] = value;
}
function buildNormalizedObject(flat) {
const ordered = {};
for (const key of enKeys) {
if (key in flat) {
setNestedValue(ordered, key, flat[key]);
}
}
return ordered;
}
const enFlat = flatten(en);
const enKeys = Object.keys(enFlat);
const enKeySet = new Set(enKeys);
console.log(`en-US.json has ${enKeys.length} keys`);
const files = readdirSync(messagesDir)
.filter(f => f.endsWith('.json') && f !== 'en-US.json')
.sort();
const allMissing = {};
const allExtra = {};
let totalMissing = 0;
let totalExtra = 0;
let updatedFiles = 0;
for (const fname of files) {
const filePath = join(messagesDir, fname);
const raw = readFileSync(filePath, 'utf8');
const data = JSON.parse(raw);
const flat = flatten(data);
const missing = enKeys.filter(k => !(k in flat));
const extra = Object.keys(flat).filter(k => !enKeySet.has(k)).sort();
if (missing.length) {
allMissing[fname] = missing;
console.log(`${fname}: ${missing.length} missing`);
totalMissing += missing.length;
}
if (extra.length) {
allExtra[fname] = extra;
console.log(`${fname}: ${extra.length} extra`);
totalExtra += extra.length;
}
if (removeExtraKeys && extra.length) {
const normalized = buildNormalizedObject(flat);
const nextRaw = `${JSON.stringify(normalized, null, 2).replace(/\n/g, newline)}${newline}`;
if (nextRaw !== raw) {
writeFileSync(filePath, nextRaw, 'utf8');
updatedFiles++;
}
}
}
console.log(`\nTotal missing across all locales: ${totalMissing}`);
console.log(`Total extra across all locales: ${totalExtra}`);
if (removeExtraKeys) {
console.log(`Files updated to remove extra keys: ${updatedFiles}`);
}
const keyCounts = {};
for (const missing of Object.values(allMissing)) {
for (const k of missing) {
keyCounts[k] = (keyCounts[k] || 0) + 1;
}
}
const sorted = Object.entries(keyCounts).sort((a, b) => b[1] - a[1]);
if (sorted.length) {
console.log('\nMost commonly missing keys:');
for (const [k, count] of sorted) {
console.log(` "${k}": missing from ${count} files (en value: "${enFlat[k]}")`);
}
}
const extraKeyCounts = {};
for (const extra of Object.values(allExtra)) {
for (const k of extra) {
extraKeyCounts[k] = (extraKeyCounts[k] || 0) + 1;
}
}
const sortedExtra = Object.entries(extraKeyCounts).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
if (sortedExtra.length) {
console.log('\nMost commonly extra keys:');
for (const [k, count] of sortedExtra) {
console.log(` "${k}": extra in ${count} files`);
}
}