@vizhub/quadstream 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,229 @@
1
+ import { assertPosition, boundsOf, simpleClosedRing, validPolygon, unionBounds, } from "./geometry.js";
2
+ /** Exact coordinate topology: no implicit snapping, deduping almost-equal points, or antimeridian wrapping. */
3
+ export function buildTopology(input) {
4
+ return buildTopologyWithPolicy(input, {
5
+ position: assertPosition,
6
+ ring: simpleClosedRing,
7
+ polygon: validPolygon,
8
+ });
9
+ }
10
+ /** Internal shared graph construction; coordinate semantics are provided by the caller. */
11
+ export function buildTopologyWithPolicy(input, policy) {
12
+ if (!input ||
13
+ input.type !== "FeatureCollection" ||
14
+ !Array.isArray(input.features))
15
+ throw new Error("Expected a GeoJSON FeatureCollection");
16
+ if (!input.features.length)
17
+ throw new Error("Empty FeatureCollection is not supported");
18
+ const vertices = [], byLocation = new Map(), featureIdsByVertex = new Map(), features = [];
19
+ const featureIds = new Set();
20
+ let overall;
21
+ function vertexId(p) {
22
+ const [x, y] = policy.position(p), key = JSON.stringify([x, y]);
23
+ const existing = byLocation.get(key);
24
+ if (existing !== undefined)
25
+ return existing;
26
+ const id = vertices.length;
27
+ vertices.push({ id, x, y, critical: false });
28
+ byLocation.set(key, id);
29
+ return id;
30
+ }
31
+ for (let f = 0; f < input.features.length; f++) {
32
+ const feature = input.features[f];
33
+ if (!feature ||
34
+ feature.type !== "Feature" ||
35
+ !feature.geometry ||
36
+ typeof feature.geometry !== "object")
37
+ throw new Error(`Feature ${f} must have a supported geometry`);
38
+ const featureId = String(feature.id ?? f);
39
+ if (featureIds.has(featureId))
40
+ throw new Error(`Duplicate feature id: ${featureId}`);
41
+ featureIds.add(featureId);
42
+ const { type, coordinates } = feature.geometry;
43
+ if (!["Polygon", "MultiPolygon", "LineString", "MultiLineString"].includes(type))
44
+ throw new Error(`Unsupported geometry: ${type}`);
45
+ const paths = [], groups = [];
46
+ function append(coords, closed) {
47
+ if (!Array.isArray(coords))
48
+ throw new Error("Invalid coordinate path");
49
+ const pts = coords.map(policy.position);
50
+ if (closed) {
51
+ if (pts.length >= 2 &&
52
+ pts[0][0] === pts.at(-1)[0] &&
53
+ pts[0][1] === pts.at(-1)[1])
54
+ pts.pop();
55
+ if (new Set(pts.map((p) => JSON.stringify(p))).size < 3 ||
56
+ !policy.ring([...pts, pts[0]]))
57
+ throw new Error(`Invalid or self-intersecting source polygon ring in feature ${featureId}`);
58
+ }
59
+ else if (pts.length < 2 ||
60
+ new Set(pts.map((p) => JSON.stringify(p))).size < 2 ||
61
+ (policy.line && !policy.line(pts)))
62
+ throw new Error(`Line requires >=2 distinct coordinates in feature ${featureId}`);
63
+ const ids = pts.map(vertexId);
64
+ for (const id of ids) {
65
+ if (!featureIdsByVertex.has(id))
66
+ featureIdsByVertex.set(id, new Set());
67
+ featureIdsByVertex.get(id).add(featureId);
68
+ }
69
+ paths.push({ ids, closed });
70
+ }
71
+ if (type === "Polygon") {
72
+ const group = [];
73
+ for (const ring of coordinates) {
74
+ group.push(paths.length);
75
+ append(ring, true);
76
+ }
77
+ if (!group.length ||
78
+ !policy.polygon(coordinates.map((r) => {
79
+ const pts = r.map(policy.position);
80
+ return pts[0][0] === pts.at(-1)[0] &&
81
+ pts[0][1] === pts.at(-1)[1]
82
+ ? pts
83
+ : [...pts, pts[0]];
84
+ })))
85
+ throw new Error(`Invalid polygon (possibly hole containment): ${featureId}`);
86
+ groups.push(group);
87
+ }
88
+ else if (type === "MultiPolygon") {
89
+ for (const polygon of coordinates) {
90
+ const group = [];
91
+ for (const ring of polygon) {
92
+ group.push(paths.length);
93
+ append(ring, true);
94
+ }
95
+ groups.push(group);
96
+ if (!policy.polygon(polygon.map((r) => {
97
+ const pts = r.map(policy.position);
98
+ return pts[0][0] === pts.at(-1)[0] &&
99
+ pts[0][1] === pts.at(-1)[1]
100
+ ? pts
101
+ : [...pts, pts[0]];
102
+ })))
103
+ throw new Error(`Invalid multipolygon component: ${featureId}`);
104
+ }
105
+ if (!groups.length)
106
+ throw new Error(`Empty multipolygon: ${featureId}`);
107
+ }
108
+ else if (type === "LineString") {
109
+ append(coordinates, false);
110
+ groups.push([0]);
111
+ }
112
+ else {
113
+ for (const line of coordinates) {
114
+ const i = paths.length;
115
+ append(line, false);
116
+ groups.push([i]);
117
+ }
118
+ if (!groups.length)
119
+ throw new Error(`Empty multiline: ${featureId}`);
120
+ }
121
+ const all = paths.flatMap((path) => path.ids.map((i) => [vertices[i].x, vertices[i].y]));
122
+ const b = boundsOf(all);
123
+ overall = overall ? unionBounds(overall, b) : b;
124
+ features.push({
125
+ id: featureId,
126
+ properties: { ...(feature.properties ?? {}) },
127
+ geometryType: type,
128
+ paths,
129
+ groups,
130
+ bounds: b,
131
+ });
132
+ }
133
+ const edgeOwners = new Map(), neighbors = new Map();
134
+ const edgeKey = (a, b) => (a < b ? `${a}:${b}` : `${b}:${a}`);
135
+ let pathNumber = 0;
136
+ for (const f of features)
137
+ for (const path of f.paths) {
138
+ const n = path.ids.length, limit = path.closed ? n : n - 1;
139
+ if (!path.closed) {
140
+ vertices[path.ids[0]].critical = true;
141
+ vertices[path.ids[n - 1]].critical = true;
142
+ }
143
+ if (path.closed) {
144
+ // Three stable anchors avoid collapsing an entire closed ring to one point.
145
+ for (const i of [0, Math.floor(n / 3), Math.floor((2 * n) / 3)])
146
+ vertices[path.ids[i]].critical = true;
147
+ }
148
+ for (let i = 0; i < limit; i++) {
149
+ const a = path.ids[i], b = path.ids[(i + 1) % n];
150
+ if (a === b)
151
+ continue;
152
+ const key = edgeKey(a, b);
153
+ if (!edgeOwners.has(key))
154
+ edgeOwners.set(key, new Set());
155
+ edgeOwners.get(key).add(pathNumber);
156
+ if (!neighbors.has(a))
157
+ neighbors.set(a, new Set());
158
+ if (!neighbors.has(b))
159
+ neighbors.set(b, new Set());
160
+ neighbors.get(a).add(b);
161
+ neighbors.get(b).add(a);
162
+ }
163
+ pathNumber++;
164
+ }
165
+ const incident = new Map();
166
+ for (const [edge, owners] of edgeOwners) {
167
+ const signature = [...owners].sort((a, b) => a - b).join(",");
168
+ const [a, b] = edge.split(":").map(Number);
169
+ for (const id of [a, b]) {
170
+ if (!incident.has(id))
171
+ incident.set(id, new Set());
172
+ incident.get(id).add(signature);
173
+ }
174
+ }
175
+ for (const v of vertices) {
176
+ const shapeCount = featureIdsByVertex.get(v.id)?.size ?? 0;
177
+ if (shapeCount >= 3 ||
178
+ neighbors.get(v.id)?.size !== 2 ||
179
+ incident.get(v.id)?.size !== 1)
180
+ v.critical = true;
181
+ }
182
+ const arcs = [], arcByKey = new Map();
183
+ function intern(ids) {
184
+ const forward = ids.join(","), backward = [...ids].reverse().join(",");
185
+ const reversed = forward > backward, key = reversed ? backward : forward;
186
+ const existing = arcByKey.get(key);
187
+ if (existing !== undefined)
188
+ return reversed ? -(existing + 1) : existing + 1;
189
+ const id = arcs.length;
190
+ arcs.push({ id, vertexIds: reversed ? [...ids].reverse() : [...ids] });
191
+ arcByKey.set(key, id);
192
+ return reversed ? -(id + 1) : id + 1;
193
+ }
194
+ const output = features.map((f) => ({
195
+ id: f.id,
196
+ properties: f.properties,
197
+ geometryType: f.geometryType,
198
+ groups: f.groups,
199
+ paths: [],
200
+ bounds: f.bounds,
201
+ }));
202
+ for (let fi = 0; fi < features.length; fi++) {
203
+ const feature = features[fi], result = output[fi];
204
+ for (const raw of feature.paths) {
205
+ let ids = [...raw.ids];
206
+ if (raw.closed) {
207
+ // Ring is cyclic: align at a stable marked vertex, without changing direction.
208
+ let anchor = 0;
209
+ for (let i = 1; i < ids.length; i++)
210
+ if (vertices[ids[i]].critical && ids[i] < ids[anchor])
211
+ anchor = i;
212
+ ids = [...ids.slice(anchor), ...ids.slice(0, anchor)];
213
+ }
214
+ const refs = [], n = ids.length, total = raw.closed ? n : n - 1;
215
+ let current = [ids[0]];
216
+ for (let i = 1; i <= total; i++) {
217
+ const next = ids[i % n];
218
+ current.push(next);
219
+ if (vertices[next].critical || i === total) {
220
+ if (current.length > 1)
221
+ refs.push(intern(current));
222
+ current = [next];
223
+ }
224
+ }
225
+ result.paths.push({ closed: raw.closed, arcs: refs });
226
+ }
227
+ }
228
+ return { vertices, arcs, features: output, bounds: overall };
229
+ }
@@ -0,0 +1,119 @@
1
+ /** Planar [x, y] coordinates. Geographic longitude wrapping is not implicit. */
2
+ export type Position = readonly [number, number];
3
+ export type Bounds = readonly [number, number, number, number];
4
+ export type GeometryType = "Polygon" | "MultiPolygon" | "LineString" | "MultiLineString";
5
+ export type Properties = Record<string, unknown>;
6
+ export type Geometry = {
7
+ type: "Polygon";
8
+ coordinates: Position[][];
9
+ } | {
10
+ type: "MultiPolygon";
11
+ coordinates: Position[][][];
12
+ } | {
13
+ type: "LineString";
14
+ coordinates: Position[];
15
+ } | {
16
+ type: "MultiLineString";
17
+ coordinates: Position[][];
18
+ };
19
+ export interface Feature {
20
+ type: "Feature";
21
+ id?: string | number;
22
+ properties: Properties | null;
23
+ geometry: Geometry;
24
+ }
25
+ export interface FeatureCollection {
26
+ type: "FeatureCollection";
27
+ features: Feature[];
28
+ }
29
+ export interface Vertex {
30
+ id: number;
31
+ x: number;
32
+ y: number;
33
+ critical: boolean;
34
+ }
35
+ export interface Arc {
36
+ id: number;
37
+ vertexIds: number[];
38
+ }
39
+ export interface TopologyPath {
40
+ closed: boolean;
41
+ arcs: number[];
42
+ }
43
+ export interface TopologyFeature {
44
+ id: string;
45
+ properties: Properties;
46
+ geometryType: GeometryType;
47
+ paths: TopologyPath[];
48
+ /** Each group contains indices into paths: rings of a polygon, or one line. */
49
+ groups: number[][];
50
+ bounds: Bounds;
51
+ }
52
+ export interface Topology {
53
+ vertices: Vertex[];
54
+ arcs: Arc[];
55
+ features: TopologyFeature[];
56
+ bounds: Bounds;
57
+ }
58
+ export interface QuadCell {
59
+ vertexId: number;
60
+ level: number;
61
+ i: number;
62
+ j: number;
63
+ key: string;
64
+ }
65
+ export interface SparseQuadtree {
66
+ bounds: Bounds;
67
+ maxLevel: number;
68
+ cells: QuadCell[];
69
+ levelByVertexId: number[];
70
+ }
71
+ export interface QueryOptions {
72
+ bounds?: Bounds;
73
+ level?: number;
74
+ validate?: boolean;
75
+ }
76
+ export interface QueryResult {
77
+ geojson: FeatureCollection;
78
+ level: number;
79
+ /** Whether the requested reconstruction passed the dataset's validity checks. */
80
+ valid: boolean;
81
+ usedFallback: boolean;
82
+ /** Spherical queries: arcs promoted to a finer level to keep features valid. */
83
+ promotedArcs?: number;
84
+ selectedFeatures: number;
85
+ selectedVertices: number;
86
+ }
87
+ export interface PartitionRecord {
88
+ id: number;
89
+ x: number;
90
+ y: number;
91
+ level: number;
92
+ }
93
+ export interface PartitionInfo {
94
+ key: string;
95
+ byteLength: number;
96
+ checksum: string;
97
+ vertexIds: number[];
98
+ minLevel: number;
99
+ bounds: Bounds;
100
+ }
101
+ export interface QuadstreamManifest {
102
+ format: "quadstream";
103
+ version: 1;
104
+ maxLevel: number;
105
+ fileDepth: number;
106
+ bounds: Bounds;
107
+ features: TopologyFeature[];
108
+ arcs: Arc[];
109
+ vertices: Array<{
110
+ id: number;
111
+ level: number;
112
+ critical: boolean;
113
+ }>;
114
+ partitions: PartitionInfo[];
115
+ }
116
+ export interface PartitionBundle {
117
+ manifest: QuadstreamManifest;
118
+ partitions: Map<string, Uint8Array>;
119
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "@vizhub/quadstream",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Deterministic, topology-aware progressive geographic geometry engine",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE",
20
+ "CHANGELOG.md",
21
+ "bin"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.json",
25
+ "typecheck": "tsc -p tsconfig.json --noEmit",
26
+ "prettier": "prettier --write .",
27
+ "lint": "eslint .",
28
+ "test": "npm run build && node --test test/*.test.mjs",
29
+ "check": "npm run typecheck && npm run test",
30
+ "demo:map": "node examples/progressive/server.mjs",
31
+ "test:browser": "npm run build && playwright test",
32
+ "demo:globe": "node examples/progressive/server.mjs --globe",
33
+ "test:globe:browser": "npm run build && playwright test globe.spec.mjs",
34
+ "prepack": "npm run build",
35
+ "test:package": "node scripts/test-package.mjs"
36
+ },
37
+ "devDependencies": {
38
+ "typescript": "^6.0.3",
39
+ "prettier": "3.10.1",
40
+ "eslint": "10.15.0",
41
+ "@eslint/js": "10.0.1",
42
+ "typescript-eslint": "8.74.0",
43
+ "globals": "17.14.0",
44
+ "maplibre-gl": "6.19.0",
45
+ "@playwright/test": "1.65.1",
46
+ "d3": "7.9.2",
47
+ "topojson-client": "3.1.0",
48
+ "world-atlas": "2.0.2"
49
+ },
50
+ "bin": {
51
+ "quadstream": "./bin/quadstream.mjs"
52
+ },
53
+ "license": "MIT",
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/vizhub-studio/quadstream.git"
57
+ },
58
+ "homepage": "https://github.com/vizhub-studio/quadstream#readme",
59
+ "bugs": {
60
+ "url": "https://github.com/vizhub-studio/quadstream/issues"
61
+ },
62
+ "keywords": [
63
+ "geometry",
64
+ "geojson",
65
+ "topojson",
66
+ "simplification",
67
+ "topology",
68
+ "quadtree",
69
+ "gis",
70
+ "progressive",
71
+ "d3",
72
+ "maplibre"
73
+ ],
74
+ "publishConfig": {
75
+ "access": "public"
76
+ }
77
+ }