@opennodes/registry 0.1.40 → 0.1.42

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.
package/src/search.js CHANGED
@@ -1,5 +1,15 @@
1
1
  // Offering search + transparent ranking (ONP-3 §5–6).
2
- import { inJurisdiction, localSizes, pullsOf, specialtyOf, isEmbedder } from '@opennodes/core';
2
+ import {
3
+ residencyWithin, residencyCodes, servingLocations, basisRank,
4
+ inJurisdiction, localSizes, pullsOf, specialtyOf, isEmbedder,
5
+ } from '@opennodes/core';
6
+
7
+ /** BCP 47 prefix match (ONP-3 §5): `fr` matches `fr` and `fr-CA`; `fr-CA` matches only itself. */
8
+ export const langMatches = (tag, wanted) => {
9
+ const t = String(tag).toLowerCase();
10
+ const w = String(wanted).toLowerCase();
11
+ return t === w || t.startsWith(`${w}-`);
12
+ };
3
13
 
4
14
  export const RANK_COMPONENTS = { price: 0.35, tier: 0.35, probe_success: 0.30 };
5
15
  const TIER_SCORE = { unverified: 0, community: 0.4, verified: 0.8, attested: 1.0 };
@@ -89,15 +99,20 @@ async function buildOfferings(store) {
89
99
  binding: offering.binding,
90
100
  pricing: offering.pricing,
91
101
  data_policy: offering.data_policy ?? null,
102
+ node_regions: card.node?.regions ?? [],
92
103
  // Where the operator is (ONP-2 node.operator.country, node.regions).
93
104
  // Registered nodes declare it in their signed card; imports get it from the importer's list of
94
- // known providers, labeled inferred.
105
+ // known providers, labeled inferred. `location` is the registry's own server-location check.
95
106
  jurisdiction: {
96
107
  country: card.node?.operator?.country ?? null,
97
108
  regions: card.node?.regions ?? [],
98
109
  basis: card.node?.operator?.country ? (node.source === 'import' ? 'inferred' : 'declared') : null,
99
110
  location,
100
111
  },
112
+ // Where requests are served: live sites with their evidence basis (ONP-2 §3a), and the
113
+ // codes a residency check must cover (pins + sites, else node regions).
114
+ locations: servingLocations(offering, card),
115
+ residency: residencyCodes(offering, card),
101
116
  // Allocated hardware for THIS offering (offering-level override wins over the
102
117
  // node-level description) — same artifact on different vendors runs on different
103
118
  // silicon, and clients deserve to see which. Always basis-labeled, never measured.
@@ -139,6 +154,20 @@ export async function searchOfferingsPaged(store, query) {
139
154
  if (q('max_input_price')) items = items.filter((o) => (o.pricing.input_per_mtok ?? Infinity) <= Number(q('max_input_price')));
140
155
  if (q('scheme')) items = items.filter((o) => o.pricing.schemes.includes(q('scheme')));
141
156
  if (q('jurisdiction')) items = items.filter((o) => inJurisdiction(o, q('jurisdiction')));
157
+ if (q('region')) {
158
+ // Residency: every pinned region and live serving site (else the node's regions) inside.
159
+ items = items.filter((o) => residencyWithin(o.residency, q('region')));
160
+ }
161
+ if (q('location_basis')) {
162
+ // Evidence: the offering has serving sites and every one is at least this well supported.
163
+ const min = basisRank(q('location_basis'));
164
+ items = items.filter((o) => o.locations.length && o.locations.every((l) => basisRank(l.basis) >= min));
165
+ }
166
+ if (q('exclude_lineage')) {
167
+ // Origin policy on declared lineage; offerings that declare none are kept (unknown).
168
+ const banned = q('exclude_lineage').toUpperCase().split(',');
169
+ items = items.filter((o) => !(o.model.lineage_origins ?? []).some((c) => banned.includes(c)));
170
+ }
142
171
  if (q('tier')) {
143
172
  const order = ['unverified', 'community', 'verified', 'attested'];
144
173
  const min = order.indexOf(q('tier'));
@@ -148,7 +177,7 @@ export async function searchOfferingsPaged(store, query) {
148
177
  const [lang, minGrade = 'basic'] = q('lang').split(':');
149
178
  const grades = ['basic', 'strong', 'native'];
150
179
  items = items.filter((o) => (o.serving?.languages ?? []).some(
151
- (l) => l.lang === lang && grades.indexOf(l.grade) >= grades.indexOf(minGrade)));
180
+ (l) => langMatches(l.lang, lang) && grades.indexOf(l.grade) >= grades.indexOf(minGrade)));
152
181
  }
153
182
  if (q('q')) {
154
183
  const needle = q('q').toLowerCase();
package/src/server.js CHANGED
@@ -24,8 +24,17 @@ import { checkNodeLocation } from './location.js';
24
24
  import {
25
25
  importModelsDev, importHuggingFace, importOpenRouter,
26
26
  importOllamaLibrary, parseOllamaLibrary,
27
- HF_ROUTER_URL, HF_HUB_URL, OPENROUTER_URL, OLLAMA_LIBRARY_URL,
27
+ importOpenRouterProviders, fetchOpenRouterEndpoints, importLocationSeed,
28
+ HF_ROUTER_URL, HF_HUB_URL, OPENROUTER_URL, OPENROUTER_PROVIDERS_URL, OLLAMA_LIBRARY_URL,
28
29
  } from './importers.js';
30
+ import { locationRoutes, loadLocationSeeds } from './locations.js';
31
+
32
+ /** Default basemap. OSM's tile policy asks for attribution and light use; busy registries set their own. */
33
+ export const OSM_TILES = {
34
+ tiles: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
35
+ attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
36
+ max_zoom: 19,
37
+ };
29
38
 
30
39
  export async function startRegistry({
31
40
  port = 0, host = '127.0.0.1', dbPath = ':memory:',
@@ -41,9 +50,16 @@ export async function startRegistry({
41
50
  admitCooldownMs = 0, // minimum gap between Stage B runs per node (0 = none; set in production)
42
51
  trustProxy = false, // read the client address from X-Forwarded-For (behind Caddy / a CDN)
43
52
  location = null, // { selfSite, agents, intervalMs, fetchImpl, resolve, rtt } to check server locations
53
+ locationSeeds = false, // import the bundled curated location seeds (src/data/locations-*.json) at start
54
+ mapTiles = OSM_TILES, // basemap for the "Where models run" map: { tiles, attribution, max_zoom }, or null for no map
44
55
  } = {}) {
45
56
  const store = watchStoreWrites(await createStore(dbPath)); // sqlite path/:memory: or postgres:// URL; writes refresh the cached catalog
46
57
  const safeFetch = makeSafeFetch({ allowPrivate: allowPrivateTargets });
58
+ const seeds = locationSeeds ? loadLocationSeeds() : [];
59
+ for (const seed of seeds) {
60
+ const result = await importLocationSeed(store, seed);
61
+ if (result.skipped.length) console.warn(`location seed ${seed.seed}: skipped ${result.skipped.join('; ')}`);
62
+ }
47
63
  const webApp = readFileSync(fileURLToPath(new URL('./web/index.html', import.meta.url)), 'utf8');
48
64
  let registryKeys;
49
65
  if (keyPath && existsSync(keyPath)) {
@@ -315,6 +331,7 @@ export async function startRegistry({
315
331
  operator: card?.node?.operator?.name ?? null,
316
332
  country: card?.node?.operator?.country ?? null,
317
333
  regions: card?.node?.regions ?? [],
334
+ locations: card?.node?.locations ?? [],
318
335
  offerings: card?.offerings?.length ?? 0,
319
336
  availability,
320
337
  });
@@ -487,6 +504,32 @@ export async function startRegistry({
487
504
  sendJson(res, 200, await importOpenRouter(store, catalog));
488
505
  }],
489
506
 
507
+ // OpenRouter per-provider importer with declared locations (admin): inline
508
+ // {providers, models, endpoints: {modelId: [...]}}, or fetch the live APIs (one call per model).
509
+ ['POST', '/v0/import/openrouter-providers', async (req, res) => {
510
+ if (!adminOk(req, res)) return;
511
+ const body = await readJson(req, 100_000_000);
512
+ const json = async (url) => (await safeFetch(url, {}, 60_000)).json();
513
+ const providers = body.providers ?? (await json(OPENROUTER_PROVIDERS_URL)).data;
514
+ const models = body.models ?? (await json(OPENROUTER_URL)).data;
515
+ const endpoints = body.endpoints ? new Map(Object.entries(body.endpoints)) : await fetchOpenRouterEndpoints(json, models);
516
+ sendJson(res, 200, await importOpenRouterProviders(store, providers, models, endpoints));
517
+ }],
518
+
519
+ // Curated location seed (admin): inline {seed}, or re-import the bundled seeds.
520
+ ['POST', '/v0/import/locations', async (req, res) => {
521
+ if (!adminOk(req, res)) return;
522
+ const body = await readJson(req, 10_000_000);
523
+ const list = body.seed ? [body.seed] : loadLocationSeeds();
524
+ const results = {};
525
+ for (const seed of list) {
526
+ results[seed.seed] = await importLocationSeed(store, seed);
527
+ const i = seeds.findIndex((s) => s.seed === seed.seed); // /v0/locations reads site-only entries from here
528
+ if (i < 0) seeds.push(seed); else seeds[i] = seed;
529
+ }
530
+ sendJson(res, 200, results);
531
+ }],
532
+
490
533
  ['GET', '/v0/health', (req, res) => {
491
534
  sendJson(res, 200, {
492
535
  service: 'opennodes-registry',
@@ -497,6 +540,8 @@ export async function startRegistry({
497
540
  mcp: '/mcp',
498
541
  webmcp: true, // the web app at / registers in-page tools via navigator.modelContext where supported
499
542
  export: '/v0/export',
543
+ locations: '/v0/locations',
544
+ map: mapTiles,
500
545
  signing_key: { ...registryKeys.publicJwk, kid: 'registry-1' },
501
546
  stage_c: Boolean(stageC),
502
547
  });
@@ -508,8 +553,9 @@ export async function startRegistry({
508
553
  res.end(webApp);
509
554
  }],
510
555
 
511
- ...mcpRoutes(store),
556
+ ...mcpRoutes(store, seeds),
512
557
  ...exportRoutes(store, registryKeys),
558
+ ...locationRoutes(store, seeds),
513
559
  ], { cors: true }); // public read API: third-party web clients may call it directly
514
560
 
515
561
  // ---- server-location checks (location.js) ----
@@ -118,6 +118,16 @@
118
118
  .chip.inst { color: var(--accent); border-color: var(--accent); }
119
119
  .chip.imp { background: var(--panel-2); font-weight: 400; }
120
120
  .chip.loc { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }
121
+ .chip.b-documented { color: var(--accent); border-color: var(--accent); }
122
+ .chip.b-measured, .chip.b-attested { color: var(--good); border-color: var(--good); }
123
+ .chip.s-planned { color: var(--warn); border-color: var(--warn); }
124
+ .wmodels { display: flex; flex-wrap: wrap; gap: 0.25rem 0.6rem; font-size: 0.8rem; }
125
+ .wmodels .lin { font-family: "IBM Plex Mono", monospace; font-size: 0.6rem; color: var(--warn); }
126
+ #w-map { height: 440px; margin-bottom: 0.4rem; overflow: hidden; }
127
+ #w-map .leaflet-popup-content { font-family: "Archivo", "Helvetica Neue", Arial, sans-serif; font-size: 0.8rem; line-height: 1.4; margin: 0.6rem 0.8rem; }
128
+ #w-map .leaflet-popup-content .site + .site { border-top: 1px solid #D6DEE3; margin-top: 0.45rem; padding-top: 0.45rem; }
129
+ .wlegend { display: flex; flex-wrap: wrap; gap: 0.3rem 1rem; font-size: 0.74rem; color: var(--muted); margin: 0 0 0.8rem; }
130
+ .wlegend .dot { display: inline-block; width: 0.7rem; height: 0.7rem; border-radius: 50%; border: 2px solid currentColor; vertical-align: -0.1rem; margin-right: 0.3rem; }
121
131
  .micro { font-family: "IBM Plex Mono", monospace; font-size: 0.58rem; font-weight: 600; letter-spacing: 0.04em; }
122
132
  .m-measured { color: var(--good); } .m-claimed { color: var(--faint); font-weight: 400; } .m-warn { color: var(--warn); }
123
133
  .prov { font-family: "IBM Plex Mono", monospace; font-size: 0.64rem; color: var(--faint); }
@@ -244,6 +254,7 @@
244
254
  <a class="tab" data-view="models" href="#/">Models</a>
245
255
  <a class="tab" data-view="rankings" href="#/rankings">Rankings</a>
246
256
  <a class="tab" data-view="nodes" href="#/nodes">Nodes</a>
257
+ <a class="tab" data-view="where" href="#/where">Where models run</a>
247
258
  <a class="tab" data-view="feed" href="#/new">New</a>
248
259
  <a class="tab" data-view="build" href="#/build">Build</a>
249
260
  <a class="tab" data-view="chat" href="#/chat">Chat</a>
@@ -381,6 +392,30 @@
381
392
  <div class="panel tablewrap" id="n-table"></div>
382
393
  </div>
383
394
 
395
+ <!-- ================= WHERE MODELS RUN ================= -->
396
+ <div id="view-where" hidden>
397
+ <div style="display:flex; align-items:baseline; gap:0.9rem; flex-wrap:wrap"><h1>Where models run</h1><span class="counts" id="w-counts"></span></div>
398
+ <p class="sub">Every known serving site by country, with the models it serves and how far each location can be trusted: <b>claimed</b> (the provider or a news report says so), <b>documented</b> (the provider's own dated page), <b>measured</b> (registry probes), <b>attested</b> (a signed card backed by an audit). Built from node cards, imported catalogs and curated seeds; <a href="https://github.com/opennodes-io/opennodes/tree/main/impl/packages/registry/src/data" target="_blank" rel="noopener">corrections welcome</a>. Also as <a id="w-json" href="/v0/locations">JSON</a>, <a id="w-csv" href="/v0/locations?format=csv">CSV</a> and <a id="w-geojson" href="/v0/locations?format=geojson">GeoJSON</a> for QGIS, ArcGIS or any web map.</p>
399
+ <div class="toolbar">
400
+ <select id="w-country"><option value="">every country</option></select>
401
+ <select id="w-basis"><option value="">any evidence</option><option value="documented">documented or better</option><option value="measured">measured or better</option><option value="attested">attested</option></select>
402
+ <select id="w-status"><option value="">live and planned</option><option value="live">live only</option><option value="planned">planned only</option></select>
403
+ <input type="text" id="w-model" placeholder="Filter by model, e.g. gpt-oss or command">
404
+ <input type="text" id="w-lineage" placeholder="exclude lineage, e.g. CN" style="max-width:12rem">
405
+ </div>
406
+ <div class="panel pad" id="w-summary" style="margin-bottom:0.8rem"></div>
407
+ <div class="panel" id="w-map" hidden></div>
408
+ <div class="wlegend" id="w-legend" hidden>
409
+ <span><span class="dot" style="color:var(--good); background:var(--good)"></span>measured or attested</span>
410
+ <span><span class="dot" style="color:var(--accent); background:var(--accent)"></span>documented</span>
411
+ <span><span class="dot" style="color:var(--faint); background:var(--faint)"></span>claimed</span>
412
+ <span><span class="dot" style="color:var(--muted)"></span>hollow: approximate point, only the region or country is known</span>
413
+ <span><span class="dot" style="color:var(--warn); border-style:dashed"></span>dashed: planned</span>
414
+ <span>Size: models served. Several sites in one city share a marker.</span>
415
+ </div>
416
+ <div class="panel tablewrap" id="w-table"></div>
417
+ </div>
418
+
384
419
  <!-- ================= NEW (feed) ================= -->
385
420
  <div id="view-feed" hidden>
386
421
  <h1>New</h1>
@@ -595,15 +630,19 @@ const priceStr = (p, nodeId = '') => {
595
630
  const i = p.input_per_mtok ?? 0, o = p.output_per_mtok ?? 0;
596
631
  return (i === 0 && o === 0) ? 'free' : `$${fmt(i)} / $${fmt(o)} per MTok`;
597
632
  };
633
+ const basisChip = (b) => `<span class="chip b-${esc(b)}">${esc(String(b).toUpperCase())}</span>`;
634
+ /** "CA-QC Montréal (documented)" for each live serving site of an offering. */
635
+ const locStr = (locs) => (locs || []).map((l) => `${esc(l.region)}${l.site ? ' ' + esc(l.site) : ''} ${basisChip(l.basis)}`).join(' · ');
598
636
 
599
637
  /* ---------- routing ---------- */
600
- const views = ['models', 'model', 'rankings', 'nodes', 'feed', 'build', 'chat', 'node', 'register', 'qualification'];
638
+ const views = ['models', 'model', 'rankings', 'nodes', 'where', 'feed', 'build', 'chat', 'node', 'register', 'qualification'];
601
639
  function route() {
602
640
  const hash = location.hash || '#/';
603
641
  let view = 'models', arg = null;
604
642
  if (hash.startsWith('#/model/')) { view = 'model'; arg = decodeURIComponent(hash.slice(8)); }
605
643
  else if (hash.startsWith('#/rankings')) view = 'rankings';
606
644
  else if (hash.startsWith('#/nodes')) view = 'nodes';
645
+ else if (hash.startsWith('#/where')) view = 'where';
607
646
  else if (hash.startsWith('#/new')) view = 'feed';
608
647
  else if (hash.startsWith('#/build')) view = 'build';
609
648
  else if (hash.startsWith('#/chat')) view = 'chat';
@@ -618,6 +657,7 @@ function route() {
618
657
  if (view === 'chat') loadChatTargets();
619
658
  if (view === 'rankings') loadRankings();
620
659
  if (view === 'nodes') loadNodes();
660
+ if (view === 'where') loadWhere();
621
661
  if (view === 'feed') loadFeed();
622
662
  if (view === 'node' && arg) loadNode(arg);
623
663
  }
@@ -1005,6 +1045,8 @@ window.toggleRow = async function (el, idx) {
1005
1045
  ${o.serving?.max_output_tokens ? `<dt>max output</dt><dd class="num">${fmtInt(o.serving.max_output_tokens)}</dd>` : ''}
1006
1046
  ${hwStr(o) ? `<dt>hardware</dt><dd>${hwStr(o)}</dd>` : ''}
1007
1047
  <dt>schemes</dt><dd>${esc((o.pricing.schemes || []).join(', '))}</dd>
1048
+ ${o.local ? '' : `<dt>served from</dt><dd>${o.locations?.length ? locStr(o.locations) : '<span style="color:var(--faint)">location not declared</span>'}</dd>`}
1049
+ ${o.model.lineage_origins ? `<dt>lineage</dt><dd>${esc(o.model.lineage_origins.join(', '))} <span class="prov" style="display:inline">· declared</span></dd>` : ''}
1008
1050
  ${o.local ? `<dt>run locally</dt><dd><code style="background:var(--panel-2); padding:0.1em 0.4em; border-radius:3px" class="mono">${esc(o.local.run)}</code>${o.local.pulls ? ` <span class="prov" style="display:inline">· ${esc(o.local.pulls)} pulls</span>` : ''}${o.local.sizes ? `<br><span class="prov" style="display:inline" title="Memory to run it at Ollama's default 4-bit quantization: weights plus runtime and a default context; an estimate">memory needed: ${o.local.sizes.map((t) => `${esc(t)} ~${memGb(t) ?? '?'} GB`).join(' · ')}</span>` : ''}</dd>` : ''}
1009
1051
  </dl>
1010
1052
  </div>
@@ -2161,7 +2203,7 @@ async function loadNodes() {
2161
2203
  <td><a href="#/node/${encodeURIComponent(n.id)}" style="font-weight:600">${esc(n.id)}</a></td>
2162
2204
  <td><span style="display:inline-flex; gap:0.3rem">${tierChip(n.tier)}${n.institutional ? '<span class="chip inst">institutional</span>' : ''}${n.source === 'import' ? '<span class="chip imp">IMPORTED</span>' : ''}</span></td>
2163
2205
  <td>${esc(n.operator ?? '—')}${n.country ? ' <span style="color:var(--muted)">(' + esc(n.country) + ')</span>' : ''}</td>
2164
- <td style="color:var(--muted)">${esc((n.regions || []).join(', ') || '—')}</td>
2206
+ <td style="color:var(--muted)">${esc([...new Set([...(n.regions || []), ...(n.locations || []).map((l) => l.region)])].join(', ') || '—')}</td>
2165
2207
  <td>${n.offerings}</td>
2166
2208
  <td>${n.availability?.ratio != null ? Math.round(n.availability.ratio * 100) + '%' : '—'}</td>
2167
2209
  <td><span class="prov">${ago(n.updated_at)}</span></td>
@@ -2169,6 +2211,123 @@ async function loadNodes() {
2169
2211
  } catch (e) { $('#n-table').innerHTML = '<p class="err">' + esc(e.message) + '</p>'; }
2170
2212
  }
2171
2213
 
2214
+ /* ---------- where models run ---------- */
2215
+ let whereCountriesLoaded = false;
2216
+ async function loadWhere() {
2217
+ const qs = new URLSearchParams();
2218
+ const set = (k, id) => { const v = $(id).value.trim(); if (v) qs.set(k, v); };
2219
+ set('country', '#w-country'); set('basis', '#w-basis'); set('status', '#w-status');
2220
+ set('model', '#w-model'); set('exclude_lineage', '#w-lineage');
2221
+ const q = qs.toString() ? '?' + qs : '';
2222
+ $('#w-json').href = '/v0/locations' + q;
2223
+ $('#w-csv').href = '/v0/locations' + (q ? q + '&' : '?') + 'format=csv';
2224
+ $('#w-geojson').href = '/v0/locations' + (q ? q + '&' : '?') + 'format=geojson';
2225
+ try {
2226
+ const r = await api('/v0/locations' + q);
2227
+ renderWhereMap(r.sites).catch((e) => { $('#w-map').hidden = true; $('#w-legend').hidden = true; console.warn('map:', e.message); });
2228
+ if (!whereCountriesLoaded && !q) {
2229
+ whereCountriesLoaded = true;
2230
+ $('#w-country').innerHTML = '<option value="">every country</option>'
2231
+ + r.countries.map((c) => `<option value="${esc(c.country)}">${esc(c.country)} · ${c.sites} sites</option>`).join('');
2232
+ }
2233
+ const s = r.summary;
2234
+ $('#w-counts').textContent = `${s.sites} sites · ${s.countries} countries`;
2235
+ $('#w-summary').innerHTML = `<div style="display:flex; flex-wrap:wrap; gap:0.4rem 1.2rem; font-size:0.84rem">`
2236
+ + r.countries.map((c) => `<span><b>${esc(c.country)}</b> ${c.providers} providers · ${c.sites} sites (${c.live_sites} live) · ${c.models} models</span>`).join('')
2237
+ + `</div><p class="prov" style="margin:0.5rem 0 0">${fmtInt(s.located_offerings)} offerings in the registry declare where they run; ${fmtInt(s.unlocated_offerings)} do not. That gap is what this page exists to close.</p>`;
2238
+ const models = (x) => x.models.length
2239
+ ? `<div class="wmodels">${x.models.slice(0, 12).map((m) => `<span>${esc(m.name)}${m.lineage_origins ? ` <span class="lin">${esc(m.lineage_origins.join('/'))}</span>` : ''}</span>`).join('')}${x.models.length > 12 ? `<span class="prov">+${x.models.length - 12} more</span>` : ''}</div>`
2240
+ : `<span style="color:var(--muted); font-size:0.8rem">${esc(x.models_note ?? '—')}</span>`;
2241
+ const provider = (x) => (x.source === 'seed'
2242
+ ? `<b>${esc(x.provider)}</b>`
2243
+ : `<a href="#/node/${encodeURIComponent(x.node_id)}" style="font-weight:600">${esc(x.provider)}</a>`)
2244
+ + (x.operator_country ? ` <span style="color:var(--muted)">(${esc(x.operator_country)})</span>` : '')
2245
+ + (x.source !== 'registration' ? ' <span class="chip imp">' + (x.source === 'seed' ? 'SEED' : 'IMPORTED') + '</span>' : '');
2246
+ $('#w-table').innerHTML = r.sites.length ? `<table class="grid"><thead><tr>
2247
+ <th>REGION</th><th>SITE</th><th>PROVIDER</th><th>STATUS</th><th>EVIDENCE</th><th>MODELS SERVED</th>
2248
+ </tr></thead><tbody>` + r.sites.map((x) => `<tr>
2249
+ <td class="mono" style="font-size:0.78rem">${esc(x.region)}</td>
2250
+ <td>${esc(x.site ?? '—')}${x.facility_operator ? `<span class="prov">run by ${esc(x.facility_operator)}</span>` : ''}${x.note ? `<span class="prov">${esc(x.note)}</span>` : ''}</td>
2251
+ <td>${provider(x)}</td>
2252
+ <td><span class="chip s-${esc(x.status)}">${esc(String(x.status).toUpperCase())}</span></td>
2253
+ <td>${basisChip(x.basis)}${x.source_url ? `<span class="prov"><a href="${esc(x.source_url)}" target="_blank" rel="noopener">source</a>${x.checked ? ' · checked ' + esc(x.checked) : ''}</span>` : ''}</td>
2254
+ <td>${models(x)}</td>
2255
+ </tr>`).join('') + '</tbody></table>' : '<p class="sub" style="padding:0.9rem 1rem; margin:0">No sites match these filters.</p>';
2256
+ } catch (e) { $('#w-table').innerHTML = '<p class="err">' + esc(e.message) + '</p>'; }
2257
+ }
2258
+ /* Map: Leaflet is fetched only when this page opens (no CDN or tile requests elsewhere in the
2259
+ app), pinned by version and integrity. Tiles come from the registry's /v0/health `map`
2260
+ setting; when it is null the map stays hidden and the table carries everything. */
2261
+ const LEAFLET = {
2262
+ css: ['https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css', 'sha512-h9FcoyWjHcOcmEVkxOfTLnmZFWIH0iZhZT1H2TbOq55xssQGEJHEaIm+PgoUaZbRvQTNTluNOEfb1ZRy6D3BOw=='],
2263
+ js: ['https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js', 'sha512-puJW3E/qXDqYp9IfhAI54BJEaWIfloJ7JWs7OeD5i6ruC9JZL1gERT1wjtwXFlh7CjE7ZJ+/vcRZRkIYIb6p4g=='],
2264
+ };
2265
+ let leafletReady = null, whereMap = null, whereLayer = null, mapConfig;
2266
+ function loadLeaflet() {
2267
+ leafletReady ??= new Promise((resolve, reject) => {
2268
+ const css = Object.assign(document.createElement('link'), { rel: 'stylesheet', href: LEAFLET.css[0], integrity: LEAFLET.css[1], crossOrigin: 'anonymous', referrerPolicy: 'no-referrer' });
2269
+ const js = Object.assign(document.createElement('script'), { src: LEAFLET.js[0], integrity: LEAFLET.js[1], crossOrigin: 'anonymous', referrerPolicy: 'no-referrer' });
2270
+ js.onload = () => resolve(window.L);
2271
+ js.onerror = () => { leafletReady = null; reject(new Error('map library did not load')); };
2272
+ document.head.append(css, js);
2273
+ });
2274
+ return leafletReady;
2275
+ }
2276
+ const BASIS_ORDER = ['claimed', 'documented', 'measured', 'attested'];
2277
+ async function renderWhereMap(sites) {
2278
+ if (mapConfig === undefined) mapConfig = (await api('/v0/health')).map ?? null;
2279
+ if (!mapConfig) return;
2280
+ const L = await loadLeaflet();
2281
+ $('#w-map').hidden = false; $('#w-legend').hidden = false;
2282
+ const css = getComputedStyle(document.documentElement);
2283
+ const color = { claimed: css.getPropertyValue('--faint').trim(), documented: css.getPropertyValue('--accent').trim(),
2284
+ measured: css.getPropertyValue('--good').trim(), attested: css.getPropertyValue('--good').trim(), planned: css.getPropertyValue('--warn').trim() };
2285
+ if (!whereMap) {
2286
+ whereMap = L.map('w-map', { worldCopyJump: true, scrollWheelZoom: false }).setView([50, -95], 3);
2287
+ L.tileLayer(mapConfig.tiles, { attribution: mapConfig.attribution, maxZoom: mapConfig.max_zoom ?? 19 }).addTo(whereMap);
2288
+ whereLayer = L.layerGroup().addTo(whereMap);
2289
+ }
2290
+ // The container was hidden until now: let layout give it a size before fitting bounds.
2291
+ await new Promise((r) => requestAnimationFrame(() => r()));
2292
+ whereMap.invalidateSize();
2293
+ whereLayer.clearLayers();
2294
+ // One marker per point: sites in the same city (Montréal: AWS, Google, Oracle) share it.
2295
+ const groups = new Map();
2296
+ for (const s of sites.filter((x) => x.geo)) {
2297
+ const key = s.geo.lat.toFixed(3) + ',' + s.geo.lon.toFixed(3);
2298
+ if (!groups.has(key)) groups.set(key, []);
2299
+ groups.get(key).push(s);
2300
+ }
2301
+ const bounds = [];
2302
+ for (const group of groups.values()) {
2303
+ const { lat, lon } = group[0].geo;
2304
+ const best = group.map((s) => s.basis).sort((a, b) => BASIS_ORDER.indexOf(b) - BASIS_ORDER.indexOf(a))[0];
2305
+ const derived = group.every((s) => s.geo.derived);
2306
+ const planned = group.every((s) => s.status === 'planned');
2307
+ const models = group.reduce((n, s) => n + s.models.length, 0);
2308
+ const c = planned ? color.planned : (color[best] || color.claimed);
2309
+ const marker = L.circleMarker([lat, lon], {
2310
+ radius: Math.min(22, 6 + Math.sqrt(models) * 2.2), color: c, weight: 2,
2311
+ fillColor: c, fillOpacity: derived ? 0 : 0.55, dashArray: planned ? '4 3' : null,
2312
+ });
2313
+ marker.bindPopup(group.map((s) => `<div class="site">
2314
+ <b>${esc(s.provider)}</b>${s.operator_country ? ` (${esc(s.operator_country)})` : ''}<br>
2315
+ ${esc(s.site ?? 'site not named')} · <span class="mono">${esc(s.region)}</span> · ${esc(s.status)} · ${basisChip(s.basis)}
2316
+ ${s.geo.derived ? `<br><i style="color:#5C6E7E">Approximate: only the ${esc(s.geo.precision)} is known</i>` : ''}
2317
+ <br>${s.models.length ? esc(s.models.slice(0, 8).map((m) => m.name).join(', ')) + (s.models.length > 8 ? ` +${s.models.length - 8} more` : '') : `<span style="color:#5C6E7E">${esc(s.models_note ?? 'no models listed')}</span>`}
2318
+ ${s.source === 'seed' ? '' : `<br><a href="#/node/${encodeURIComponent(s.node_id)}">node card</a>`}${s.source_url ? ` · <a href="${esc(s.source_url)}" target="_blank" rel="noopener">source</a>` : ''}
2319
+ </div>`).join(''), { maxWidth: 320, maxHeight: 320 });
2320
+ marker.bindTooltip(`${group.length} site${group.length > 1 ? 's' : ''} · ${models} models`);
2321
+ marker.addTo(whereLayer);
2322
+ bounds.push([lat, lon]);
2323
+ }
2324
+ if (bounds.length) whereMap.fitBounds(bounds, { padding: [30, 30], maxZoom: 6 });
2325
+ }
2326
+
2327
+ for (const id of ['w-country', 'w-basis', 'w-status']) $('#' + id).addEventListener('change', loadWhere);
2328
+ let whereDebounce;
2329
+ for (const id of ['w-model', 'w-lineage']) $('#' + id).addEventListener('input', () => { clearTimeout(whereDebounce); whereDebounce = setTimeout(loadWhere, 250); });
2330
+
2172
2331
  /* ---------- feed ---------- */
2173
2332
  async function loadFeed() {
2174
2333
  try {