Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

Merge upstream/main into pr/mapillary-layer

Said Turkseverecb16b2fe2c3
diff --cc CONTRIBUTING.md
index c65efac10,cdfbb6547..63f83e4c2
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@@ -70,6 -70,39 +70,39 @@@ gate for the feature you changed
> and a browser. Include the applicable local run in your PR's validation
> evidence.
+ ## Share-link layer tokens
+
+ Every shareable layer owns an immutable token in `LAYER_STATE_REGISTRY` and
+ `src/data/layerStateTokenReservations.json`. Never change or reuse an existing
+ token: published v2 links are authored state, and the reservation remains even
+ if its layer is later removed.
+
+ New layers first use the remaining unreserved single-character digits (`0`
+ through `9`), then the two-character base-36 namespace (`00` through `zz`). On the
-current published ledger, `1` and `2` are already owned, so the next choices
-are `0`, `3` through `9`, then `00`. After rebasing onto the latest `main`, run
++current published ledger, `0`, `1` and `2` are already owned, so the next
++choices are `3` through `9`, then `00`. After rebasing onto the latest `main`, run
+ `npm run layer-token:next -- <layer-id>`, add that result to both the permanent
+ JSON reservation ledger and registry entry, and keep the exact registered-layer
+ count assertion up to date. The token is assigned against the merge-time base, not
+ claimed when a PR opens, so another merged layer may require rerunning the
+ command after a rebase. Never repurpose a published or retired token.
+ Run `npm run layer-token:check -- --base-ref origin/main` after the rebase;
+ this checks that every published assignment remains reserved and that new
+ assignments consume free digits before the two-character tokens, in order.
+ Pull-request CI runs the same check against `main`.
+
+ The helper reads the local ledger; it does not run during a rebase or edit files.
+ If another PR publishes your provisional token first, keep every published
+ registry entry and ledger reservation from the refreshed `main`. Temporarily
+ remove only your still-unpublished layer's registry entry and ledger row so the
+ local registry is valid again, then rerun `npm run layer-token:next -- <layer-id>`.
+ For example, if PR A publishes `0` while PR B still provisionally uses `0`,
+ PR B removes only its own provisional entry, reruns the helper, and receives
+ `3`. Put `3` on PR B's registry entry and ledger row, update its pinned count
+ and token tests, then rerun `npm run layer-token:check -- --base-ref origin/main`.
+ An invalid duplicate ledger can fail during module import before the helper
+ prints anything; never fix that by renaming or deleting PR A's published token.
+
## Good first contributions
The highest-leverage places to jump in:
diff --cc README.md
index 3a5971366,88690d52f..da5f59c22
--- a/README.md
+++ b/README.md
@@@ -326,22 -325,6 +326,22 @@@ _The Space Missions layer replaying a F
---
+## 📷 Street Level
+
+> One panel for street-level imagery from any provider. This build registers **Mapillary**, which needs a free **Mapillary client token** in POWER UP; Google Street View, KartaView and Panoramax are the next providers.
+
+Setup for Mapillary:
+
+1. **Mapillary client token (free).** Sign in at [mapillary.com/dashboard/developers](https://www.mapillary.com/dashboard/developers), choose **Register application**, give it any name and website, tick **Read** access, and copy the **Client Token** (it starts with `MLY|`). Paste it into **POWER UP → Mapillary**, or set `MAPILLARY_CLIENT_TOKEN` in `.env` and restart `npm run dev`.
+
+Without the token the STREET LEVEL panel reads **KEY REQUIRED**, the Mapillary chip turns amber and the controls stay greyed out.
+
+Turn on **Street Level** under DATA LAYERS → Cameras, or open the STREET LEVEL strip in the right rail and press the **ON/OFF** pill in its header. The **PROVIDERS** row has one chip per registered provider: lighting a chip turns its imagery on (and the layer with it), and darkening the last lit chip turns the layer off. The **IMAGERY** filter (ALL / 360° / FLAT) and the **SINCE** slider (any date on the left, the last month on the right, with the cut-off date spelled out) apply to every provider at once. Mapillary's coverage draws as ground-hugging lines (recent captures bright green, older ones dim, 360° panoramas magenta); click a line for its image cones and a cone to open the photo. The photo opens at the top of the panel, so it is on screen without scrolling. The bar above it has **EXPAND** (most of the screen), **FIT** (the whole photo, with dark bars where its shape differs from the frame) / **FILL** (edge to edge, cropped) and **FOLLOW** (the globe camera moves wherever the street-level view looks; available on the Google 3D map only, since flat imagery has nothing to stand among); the caption links to the image on the provider's own site. Mapillary blurs faces and licence plates before publishing imagery, and the globe credits "© Mapillary contributors, CC BY-SA 4.0" while the provider is on.
+
+The panel is also a window: drag its header to lift it out of the rail, and resize it from any edge or corner. A larger window gives the photo the room; only the settings below it scroll. Double-clicking the header, collapsing the window, or pressing SHRINK after EXPAND puts it back in the rail at its default size, so it never stays parked over the globe.
+
- Share links carry the layer's provider switches and filter (`3.m.0` turns Mapillary off, `3.p.p` keeps only panoramas, `3.s.365` shows the last year). Adding a provider means implementing the contract in `src/layers/streetLevel/registry.js` and registering it in `src/app/layers/streetLevel.js`; the chip, credit and share bit follow.
++Share links carry the layer's provider switches and filter (`0.m.0` turns Mapillary off, `0.p.p` keeps only panoramas, `0.s.365` shows the last year). Adding a provider means implementing the contract in `src/layers/streetLevel/registry.js` and registering it in `src/app/layers/streetLevel.js`; the chip, credit and share bit follow.
+
## 🎖️ Field Missions
Once the basics click, run these:
diff --cc docs/CURRENT-STATE.md
index 2080541b6,8a6cde193..8b8cf27ad
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@@ -2772,80 -2771,6 +2772,80 @@@ its criteria cannot be silently ignored
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
+Street Level lives in the right context rail next to CCTV as an ordinary
- collapsible panel (`#street-level-panel`, share token `3`, option owner
++collapsible panel (`#street-level-panel`, share token `0`, option owner
+`street-level`) and starts collapsed. It is modelled on the iD editor's photo
+overlay: one panel, a PROVIDERS chip per registered imagery provider, shared
+360°/flat and captured-since filters (stored as relative days so a link keeps
+its meaning), one viewer host, and one on-globe credit per active provider.
+Share options: `m` (Mapillary on/off), `p` (a/p/f panorama mode), `s`
+(since, days). Only Mapillary is registered in this build. Without
+`MAPILLARY_CLIENT_TOKEN` the header reads KEY REQUIRED, the Mapillary chip
+turns amber and the controls stay disabled; with it, coverage draws as
+ground-clamped sequence lines (z0–5 overview points from orbit, z11–14
+sequences below 60 km) and the proxy strips the unused `image` point layer
+from z14 tiles in transit (12 MB → ~80 KB).
+
+On Google 3D (`photoreal`) at street zoom the layer switches its surface mode
+from `draped` to `terrain` (`getUIState().surface`; in below 1,400 m above the
+ground, out above 1,800 m, so the mode does not flap). Draped ground polylines
+and clamped billboards land on the top of the photoreal mesh, so on a street
+under trees or an overpass the coverage appears to float at roof height. In
+terrain mode `src/layers/streetLevel/groundCast.js` places lines, cones and the
+position marker on the bare earth from the terrain service
+(`/api/terrain/heights`) plus 2 m, and the mesh hides whatever is behind
+buildings and trees. Heights are sampled on the ground-floor grid (0.001°,
+~111 m), shared with other layers' cache, and interpolated bilinearly; a z14
+tile needs at most a few hundred lookups, sent once per tile and aborted when
+the tile is dropped. A tile is drawn draped first and swapped for its cast
+lines when the heights arrive; a geoid fallback (terrain proxy down) counts as
+unknown and leaves the lines draped. Cones and the marker keep drawing over
+buildings so they stay clickable. Framing or following a photo also checks the
+sampled mesh height against the bare earth: `sampleHeight` can return values
+kilometres underground before the tiles under the photo have loaded, and such
+a sample is ignored.
+
+The panel has no separate ON/OFF or nearest-photo buttons. The header pill is
+the layer switch, and a provider chip is lit only while the layer is on: with
+one provider it is the layer switch too, and with several, darkening the last
+lit chip turns the layer off while leaving that provider switched on. The
+viewer sits first, under the header, with its tools (EXPAND, FIT/FILL, FOLLOW,
+close) in a bar above the image so the provider's own overlays stay clear;
+the settings follow. FOLLOW is offered only while the map stack is Google 3D
+(`photoreal`): the layer takes the application map stack controller through
+`attachMapStackController`, subscribes to stack switches, disables the button
+with a MAP SOURCE hint on other stacks, and stops following when the stack
+leaves Google 3D. SINCE is a stepped range input (any date, 10, 5, 3, 2 and
+1 years, 6, 3 and 1 months) whose readout names the cut-off date. The panel is
+portable (`street-level-panel` spec in `PanelPositionControls`, minimum
+320 × 280, `dockOnCollapse`): in a resized window the viewer takes the spare
+height and only `.sl-settings` scrolls, and a user's collapse, a header
+double-click or SHRINK after EXPAND docks it at its default size (cockpit
+entry, restores and the Cyber accordion never dock a floating window). At
+phone width (≤720 px) the rail is the band between mid-screen and the credit
+line, so the viewer's height is derived from that band instead of 16:10 and
+the whole photo and caption fit without scrolling.
+
+Street-level providers implement the contract documented in
+`src/layers/streetLevel/registry.js`: a definition (`id`, `name`, `label`,
+`requiresKeyId`, `pickPrefix`, `colors`, `credit`, `capabilities`, `legend`,
+`externalUrl`, `create`) whose `create(context)` returns an instance with
+`status`, `init`/`activate`/`deactivate`/`destroy`, `refreshCoverage`,
+`setFilter`, optional `setSurface`, `coverageStats`, `handlePick`, optional
+sequence selection,
+`nearestImage`, and a viewer adapter (`mount`/`open`/`close`/`unmount`/
+`resize`/`onPose`) that emits a provider-neutral pose. The core routes clicks
+by pick prefix, swaps viewer adapters in the one host, adds and removes each
+provider's Cesium credit, and fans the filter out to every provider. The
+context also carries `getSurface()` and `groundCaster` (bare-earth heights),
+so a provider can draw on the ground in terrain mode. Adding a
+provider: implement the definition, register it in
+`src/app/layers/streetLevel.js`, add its boolean option to the `street-level`
+group in `src/data/layerState.js` and its modules to
+`scripts/package-boundaries.json`; the chip, credit and legend follow. Once a
+keyless provider registers, `requiresKeyId` on the layer becomes null and the
+key gate moves to the chips, by design.
+
Directions is a keyless front end to the routing the voice agent already
uses. Its row chips are the whole interface: DRIVE / WALK / BIKE pick the
profile; SET A and SET B arm the next globe click (Escape or a second press
@@@ -3573,11 -3498,33 +3573,33 @@@ silently demoting every later lookup fo
with compact fields for enabled layers, allowlisted layer options, panel state,
and the active preset's allowlisted shader controls. An absent layer field uses
deterministic defaults; an explicit empty field means no enabled layers.
- - The registry seals only after all 16 production layers register, and every
- layer has an explicit serialization disposition. Unknown enabled-layer tokens
- reject the layer payload; unknown option tokens are ignored. Restoration
+ - The registry seals only after every production layer registers, and every
+ layer has an explicit serialization disposition. Unknown, empty, or repeated
+ enabled-layer tokens reject the whole layer payload (`l=` alone is the valid
+ explicit-empty form); unknown option tokens are ignored. Restoration
settles independently per layer so one failed or unavailable source cannot
block its siblings.
+ - Layer tokens are permanent public compatibility identifiers. The reservation
+ JSON ledger at `src/data/layerStateTokenReservations.json` pins all existing
- one-character assignments (all letters plus `1` and
++ one-character assignments (all letters plus `0`, `1` and
+ `2` on current `main`) even if a layer is later removed. New layers allocate
- the remaining unreserved single-character digits first (`0`, then `3`
- through `9` on current `main`), then the next unreserved two-character
++ the remaining unreserved single-character digits first (`3` through `9` on
++ current `main`), then the next unreserved two-character
+ base-36 token (`00` through `zz`) after rebasing onto the merge-time `main`;
+ the dot-delimited v2 codec accepts both widths without changing existing
+ links or the schema version. The contributor
+ check reads the complete published JSON ledger from `origin/main`, including
+ retired reservations, so later assignments cannot silently replace published
+ ones. The pre-ledger base is accepted only at its known source blob; unknown
+ historical shapes fail closed.
+ Pull-request CI runs this check against `origin/main`.
+ - `scripts/qa-layer-token-twochar.mjs` simulates exhaustion of the earlier
+ digit slots and injects a no-network `00` layer only into isolated dev-browser
+ responses. It proves encoding, a cold-recipient reload, restoration, explicit
+ OFF, and legacy-token compatibility. This is synthetic
+ end-to-end evidence, not production allocation: `00` remains unreserved until
+ the first eligible real layer receives it after the free digits through the
+ normal allocation process and passes its own application share/reload check.
- Stable visible options are limited to aircraft 3D mode, selected civilian and
military flight IDs, Satellite catalog and selection, CCTV coverage/projection/
auto-hop, and Radio filter/volume. Playback and tuning, live-data health,
diff --cc package.json
index d742c777e,e48881c6d..3b53e0324
--- a/package.json
+++ b/package.json
@@@ -39,14 -35,18 +39,16 @@@
"doctor": "node scripts/setup-doctor.mjs",
"format": "node scripts/format.mjs --write",
"format:check": "node scripts/format.mjs --check",
- "layer-token:next": "node scripts/next-layer-state-token.mjs",
+ "layer-token:check": "node scripts/check-layer-state-tokens.mjs",
- "dev": "vite",
- "dev:secure": "./scripts/dev-secure.sh",
++ "layer-token:next": "node scripts/next-layer-state-token.mjs",
"opensky:import": "./scripts/opensky-import-client.sh",
- "build": "vite build",
"preview": "vite preview",
- "test": "node scripts/run-unit-tests.mjs",
- "test:track": "node scripts/track-regression.mjs",
"qa:map-source-tray": "node scripts/qa-map-source-tray.mjs",
- "check:boundaries": "node scripts/check-import-directions.mjs && node scripts/check-package-boundaries.mjs",
- "qa:transit": "node scripts/qa-transit.mjs"
+ "qa:panel-resize": "node scripts/qa-panel-resize.mjs",
+ "qa:street-level": "node scripts/qa-street-level.mjs",
+ "qa:transit": "node scripts/qa-transit.mjs",
+ "test": "node scripts/run-unit-tests.mjs",
+ "test:track": "node scripts/track-regression.mjs"
},
"dependencies": {
"@jtarrio/signals": "^0.10.0",
diff --cc src/data/layerState.js
index 7a2acf57f,ab848c998..db822f384
--- a/src/data/layerState.js
+++ b/src/data/layerState.js
@@@ -548,12 -632,6 +643,12 @@@ export const LAYER_STATE_REGISTRY = Obj
disposition: 'enabled+options',
optionOwner: 'satellites',
}),
+ Object.freeze({
+ id: 'street-level',
- token: '3',
++ token: '0',
+ disposition: 'enabled+options',
+ optionOwner: 'street-level',
+ }),
Object.freeze({
id: 'telegeography-submarine-cables',
token: 'u',
diff --cc src/data/layerState.test.mjs
index dd1d6999d,1b504a439..786270bcc
--- a/src/data/layerState.test.mjs
+++ b/src/data/layerState.test.mjs
@@@ -194,10 -199,148 +199,148 @@@ function encode(state)
test('production registry is exact, canonical, and rejects incomplete contracts', async () => {
assert.equal(validateLayerStateRegistry(), true);
- assert.equal(REGISTERED_LAYER_IDS.length, 28);
- assert.equal(new Set(REGISTERED_LAYER_IDS).size, 28);
+ assert.equal(REGISTERED_LAYER_IDS.length, 29);
+ assert.equal(new Set(REGISTERED_LAYER_IDS).size, 29);
assert.ok(REGISTERED_LAYER_IDS.includes('transit'));
assert.deepEqual(REGISTERED_LAYER_IDS, [...REGISTERED_LAYER_IDS].sort());
+ assert.deepEqual(LEGACY_LAYER_STATE_TOKENS, {
+ 'ais-live-vessels': 'a',
+ 'alpr-cameras': 'p',
+ 'bhote-koshi-2026': 'h',
+ 'bhote-koshi-locator': 'z',
+ bikeshare: 'b',
+ cctv: 'c',
+ directions: 'n',
+ earthquakes: 'e',
+ 'fire-perimeters': '2',
+ flights: 'f',
+ 'local-dams': 'q',
+ 'local-datacenters': 'd',
+ 'local-firms': 'w',
+ military: 'm',
+ 'military-awareness': 'g',
+ 'military-installations': 'i',
+ radio: 'r',
+ 'recent-imagery': '1',
+ 'rocket-launches': 'x',
+ satellites: 's',
+ 'telegeography-submarine-cables': 'u',
+ traffic: 't',
+ transit: 'j',
+ 'weather-cyclones': 'y',
+ 'weather-lightning': 'l',
+ 'weather-radar': 'v',
+ 'weather-satellite': 'o',
+ wind: 'k',
+ });
+ for (const { id, token } of LAYER_STATE_REGISTRY) {
+ assert.equal(LAYER_STATE_TOKEN_RESERVATIONS[id], token);
+ }
+ for (const [id, token] of Object.entries(LEGACY_LAYER_STATE_TOKENS)) {
+ assert.equal(LAYER_STATE_TOKEN_RESERVATIONS[id], token);
+ }
- assert.equal(nextLayerStateToken(), '0');
++ assert.equal(nextLayerStateToken(), '3');
+ assert.equal(
- nextLayerStateToken({ ...LAYER_STATE_TOKEN_RESERVATIONS, alpha: '0', bravo: '3' }),
- '4',
++ nextLayerStateToken({ ...LAYER_STATE_TOKEN_RESERVATIONS, alpha: '3', bravo: '4' }),
++ '5',
+ );
+ const digitsExhausted = {
+ ...LAYER_STATE_TOKEN_RESERVATIONS,
+ ...Object.fromEntries(
- [...'03456789'].map((digit) => [`prior-${digit}`, digit]),
++ [...'3456789'].map((digit) => [`prior-${digit}`, digit]),
+ ),
+ };
+ assert.equal(nextLayerStateToken(digitsExhausted), '00');
+ assert.equal(
+ nextLayerStateToken({ ...digitsExhausted, retired: '00', used: '01' }),
+ '02',
+ );
+ assert.equal(
+ nextLayerStateToken({
+ ...digitsExhausted,
+ ...Object.fromEntries(
+ [...LAYER_STATE_TOKEN_ALPHABET].map((second) => [
+ `pair-0${second}`,
+ `0${second}`,
+ ]),
+ ),
+ }),
+ '10',
+ );
+ assert.throws(
+ () =>
+ nextLayerStateToken(
+ Object.fromEntries(
+ [
+ ...'0123456789',
+ ...[...LAYER_STATE_TOKEN_ALPHABET].flatMap((first) =>
+ [...LAYER_STATE_TOKEN_ALPHABET].map((second) => `${first}${second}`),
+ ),
+ ].map((token, index) => [`occupied-${index}`, token]),
+ ),
+ ),
+ /namespace exhausted/,
+ );
+ assert.equal(
+ validateLayerStateRegistry(
+ [{ id: 'future-layer', token: '0', disposition: 'enabled-only' }],
+ { 'future-layer': '0' },
+ ),
+ true,
+ );
+ assert.equal(
+ validateLayerStateRegistry(
+ [{ id: 'future-layer', token: '01', disposition: 'enabled-only' }],
+ { retired: '00', 'future-layer': '01' },
+ ),
+ true,
+ );
+ assert.equal(
+ validateLayerStateAllocations(
+ LAYER_STATE_TOKEN_RESERVATIONS,
- { ...LAYER_STATE_TOKEN_RESERVATIONS, future: '0', next: '3' },
++ { ...LAYER_STATE_TOKEN_RESERVATIONS, future: '3', next: '4' },
+ ),
+ true,
+ );
+ assert.throws(
+ () => validateLayerStateAllocations(LAYER_STATE_TOKEN_RESERVATIONS, {
+ ...LAYER_STATE_TOKEN_RESERVATIONS,
+ future: '00',
+ }),
- /next free token 0/,
++ /next free token 3/,
+ );
+ const beforeLastDigit = { ...digitsExhausted };
+ delete beforeLastDigit['prior-9'];
+ assert.equal(
+ validateLayerStateAllocations(
+ beforeLastDigit,
+ { ...beforeLastDigit, futurePair: '00', futureDigit: '9' },
+ ),
+ true,
+ );
+ assert.equal(
+ validateLayerStateAllocations(
+ digitsExhausted,
+ { ...digitsExhausted, pairB: '01', pairA: '00' },
+ ),
+ true,
+ );
+ assert.throws(
+ () =>
+ validateLayerStateAllocations(
- { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '0' },
- { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '0', competing: '0' },
++ { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '3' },
++ { ...LAYER_STATE_TOKEN_RESERVATIONS, merged: '3', competing: '3' },
+ ),
- /next free token 3/,
++ /next free token 4/,
+ );
+ assert.throws(
+ () => validateLayerStateAllocations({ future: '00' }, { future: '01' }),
+ /changed or removed/,
+ );
+ assert.throws(
+ () => validateLayerStateAllocations({ retired: '00' }, { newcomer: '00' }),
+ /changed or removed/,
+ );
assert.throws(
() =>
validateLayerStateRegistry([
diff --cc src/data/layerStateTokenLedger.test.mjs
index 000000000,7b0a9263c..95e827416
mode 000000,100644..100644
--- a/src/data/layerStateTokenLedger.test.mjs
+++ b/src/data/layerStateTokenLedger.test.mjs
@@@ -1,0 -1,419 +1,419 @@@
+ import assert from 'node:assert/strict';
+ import { execFileSync, spawnSync } from 'node:child_process';
+ import {
+ mkdtempSync,
+ mkdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+ } from 'node:fs';
+ import { tmpdir } from 'node:os';
+ import path from 'node:path';
+ import { fileURLToPath, pathToFileURL } from 'node:url';
+ import test from 'node:test';
+ import {
+ LEGACY_LAYER_STATE_TOKENS,
+ LAYER_STATE_TOKEN_ALPHABET,
+ LAYER_STATE_TOKEN_RESERVATIONS,
+ nextLayerStateToken,
+ parseLayerStateTokenReservations,
+ validateLayerStateAllocations,
+ } from './layerState.js';
+ import {
+ PRE_LEDGER_LAYER_STATE_TOKENS,
+ checkLayerStateTokens,
+ readPublishedLayerStateReservations,
+ } from '../../scripts/check-layer-state-tokens.mjs';
+
+ const LEDGER_PATH = 'src/data/layerStateTokenReservations.json';
+ const SOURCE_PATH = 'src/data/layerState.js';
+ const CODEC_SOURCE_PATH = fileURLToPath(
+ new URL('./layerState.js', import.meta.url),
+ );
+ const CHECKER_PATH = fileURLToPath(
+ new URL('../../scripts/check-layer-state-tokens.mjs', import.meta.url),
+ );
+ const NEXT_PATH = fileURLToPath(
+ new URL('../../scripts/next-layer-state-token.mjs', import.meta.url),
+ );
+ const reservationRows = JSON.parse(
+ readFileSync(
+ new URL('./layerStateTokenReservations.json', import.meta.url),
+ 'utf8',
+ ),
+ );
+
+ test('pre-ledger published ownership is independent of the candidate mapping', () => {
+ assert.notStrictEqual(
+ PRE_LEDGER_LAYER_STATE_TOKENS,
+ LEGACY_LAYER_STATE_TOKENS,
+ );
+ assert.deepEqual(PRE_LEDGER_LAYER_STATE_TOKENS, LEGACY_LAYER_STATE_TOKENS);
+ assert.equal(Object.keys(PRE_LEDGER_LAYER_STATE_TOKENS).length, 28);
+ assert.equal(PRE_LEDGER_LAYER_STATE_TOKENS['recent-imagery'], '1');
+ assert.equal(PRE_LEDGER_LAYER_STATE_TOKENS['fire-perimeters'], '2');
+ assert.throws(
+ () =>
+ validateLayerStateAllocations(PRE_LEDGER_LAYER_STATE_TOKENS, {
+ ...LAYER_STATE_TOKEN_RESERVATIONS,
+ flights: '00',
+ }),
+ /Published layer-state token changed or removed: flights/,
+ );
+ });
+
+ function git(cwd, ...args) {
+ return execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
+ }
+
+ function withPublishedBase(
+ { rows, source = 'export const changed = true;\n' },
+ check,
+ ) {
+ const cwd = mkdtempSync(path.join(tmpdir(), 'gev-layer-token-ledger-'));
+ try {
+ git(cwd, 'init', '-q');
+ mkdirSync(path.join(cwd, 'src/data'), { recursive: true });
+ writeFileSync(path.join(cwd, SOURCE_PATH), source);
+ if (rows !== undefined) {
+ writeFileSync(path.join(cwd, LEDGER_PATH), JSON.stringify(rows));
+ }
+ git(cwd, 'add', 'src/data');
+ git(
+ cwd,
+ '-c',
+ 'user.name=Layer Token Test',
+ '-c',
+ 'commit',
+ '-q',
+ '-m',
+ 'published base',
+ );
+ check(cwd);
+ } finally {
+ rmSync(cwd, { recursive: true, force: true });
+ }
+ }
+
+ function writeCodecFixture(cwd, rows, entries) {
+ const source = readFileSync(CODEC_SOURCE_PATH, 'utf8');
+ const registryEnd = ']);\n\nexport const REGISTERED_LAYER_IDS';
+ assert.equal(source.split(registryEnd).length, 2);
+ const additions = entries
+ .map(
+ ({ id, token }) =>
+ ` Object.freeze({ id: '${id}', token: '${token}', disposition: 'enabled-only' }),`,
+ )
+ .join('\n');
+ mkdirSync(path.join(cwd, 'src/data'), { recursive: true });
+ writeFileSync(path.join(cwd, 'package.json'), '{"type":"module"}');
+ writeFileSync(
+ path.join(cwd, SOURCE_PATH),
+ source.replace(registryEnd, `${additions}\n${registryEnd}`),
+ );
+ writeFileSync(path.join(cwd, LEDGER_PATH), JSON.stringify(rows));
+ return path.join(cwd, SOURCE_PATH);
+ }
+
+ test('reservation ledger is complete, pinned, and rejects duplicate or malformed rows', () => {
+ assert.deepEqual(
+ { ...parseLayerStateTokenReservations(reservationRows) },
+ { ...LAYER_STATE_TOKEN_RESERVATIONS },
+ );
- assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 28);
++ assert.equal(Object.keys(LAYER_STATE_TOKEN_RESERVATIONS).length, 29);
+ assert.deepEqual(
+ { ...LAYER_STATE_TOKEN_RESERVATIONS },
- { ...LEGACY_LAYER_STATE_TOKENS },
++ { ...LEGACY_LAYER_STATE_TOKENS, 'street-level': '0' },
+ );
+ assert.throws(
+ () => parseLayerStateTokenReservations(reservationRows.slice(1)),
+ /Missing or changed legacy/,
+ );
+ assert.throws(
+ () =>
+ parseLayerStateTokenReservations([
+ ...reservationRows,
+ reservationRows[0],
+ ]),
+ /Duplicate layer-state token reservation id/,
+ );
+ assert.throws(
+ () =>
+ parseLayerStateTokenReservations([...reservationRows, ['future', 'a']]),
+ /Duplicate layer-state token reservation/,
+ );
+ assert.equal(
- parseLayerStateTokenReservations([...reservationRows, ['future', '0']])
++ parseLayerStateTokenReservations([...reservationRows, ['future', '3']])
+ .future,
- '0',
++ '3',
+ );
+ assert.throws(
+ () =>
+ parseLayerStateTokenReservations([
+ ...reservationRows.filter(([id]) => id !== 'transit'),
+ ['future', 'j'],
+ ]),
+ /Legacy layer-state token is immutable/,
+ );
+ assert.throws(
+ () => parseLayerStateTokenReservations([...reservationRows, ['future']]),
+ /Invalid layer-state token ledger row/,
+ );
+ });
+
+ test('published retired digits and competing PRs advance the merge-time allocation', () => {
+ withPublishedBase(
- { rows: [...reservationRows, ['retired-layer', '0']] },
++ { rows: [...reservationRows, ['retired-layer', '3']] },
+ (cwd) => {
+ const published = readPublishedLayerStateReservations('HEAD', cwd);
- assert.equal(nextLayerStateToken(published), '3');
++ assert.equal(nextLayerStateToken(published), '4');
+ assert.equal(
+ validateLayerStateAllocations(published, {
+ ...published,
- newcomer: '3',
++ newcomer: '4',
+ }),
+ true,
+ );
+ assert.throws(
+ () =>
+ validateLayerStateAllocations(published, {
+ ...published,
- competing: '0',
++ competing: '3',
+ }),
- /next free token 3/,
++ /next free token 4/,
+ );
+ assert.throws(
+ () =>
+ validateLayerStateAllocations(published, {
+ ...LAYER_STATE_TOKEN_RESERVATIONS,
- newcomer: '0',
++ newcomer: '3',
+ }),
+ /changed or removed: retired-layer/,
+ );
+ },
+ );
+ });
+
-test('PR B manually replaces provisional 0 with 3 after PR A publishes 0', () => {
- withPublishedBase({ rows: [...reservationRows, ['pr-a', '0']] }, (cwd) => {
++test('PR B manually replaces provisional 3 with 4 after PR A publishes 3', () => {
++ withPublishedBase({ rows: [...reservationRows, ['pr-a', '3']] }, (cwd) => {
+ mkdirSync(path.join(cwd, 'scripts'));
+ const fixtureChecker = path.join(
+ cwd,
+ 'scripts/check-layer-state-tokens.mjs',
+ );
+ writeFileSync(fixtureChecker, readFileSync(CHECKER_PATH, 'utf8'));
+ const fixtureNext = path.join(cwd, 'scripts/next-layer-state-token.mjs');
+ writeFileSync(fixtureNext, readFileSync(NEXT_PATH, 'utf8'));
+ const runCheck = () =>
+ spawnSync(
+ process.execPath,
+ [realpathSync(fixtureChecker), '--base-ref', 'HEAD'],
+ {
+ cwd,
+ encoding: 'utf8',
+ },
+ );
+
+ writeCodecFixture(
+ cwd,
- [...reservationRows, ['pr-b', '0']],
- [{ id: 'pr-b', token: '0' }],
++ [...reservationRows, ['pr-b', '3']],
++ [{ id: 'pr-b', token: '3' }],
+ );
+ const beforeRebase = runCheck();
+ assert.equal(beforeRebase.status, 1);
+ assert.match(beforeRebase.stderr, /changed or removed: pr-a/);
+
+ writeCodecFixture(
+ cwd,
- [...reservationRows, ['pr-a', '0'], ['pr-b', '0']],
++ [...reservationRows, ['pr-a', '3'], ['pr-b', '3']],
+ [
- { id: 'pr-a', token: '0' },
- { id: 'pr-b', token: '0' },
++ { id: 'pr-a', token: '3' },
++ { id: 'pr-b', token: '3' },
+ ],
+ );
+ const staleRebase = runCheck();
+ assert.equal(staleRebase.status, 1);
+ assert.match(staleRebase.stderr, /Duplicate layer-state token reservation/);
+
+ const published = readPublishedLayerStateReservations('HEAD', cwd);
- assert.equal(nextLayerStateToken(published), '3');
- const validBaselineRows = [...reservationRows, ['pr-a', '0']];
- writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '0' }]);
++ assert.equal(nextLayerStateToken(published), '4');
++ const validBaselineRows = [...reservationRows, ['pr-a', '3']];
++ writeCodecFixture(cwd, validBaselineRows, [{ id: 'pr-a', token: '3' }]);
+ const helper = spawnSync(
+ process.execPath,
+ [realpathSync(fixtureNext), 'pr-b'],
+ { cwd, encoding: 'utf8' },
+ );
+ assert.equal(helper.status, 0, helper.stderr);
- assert.match(helper.stdout, /pr-b: 3/);
++ assert.match(helper.stdout, /pr-b: 4/);
+ assert.deepEqual(
+ JSON.parse(readFileSync(path.join(cwd, LEDGER_PATH), 'utf8')),
+ validBaselineRows,
+ 'the helper reports a token without rewriting the ledger',
+ );
+ writeCodecFixture(
+ cwd,
- [...reservationRows, ['pr-a', '0'], ['pr-b', '3']],
++ [...reservationRows, ['pr-a', '3'], ['pr-b', '4']],
+ [
- { id: 'pr-a', token: '0' },
- { id: 'pr-b', token: '3' },
++ { id: 'pr-a', token: '3' },
++ { id: 'pr-b', token: '4' },
+ ],
+ );
+ const corrected = runCheck();
+ assert.equal(corrected.status, 0, corrected.stderr);
- assert.match(corrected.stdout, /29 published, 1 new/);
++ assert.match(corrected.stdout, /30 published, 1 new/);
+ });
+ });
+
+ test('allocation batches cross the last digit and base-36 pair boundaries in order', () => {
- const digitRows = [...'03456789'].map((digit) => [`retired-${digit}`, digit]);
++ const digitRows = [...'3456789'].map((digit) => [`retired-${digit}`, digit]);
+ const allDigits = parseLayerStateTokenReservations([
+ ...reservationRows,
+ ...digitRows,
+ ]);
+ const beforeNine = { ...allDigits };
+ delete beforeNine['retired-9'];
+ assert.equal(
+ validateLayerStateAllocations(beforeNine, {
+ ...beforeNine,
+ pair: '00',
+ lastDigit: '9',
+ }),
+ true,
+ );
+ const baseBefore0a = {
+ ...allDigits,
+ ...Object.fromEntries(
+ [...'012345678'].map((second) => [`retired-0${second}`, `0${second}`]),
+ ),
+ };
+ assert.equal(nextLayerStateToken(baseBefore0a), '09');
+ assert.equal(
+ validateLayerStateAllocations(baseBefore0a, {
+ ...baseBefore0a,
+ after: '0a',
+ before: '09',
+ }),
+ true,
+ );
+ const baseBefore10 = {
+ ...allDigits,
+ ...Object.fromEntries(
+ [...LAYER_STATE_TOKEN_ALPHABET]
+ .slice(0, -1)
+ .map((second) => [`retired-0${second}`, `0${second}`]),
+ ),
+ };
+ assert.equal(nextLayerStateToken(baseBefore10), '0z');
+ assert.equal(
+ validateLayerStateAllocations(baseBefore10, {
+ ...baseBefore10,
+ after: '10',
+ before: '0z',
+ }),
+ true,
+ );
+ });
+
+ test('an isolated valid two-character fixture round-trips an l field beyond the old 64-character cap', async () => {
+ const cwd = mkdtempSync(path.join(tmpdir(), 'gev-layer-token-width-'));
+ try {
- const priorDigits = [...'03456789'].map((digit) => [
++ const priorDigits = [...'3456789'].map((digit) => [
+ `qa-prior-digit-${digit}`,
+ digit,
+ ]);
+ const fixtureLayers = ['00', '01', '02', '03'].map((token) => ({
+ id: `qa-layer-${token}`,
+ token,
+ }));
+ const fixtureRows = [
+ ...reservationRows,
+ ...priorDigits,
+ ...fixtureLayers.map(({ id, token }) => [id, token]),
+ ];
+ const fixtureModule = writeCodecFixture(cwd, fixtureRows, fixtureLayers);
+ const codec = await import(pathToFileURL(fixtureModule));
+ assert.equal(codec.validateLayerStateRegistry(), true);
+ assert.equal(
+ nextLayerStateToken(
+ parseLayerStateTokenReservations([...reservationRows, ...priorDigits]),
+ ),
+ '00',
+ );
+ assert.equal(
+ validateLayerStateAllocations(
+ LAYER_STATE_TOKEN_RESERVATIONS,
+ codec.LAYER_STATE_TOKEN_RESERVATIONS,
+ ),
+ true,
+ );
+
+ const expectedLayerIds = codec.REGISTERED_LAYER_IDS;
+ const state = codec.normalizeLayerState({
+ enabledLayerIds: expectedLayerIds,
+ });
+ const params = new URLSearchParams([['v', '2']]);
+ codec.encodeLayerStateParams(params, state);
+ assert.ok(params.get('l').length > 64, 'fixture must cross the old cap');
- assert.equal(params.get('l').length, 67);
++ assert.equal(params.get('l').length, 69);
+ const restored = codec.decodeLayerStateParams(params);
+ assert.deepEqual(restored?.enabledLayerIds, expectedLayerIds);
+ assert.deepEqual(restored?.options, state.options);
+ } finally {
+ rmSync(cwd, { recursive: true, force: true });
+ }
+ });
+
+ test('checker reads a complete future base ledger and rejects retired-token reuse', () => {
+ withPublishedBase(
+ {
+ rows: [...reservationRows, ['retired-layer', '00']],
+ source:
+ 'export const LAYER_STATE_TOKEN_RESERVATIONS = Object.freeze({ ["retired-layer"]: "00" });\n',
+ },
+ (cwd) => {
+ const published = readPublishedLayerStateReservations('HEAD', cwd);
- assert.equal(Object.keys(published).length, 29);
++ assert.equal(Object.keys(published).length, 30);
+ assert.equal(published['retired-layer'], '00');
+ assert.throws(
+ () =>
+ validateLayerStateAllocations(published, {
+ ...LAYER_STATE_TOKEN_RESERVATIONS,
+ newcomer: '00',
+ }),
+ /changed or removed/,
+ );
+ assert.throws(
+ () => checkLayerStateTokens('HEAD', cwd),
+ /changed or removed/,
+ );
+ const cli = spawnSync(
+ process.execPath,
+ [CHECKER_PATH, '--base-ref', 'HEAD'],
+ {
+ cwd,
+ encoding: 'utf8',
+ },
+ );
+ assert.equal(cli.status, 1);
+ assert.match(cli.stderr, /changed or removed/);
+ },
+ );
+ });
+
+ test('checker fails closed on unknown or malformed published ledgers', () => {
+ withPublishedBase({}, (cwd) => {
+ assert.throws(
+ () => readPublishedLayerStateReservations('HEAD', cwd),
+ /no recognizable layer-state token ledger/,
+ );
+ });
+ withPublishedBase({ rows: [...reservationRows, ['future', 'a']] }, (cwd) => {
+ assert.throws(
+ () => readPublishedLayerStateReservations('HEAD', cwd),
+ /Duplicate layer-state token reservation/,
+ );
+ });
+ });
diff --cc src/data/layerStateTokenReservations.json
index 000000000,600358c7c..eb49eed27
mode 000000,100644..100644
--- a/src/data/layerStateTokenReservations.json
+++ b/src/data/layerStateTokenReservations.json
@@@ -1,0 -1,30 +1,31 @@@
+ [
+ ["ais-live-vessels", "a"],
+ ["alpr-cameras", "p"],
+ ["bhote-koshi-2026", "h"],
+ ["bhote-koshi-locator", "z"],
+ ["bikeshare", "b"],
+ ["cctv", "c"],
+ ["directions", "n"],
+ ["earthquakes", "e"],
+ ["fire-perimeters", "2"],
+ ["flights", "f"],
+ ["local-dams", "q"],
+ ["local-datacenters", "d"],
+ ["local-firms", "w"],
+ ["military", "m"],
+ ["military-awareness", "g"],
+ ["military-installations", "i"],
+ ["radio", "r"],
+ ["recent-imagery", "1"],
+ ["rocket-launches", "x"],
+ ["satellites", "s"],
++ ["street-level", "0"],
+ ["telegeography-submarine-cables", "u"],
+ ["traffic", "t"],
+ ["transit", "j"],
+ ["weather-cyclones", "y"],
+ ["weather-lightning", "l"],
+ ["weather-radar", "v"],
+ ["weather-satellite", "o"],
+ ["wind", "k"]
+ ]