Files
gods-eye-view/src/share/wire.test.mjs
T
Sameh Khamis da02fd8645 feat(share): short /share/<code> links with a compact versioned view format (#1418)
* feat(share): add compact versioned share-view codec

Add a standalone codec for `#s=<base64url>` share links: a version byte
followed by protobuf-style tag-length-value fields. Settings equal to
their default are omitted and refilled from the same table on decode;
unknown fields are skipped by wire type, so new fields never break
older apps. Views are a place (camera) or a thing (an aircraft,
military aircraft, vessel or satellite to follow, with camera offset
and last-known fix); an unknown kind falls back to the camera.

The decoder bounds its input and rejects malformed payloads with a
reason instead of throwing. A converter maps the long form's parsed
state to and from the codec state; the long form is unchanged.

* fix(share): tighten codec decoding after review

Unknown detection mode and allocation names now fall back to their
defaults instead of reaching the lenient long-form migration. Future
panel values and style-parameter tokens are skipped rather than applied
or rejected, and layer options are accepted only under their owner
layer. Wrap longitudes before scaling, normalize negative zero, reuse
the layer-state tracking ID grammar, and align the format doc with the
decoder.

* feat(share): let a host share the link its own way

ShareLinkManager.buildLink() returns the current share link without
copying it, and copyLink() now copies exactly that. The share button
passes the link to an optional services.shareLink(url), which resolves
to 'shared', 'copied', 'cancelled' or false; 'cancelled' shows no toast
and 'shared' shows the new "Link shared" (es, ru, zh-CN). Without the
service the button copies as before.

* feat(share): open and make short /share/<code> links

The share button now makes `<app>/share/<code>` links with the compact
share-view code, and the app opens them at start-up through the same
restore pipeline as long links. Once the app next writes the address, the
share path is replaced (no new history entry) by the app's own address and
the live long-form hash, so a reload follows the live view. A host can pass
the code as `initialShareCode` instead. A code that fails to decode restores
nothing and shows "This share link can't be opened".

The code gains a trailing CRC-8 check byte, so any single mistyped
character is rejected instead of opening a different view. Thing views no
longer store a camera: it is derived from the entity's last-known fix and
the follow offset on a sphere, the entity kind is implied by the id's
field, and the followed entity's layer bit is implied; an aircraft followed
from the app's own camera is a 42-character code. The `#s=` hash form is
gone.

While the camera follows an aircraft, military aircraft or satellite, the
link is a thing view with the camera's offset and the entity's position.
Opening one turns the layer on and follows the entity through the existing
shared-follow restore, then swings the camera round to the shared offset; a
vessel view selects the vessel once the vessel feed has it. If the entity
is not reporting within its window, the view stays at its last-known fix
and says so. The panel and style-parameter tables now come from the codec,
and a host share hook that returns a plain value or throws still gets a
toast.

* fix(share): encode style settings against the style's own look

Settings a style applies when selected (bloom, sharpen, HUD, detection,
celestial ring and the style's shader parameters) now default, per field,
to what that style applies in a fresh session, read from the tables the
app applies (the first-load baseline, the style presets and the shader
defaults). The encoder compares against the view's style and the decoder
fills omitted settings from the decoded style, so a view that keeps its
style's look costs only its camera and style. The previous defaults did not
match a fresh session (sharpen, HUD and detection were off), so every link
paid for them, and a style's own shader parameters were always written.

A test pins the per-style defaults as frozen v1 meanings. A followed
aircraft in Noir is now 44 characters and the real long-link example 39.

* docs: changelog for #1418
2026-10-26 15:31:51 -07:00

189 lines
5.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
ShareWireError,
WIRE_FIXED32,
WIRE_FIXED64,
WIRE_LEN,
WIRE_VARINT,
WireReader,
WireWriter,
crc8,
decodeBase64Url,
encodeBase64Url,
unzigzag,
zigzag,
} from './wire.js';
const reasonOf = (fn) => {
try {
fn();
} catch (error) {
assert.ok(error instanceof ShareWireError, String(error));
return error.reason;
}
assert.fail('expected a ShareWireError');
};
test('base64url round-trips every length and byte value without padding', () => {
for (let length = 0; length < 70; length += 1) {
const bytes = Uint8Array.from(
{ length },
(_, i) => (i * 97 + length) & 0xff,
);
const text = encodeBase64Url(bytes);
assert.match(text, /^[A-Za-z0-9_-]*$/);
if (length) assert.deepEqual(decodeBase64Url(text), bytes);
}
const all = Uint8Array.from({ length: 256 }, (_, i) => i);
assert.deepEqual(decodeBase64Url(encodeBase64Url(all)), all);
assert.equal(encodeBase64Url(Uint8Array.of(0xfb, 0xff)), '-_8');
});
test('base64url rejects padding, foreign characters, bad lengths and stray bits', () => {
for (const text of ['', 'AQ==', 'A+Q', 'A/Q', 'A Q', 'AQ%', 'A', 'AQAAA']) {
assert.ok(
['empty', 'bad-base64'].includes(reasonOf(() => decodeBase64Url(text))),
text,
);
}
// "AR" carries one byte (0x01) plus four trailing bits that must be zero.
assert.equal(
reasonOf(() => decodeBase64Url('AR')),
'bad-base64',
);
assert.deepEqual(decodeBase64Url('AQ'), Uint8Array.of(1));
});
test('zigzag maps small magnitudes of either sign to small codes', () => {
assert.deepEqual([0, -1, 1, -2, 2].map(zigzag), [0, 1, 2, 3, 4]);
for (const value of [0, 1, -1, 63, -64, 1e9, -1e9, 2 ** 51, -(2 ** 51)]) {
assert.equal(unzigzag(zigzag(value)), value);
}
});
test('varints round-trip up to the largest safe integer', () => {
const values = [
0,
1,
127,
128,
300,
2 ** 21,
2 ** 31,
2 ** 32 + 5,
Number.MAX_SAFE_INTEGER,
];
const writer = new WireWriter();
for (const value of values) writer.varint(value);
const reader = new WireReader(writer.finish());
for (const value of values) assert.equal(reader.varint(), value);
assert.ok(reader.done);
assert.deepEqual(
new WireWriter().varint(300).finish(),
Uint8Array.of(0xac, 0x02),
);
});
test('the writer refuses values the format cannot carry', () => {
assert.throws(() => new WireWriter().varint(-1), RangeError);
assert.throws(() => new WireWriter().varint(1.5), RangeError);
assert.throws(() => new WireWriter().varint(2 ** 53), RangeError);
assert.throws(() => new WireWriter().tag(0, WIRE_VARINT), RangeError);
assert.throws(() => new WireWriter().textField(1, 'é'), RangeError);
});
test('the reader rejects truncated, overlong and overflowing varints', () => {
assert.equal(
reasonOf(() => new WireReader(Uint8Array.of(0x80)).varint()),
'truncated',
);
assert.equal(
reasonOf(() => new WireReader(Uint8Array.of(0x81, 0x00)).varint()),
'non-canonical-varint',
);
const tooLong = new Uint8Array(9).fill(0xff);
assert.equal(
reasonOf(() => new WireReader(tooLong).varint()),
'varint-overflow',
);
const beyondSafe = Uint8Array.of(
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0xff,
0x7f,
);
assert.equal(
reasonOf(() => new WireReader(beyondSafe).varint()),
'varint-overflow',
);
});
test('the reader bounds lengths and rejects group and reserved wire types', () => {
const absurd = new WireWriter().tag(3, WIRE_LEN).varint(1_000_000).finish();
const reader = new WireReader(absurd);
reader.tag();
assert.equal(
reasonOf(() => reader.lengthDelimited()),
'truncated',
);
for (const wireType of [3, 4, 6, 7]) {
const bytes = new WireWriter().varint(8 + wireType).finish();
assert.equal(
reasonOf(() => new WireReader(bytes).tag()),
'bad-wire-type',
);
}
assert.equal(
reasonOf(() => new WireReader(Uint8Array.of(0x00)).tag()),
'bad-field-number',
);
});
test('skip steps over each wire type and stops at a truncated value', () => {
const writer = new WireWriter()
.uintField(1, 300)
.bytesField(2, [1, 2, 3])
.tag(3, WIRE_FIXED32);
writer.bytes.push(1, 2, 3, 4);
writer.tag(4, WIRE_FIXED64);
writer.bytes.push(1, 2, 3, 4, 5, 6, 7, 8);
writer.uintField(5, 9);
const reader = new WireReader(writer.finish());
for (let field = 1; field <= 4; field += 1)
reader.skip(reader.tag().wireType);
assert.deepEqual(reader.tag(), { field: 5, wireType: WIRE_VARINT });
assert.equal(reader.varint(), 9);
const short = new WireWriter().tag(1, WIRE_FIXED64).finish();
const shortReader = new WireReader(Uint8Array.of(...short, 1, 2));
assert.equal(
reasonOf(() => shortReader.skip(shortReader.tag().wireType)),
'truncated',
);
});
test('crc8 is CRC-8/SMBUS and catches every burst of up to 8 bits', () => {
// The catalogued check value for the ASCII digits 1–9.
assert.equal(crc8(new TextEncoder().encode('123456789')), 0xf4);
assert.equal(crc8([]), 0);
const bytes = [1, 0x10, 0x82, 0x40, 0x7f, 0xff, 0x00, 0x33];
const sum = crc8(bytes);
for (let bit = 0; bit + 8 <= bytes.length * 8; bit += 1) {
for (let pattern = 1; pattern < 256; pattern += 1) {
// Flip a burst starting at `bit` (its first bit always set).
if (!(pattern & 1)) continue;
const flipped = [...bytes];
for (let k = 0; k < 8; k += 1) {
if (!(pattern & (1 << k))) continue;
const at = bit + k;
flipped[at >> 3] ^= 0x80 >> (at & 7);
}
assert.notEqual(crc8(flipped), sum, `burst ${pattern} at bit ${bit}`);
}
}
});