@vim3d/tiles 0.0.0-stage → 0.3.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.
package/manifest.js ADDED
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTilesetManifest = parseTilesetManifest;
4
+ function fail(path, reason) {
5
+ throw new TypeError(`Invalid tileset manifest at ${path}: ${reason}`);
6
+ }
7
+ function record(value, path) {
8
+ if (!value || typeof value !== 'object' || Array.isArray(value))
9
+ fail(path, 'expected an object');
10
+ return value;
11
+ }
12
+ function number(value, path) {
13
+ if (typeof value !== 'number' || !Number.isFinite(value))
14
+ fail(path, 'expected a finite number');
15
+ return value;
16
+ }
17
+ function httpURL(value, path, base) {
18
+ let url;
19
+ try {
20
+ url = new URL(value, base);
21
+ }
22
+ catch {
23
+ fail(path, 'expected a valid URL');
24
+ }
25
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
26
+ fail(path, 'expected an HTTP(S) URL');
27
+ return url;
28
+ }
29
+ /** Validates a v1 manifest and resolves payload URLs against its absolute URL. */
30
+ function parseTilesetManifest(input, manifestUrl) {
31
+ const base = httpURL(String(manifestUrl), 'manifest URL');
32
+ const manifest = record(input, '$');
33
+ if (manifest.version !== 1)
34
+ fail('version', 'expected 1');
35
+ const origin = record(manifest.origin, 'origin');
36
+ const lat = number(origin.lat, 'origin.lat');
37
+ const lon = number(origin.lon, 'origin.lon');
38
+ const elevation = number(origin.elevation, 'origin.elevation');
39
+ if (Math.abs(lat) > 90)
40
+ fail('origin.lat', 'expected latitude in [-90, 90]');
41
+ if (Math.abs(lon) > 180)
42
+ fail('origin.lon', 'expected longitude in [-180, 180]');
43
+ const ids = new Set();
44
+ function readTile(value, path, parent) {
45
+ const node = record(value, path);
46
+ const { id } = node;
47
+ if (typeof id !== 'string' || !id.trim())
48
+ fail(`${path}.id`, 'expected a nonempty string');
49
+ if (ids.has(id))
50
+ fail(`${path}.id`, `duplicate tile ID ${id}`);
51
+ ids.add(id);
52
+ const raw = node.bounds;
53
+ if (!Array.isArray(raw) || raw.length !== 6)
54
+ fail(`${path}.bounds`, 'expected six coordinates');
55
+ const coords = Array.from(raw, (coord, i) => number(coord, `${path}.bounds[${i}]`));
56
+ const bounds = [coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]];
57
+ for (let axis = 0; axis < 3; axis++) {
58
+ if (bounds[axis] > bounds[axis + 3])
59
+ fail(`${path}.bounds`, 'minimum exceeds maximum');
60
+ if (parent && (bounds[axis] < parent.bounds[axis] || bounds[axis + 3] > parent.bounds[axis + 3])) {
61
+ fail(`${path}.bounds`, 'child bounds must fit inside parent bounds');
62
+ }
63
+ }
64
+ const geometricError = number(node.geometricError, `${path}.geometricError`);
65
+ if (geometricError < 0 || (parent && geometricError > parent.geometricError)) {
66
+ fail(`${path}.geometricError`, 'must be nonnegative and no greater than the parent error');
67
+ }
68
+ let url;
69
+ if (node.url !== undefined) {
70
+ if (typeof node.url !== 'string' || !node.url.trim())
71
+ fail(`${path}.url`, 'expected a nonempty string');
72
+ url = httpURL(node.url, `${path}.url`, base).href;
73
+ }
74
+ const tile = { id, bounds, geometricError, ...(url && { url }) };
75
+ const { children } = node;
76
+ if (children === undefined || (Array.isArray(children) && children.length === 0)) {
77
+ if (!url)
78
+ fail(path, 'a leaf must have a payload URL');
79
+ return tile;
80
+ }
81
+ if (!Array.isArray(children) || children.length > 4)
82
+ fail(`${path}.children`, 'expected up to four children');
83
+ return { ...tile, children: Array.from(children, (child, i) => readTile(child, `${path}.children[${i}]`, tile)) };
84
+ }
85
+ return { version: 1, origin: { lat, lon, elevation }, root: readTile(manifest.root, 'root') };
86
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@vim3d/tiles",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Stream spatial tiles for Vim3D scenes on demand.",
5
+ "license": "BSD-3-Clause",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "sideEffects": false,
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "directory": "dist"
13
+ },
14
+ "scripts": {
15
+ "clean": "makage clean",
16
+ "prepack": "npm run build",
17
+ "build": "makage build && cp scripts/esm-package.json dist/esm/package.json && cp TILESET.md dist/",
18
+ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js"
19
+ },
20
+ "dependencies": {
21
+ "@constructive-io/fetch": "^1.2.2",
22
+ "@mapbox/vector-tile": "^2.0.4",
23
+ "@vim3d/core": "^0.14.0",
24
+ "@vim3d/geojson": "^0.8.0",
25
+ "buffer": "^5.7.1",
26
+ "flatbuffers": "^25.9.23",
27
+ "flatgeobuf": "^4.6.1",
28
+ "pbf": "^4.0.1",
29
+ "pmtiles": "^4.5.0",
30
+ "pngjs": "^7.0.0"
31
+ },
32
+ "peerDependencies": {
33
+ "three": ">=0.170.0 <1.0.0"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "three": {
37
+ "optional": true
38
+ }
39
+ },
40
+ "devDependencies": {
41
+ "@types/pngjs": "^6.0.5",
42
+ "@types/three": "^0.185.4",
43
+ "makage": "^0.8.0",
44
+ "three": "^0.185.1"
45
+ },
46
+ "gitHead": "5dfcef742d82dcd8204f501981a9941a3d83174f"
47
+ }
package/pmtiles.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type SourceOptions, type TileSourceReader } from './source.js';
2
+ export interface PMTilesOptions extends SourceOptions {
3
+ readonly layers?: readonly string[] | ((zoom: number) => readonly string[] | undefined);
4
+ /** Keep features from different tiles even when they have the same ID. */
5
+ readonly keepTileFragments?: boolean;
6
+ /** Reject zoom/bbox combinations that would request more than this many tiles. */
7
+ readonly maxTiles?: number;
8
+ }
9
+ export declare class PMTilesTileBudgetError extends RangeError {
10
+ constructor();
11
+ }
12
+ /** Read the MVT tiles overlapping a WGS84 bbox in a PMTiles v3 archive. */
13
+ export declare function pmTiles(input: string | URL, options?: PMTilesOptions): TileSourceReader;
package/pmtiles.js ADDED
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PMTilesTileBudgetError = void 0;
4
+ exports.pmTiles = pmTiles;
5
+ const pmtiles_1 = require("pmtiles");
6
+ const source_js_1 = require("./source.js");
7
+ class PMTilesTileBudgetError extends RangeError {
8
+ constructor() {
9
+ super('PMTiles query exceeds maxTiles');
10
+ }
11
+ }
12
+ exports.PMTilesTileBudgetError = PMTilesTileBudgetError;
13
+ function tileY(lat, size) {
14
+ const clamped = Math.max(-85.0511287798066, Math.min(85.0511287798066, lat));
15
+ return size * (1 - Math.asinh(Math.tan(clamped * Math.PI / 180)) / Math.PI) / 2;
16
+ }
17
+ function bboxZoom([west, south, east, north]) {
18
+ return Math.floor(-Math.log2(Math.max((east - west) / 360, tileY(south, 1) - tileY(north, 1))));
19
+ }
20
+ /** Read the MVT tiles overlapping a WGS84 bbox in a PMTiles v3 archive. */
21
+ function pmTiles(input, options = {}) {
22
+ const url = (0, source_js_1.sourceURL)(input);
23
+ const maxTiles = (0, source_js_1.positiveInteger)(options.maxTiles ?? 64, 'maxTiles');
24
+ return (0, source_js_1.sourceReader)(options, async function* (bbox, context, requestedZoom) {
25
+ const source = {
26
+ getKey: () => url.href,
27
+ getBytes: async (offset, length, _signal, etag) => {
28
+ // The library asks for a 16 KiB bootstrap, which can include tile payloads.
29
+ // Supply just the header and root directory within that bootstrap instead.
30
+ if (offset === 0 && length === 16_384) {
31
+ const header = await (0, source_js_1.readRange)(url, 0, 127, context);
32
+ const { specVersion, rootDirectoryOffset: start, rootDirectoryLength: size, } = (0, pmtiles_1.bytesToHeader)(header.data, header.etag);
33
+ if (specVersion !== 3)
34
+ throw new Error('Expected a PMTiles v3 archive');
35
+ if (start < 127 || size < 1 || start + size > length)
36
+ throw new Error('Invalid PMTiles root directory span');
37
+ const root = await (0, source_js_1.readRange)(url, start, size, context);
38
+ if (root.etag !== header.etag)
39
+ throw new pmtiles_1.EtagMismatch();
40
+ const bytes = new Uint8Array(start + size);
41
+ bytes.set(new Uint8Array(header.data));
42
+ bytes.set(new Uint8Array(root.data), start);
43
+ return { data: bytes.buffer, etag: header.etag };
44
+ }
45
+ const range = await (0, source_js_1.readRange)(url, offset, length, context);
46
+ if (etag !== undefined && range.etag !== etag)
47
+ throw new pmtiles_1.EtagMismatch();
48
+ return range;
49
+ },
50
+ };
51
+ const archive = new pmtiles_1.PMTiles(source);
52
+ const header = await archive.getHeader();
53
+ if (header.tileType !== pmtiles_1.TileType.Mvt)
54
+ throw new Error('PMTiles source must contain MVT vector tiles');
55
+ if (header.minZoom > header.maxZoom || header.maxZoom > 26)
56
+ throw new Error('Invalid PMTiles zoom range');
57
+ const zoom = Math.max(header.minZoom, Math.min(header.maxZoom, Math.floor(requestedZoom)));
58
+ const size = 2 ** zoom;
59
+ const [west, south, east, north] = bbox;
60
+ const clip = (i) => Math.max(0, Math.min(size - 1, i));
61
+ if (south >= 85.0511287798066 || north <= -85.0511287798066)
62
+ return;
63
+ const x0 = clip(Math.floor((west + 180) / 360 * size));
64
+ const x1 = clip(Math.ceil((east + 180) / 360 * size) - 1);
65
+ const y0 = clip(Math.floor(tileY(north, size)));
66
+ const y1 = clip(Math.ceil(tileY(south, size)) - 1);
67
+ if ((x1 - x0 + 1) * (y1 - y0 + 1) > maxTiles)
68
+ throw new PMTilesTileBudgetError();
69
+ const layers = typeof options.layers === 'function' ? options.layers(zoom) : options.layers;
70
+ const [{ VectorTile }, { default: Pbf }] = await Promise.all([import('@mapbox/vector-tile'), import('pbf')]);
71
+ const seen = new Set();
72
+ for (let x = x0; x <= x1; x++) {
73
+ for (let y = y0; y <= y1; y++) {
74
+ const response = await archive.getZxy(zoom, x, y, context.signal);
75
+ context.signal.throwIfAborted();
76
+ if (!response)
77
+ continue;
78
+ const tile = new VectorTile(new Pbf(response.data));
79
+ const features = [];
80
+ for (const [name, layer] of Object.entries(tile.layers)) {
81
+ if (layers && !layers.includes(name))
82
+ continue;
83
+ for (let i = 0; i < layer.length; i++) {
84
+ const feature = (0, source_js_1.withId)(layer.feature(i).toGeoJSON(x, y, zoom), options.idField);
85
+ feature.id = JSON.stringify([name, feature.id]);
86
+ if (!options.keepTileFragments) {
87
+ const key = (0, source_js_1.featureKey)(feature);
88
+ if (seen.has(key))
89
+ continue;
90
+ seen.add(key);
91
+ }
92
+ features.push(feature);
93
+ }
94
+ }
95
+ yield features;
96
+ }
97
+ }
98
+ }, bboxZoom);
99
+ }
@@ -0,0 +1,23 @@
1
+ import type { FeatureCollection } from '@vim3d/geojson';
2
+ import { TileLoader, type LoaderOptions } from './loader.js';
3
+ import type { TileOrigin } from './manifest.js';
4
+ import type { TileSourceConfig } from './source-config.js';
5
+ import { type SourceBBox, type TileSourceReader } from './source.js';
6
+ export type QueryTileSourceConfig = TileSourceConfig & {
7
+ readonly bounds: SourceBBox;
8
+ readonly origin: TileOrigin;
9
+ readonly elevationBounds?: readonly [number, number];
10
+ };
11
+ export type CreateTileSourceReader = (config: QueryTileSourceConfig) => TileSourceReader | Promise<TileSourceReader>;
12
+ export interface QueryTile extends FeatureCollection {
13
+ readonly sourceId: string;
14
+ readonly attribution?: string;
15
+ readonly bbox: SourceBBox;
16
+ readonly zoom: number;
17
+ }
18
+ export interface QueryLoaderOptions extends LoaderOptions<QueryTile> {
19
+ readonly maxVisibleTiles?: number;
20
+ readonly maxFeaturesPerTile?: number;
21
+ }
22
+ export declare function validateTileSource(config: unknown): asserts config is QueryTileSourceConfig;
23
+ export declare function openQueryTiles(config: QueryTileSourceConfig, reader: TileSourceReader, options?: QueryLoaderOptions): TileLoader<QueryTile>;
package/query-tiles.js ADDED
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateTileSource = validateTileSource;
4
+ exports.openQueryTiles = openQueryTiles;
5
+ const core_1 = require("@vim3d/core");
6
+ const loader_js_1 = require("./loader.js");
7
+ const source_js_1 = require("./source.js");
8
+ const view_js_1 = require("./view.js");
9
+ const radians = Math.PI / 180;
10
+ function boundedInteger(value, name, min, max = Number.MAX_SAFE_INTEGER) {
11
+ if (!Number.isSafeInteger(value) || value < min || value > max)
12
+ throw new RangeError(`Invalid ${name}`);
13
+ return value;
14
+ }
15
+ function validateTileSource(config) {
16
+ const candidate = config;
17
+ if (!candidate || !['flatgeobuf', 'pmtiles', 'ogc-features', 'socrata'].includes(candidate.kind)) {
18
+ throw new TypeError('Invalid tile source kind');
19
+ }
20
+ if (typeof candidate.url !== 'string' || !['http:', 'https:'].includes(new URL(candidate.url).protocol)) {
21
+ throw new TypeError('Expected an HTTP(S) tile source URL');
22
+ }
23
+ const { bounds, origin, elevationBounds } = candidate;
24
+ const minZoom = boundedInteger(candidate.minZoom ?? 1, 'minZoom', 1, 24);
25
+ boundedInteger(candidate.maxZoom ?? 16, 'maxZoom', minZoom, 24);
26
+ const [w, s, e, n] = Array.isArray(bounds) ? bounds : [];
27
+ if (!Array.isArray(bounds) || bounds.length !== 4 || !bounds.every(Number.isFinite) ||
28
+ w < -180 || e > 180 || s < -90 || n > 90 || w >= e || s >= n)
29
+ throw new RangeError('Invalid tile source bounds');
30
+ if (!origin || ![origin.lat, origin.lon, origin.elevation].every(Number.isFinite) ||
31
+ Math.abs(origin.lat) > 90 || Math.abs(origin.lon) > 180)
32
+ throw new RangeError('Invalid tile source origin');
33
+ if (elevationBounds !== undefined && (!Array.isArray(elevationBounds) || elevationBounds.length !== 2 ||
34
+ !elevationBounds.every(Number.isFinite) || elevationBounds[0] > elevationBounds[1])) {
35
+ throw new RangeError('Invalid tile source elevationBounds');
36
+ }
37
+ }
38
+ function openQueryTiles(config, reader, options = {}) {
39
+ validateTileSource(config);
40
+ const minZoom = boundedInteger(config.minZoom ?? 1, 'minZoom', 1, 24);
41
+ const maxZoom = boundedInteger(config.maxZoom ?? 16, 'maxZoom', minZoom, 24);
42
+ const maxTiles = boundedInteger(options.maxVisibleTiles ?? 64, 'maxVisibleTiles', 1);
43
+ const maxFeatures = boundedInteger(options.maxFeaturesPerTile ?? 10_000, 'maxFeaturesPerTile', 1);
44
+ const { origin } = config;
45
+ const [minElevation, maxElevation] = config.elevationBounds ?? [origin.elevation - 100, origin.elevation + 1000];
46
+ const sourceId = config.url;
47
+ const attribution = config.attribution ?? reader.attribution;
48
+ function cell(bbox, id, zoom) {
49
+ const [w, s, e, n] = bbox;
50
+ const lonMid = (w + e) / 2, latMid = (s + n) / 2;
51
+ const samples = [[w, s], [w, n], [e, s], [e, n],
52
+ [lonMid, s], [lonMid, n], [w, latMid], [e, latMid]];
53
+ const points = samples.flatMap(([lon, lat]) => [
54
+ (0, core_1.geodeticToScene)(origin, lat, lon, minElevation),
55
+ (0, core_1.geodeticToScene)(origin, lat, lon, maxElevation),
56
+ ]);
57
+ // Bound curvature between projected samples.
58
+ const span = radians * Math.hypot(e - w, n - s);
59
+ const padding = (7_000_000 + Math.max(Math.abs(minElevation), Math.abs(maxElevation))) * span * span / 4;
60
+ const [xs, ys, zs] = [0, 1, 2].map(axis => points.map(point => point[axis]));
61
+ const bounds = [Math.min(...xs) - padding, Math.min(...ys) - padding, Math.min(...zs) - padding,
62
+ Math.max(...xs) + padding, Math.max(...ys) + padding, Math.max(...zs) + padding];
63
+ return { id, bbox, zoom, bounds, geometricError: span * 6_378_137 / 8 };
64
+ }
65
+ const [west, south, east, north] = config.bounds;
66
+ const baseZoom = Math.max(0, Math.min(maxZoom - 1, Math.floor(Math.log2(360 / Math.max(east - west, north - south)))));
67
+ const root = cell(config.bounds, 'r', baseZoom);
68
+ function plan(view) {
69
+ const bounds = root.bounds;
70
+ const coversExtent = view.frustum.every(([a, b, c, d]) => a * bounds[a < 0 ? 3 : 0] + b * bounds[b < 0 ? 4 : 1] + c * bounds[c < 0 ? 5 : 2] + d >= 0);
71
+ if (coversExtent || (0, view_js_1.screenSpaceError)(root, view.projection) <= view.maxScreenSpaceError)
72
+ return [];
73
+ const firstQueryZoom = Math.max(minZoom, baseZoom + 1);
74
+ for (let zoomLimit = maxZoom; zoomLimit >= firstQueryZoom; zoomLimit--) {
75
+ const selected = [];
76
+ let visited = 0;
77
+ let overBudget = false;
78
+ function visit(tile) {
79
+ if (overBudget || !(0, view_js_1.intersects)(tile.bounds, view.frustum))
80
+ return;
81
+ if (++visited > maxTiles * (zoomLimit - baseZoom + 1) * 4) {
82
+ overBudget = true;
83
+ return;
84
+ }
85
+ const error = (0, view_js_1.screenSpaceError)(tile, view.projection);
86
+ const refine = error > view.maxScreenSpaceError;
87
+ if (tile.zoom <= firstQueryZoom && error < view.maxScreenSpaceError)
88
+ return;
89
+ if (tile.zoom >= firstQueryZoom && (!refine || tile.zoom === zoomLimit)) {
90
+ if (selected.length === maxTiles)
91
+ overBudget = true;
92
+ else
93
+ selected.push(tile);
94
+ return;
95
+ }
96
+ const [w, s, e, n] = tile.bbox;
97
+ const x = (w + e) / 2, y = (s + n) / 2;
98
+ if (x === w || x === e || y === s || y === n)
99
+ return;
100
+ const boxes = [[w, s, x, y], [x, s, e, y], [w, y, x, n], [x, y, e, n]];
101
+ for (const [i, box] of boxes.entries())
102
+ visit(cell(box, tile.id + i, tile.zoom + 1));
103
+ }
104
+ visit(root);
105
+ if (!overBudget)
106
+ return selected;
107
+ }
108
+ return [];
109
+ }
110
+ return new loader_js_1.TileLoader(loader_js_1.sourceMode, undefined, {
111
+ ...options, origin, root,
112
+ plan: view => plan(view).map(tile => ({ tile, query: { bbox: tile.bbox, zoom: tile.zoom } })),
113
+ selectVisible: visible => visible,
114
+ async read({ bbox, zoom = minZoom }, { signal, fetch }) {
115
+ const features = [];
116
+ const seen = new Set();
117
+ let count = 0;
118
+ for await (const page of reader.query(bbox, { signal, zoom, fetch })) {
119
+ signal.throwIfAborted();
120
+ for (const feature of page) {
121
+ count++;
122
+ const propertyId = config.idField ? feature.properties?.[config.idField] : undefined;
123
+ const identified = feature.id === undefined
124
+ && ((typeof propertyId === 'string' && propertyId.trim()) || Number.isFinite(propertyId))
125
+ ? (0, source_js_1.withId)(feature, config.idField) : feature;
126
+ if (identified.id !== undefined) {
127
+ const key = (0, source_js_1.featureKey)(identified);
128
+ if (!seen.has(key)) {
129
+ seen.add(key);
130
+ features.push(identified);
131
+ }
132
+ }
133
+ else
134
+ features.push(identified);
135
+ if (count === maxFeatures)
136
+ break;
137
+ }
138
+ if (count === maxFeatures)
139
+ break;
140
+ }
141
+ return { type: 'FeatureCollection', features, bbox, zoom, sourceId, attribution };
142
+ },
143
+ });
144
+ }
@@ -0,0 +1,26 @@
1
+ import type { TileOrigin } from './manifest.js';
2
+ import type { SourceBBox, SourceOptions, TileSourceReader } from './source.js';
3
+ interface SourceConfigBase extends SourceOptions {
4
+ readonly url: string;
5
+ readonly bounds?: SourceBBox;
6
+ readonly origin?: TileOrigin;
7
+ }
8
+ interface PagedConfig {
9
+ readonly pageSize?: number;
10
+ readonly maxFeatures?: number;
11
+ readonly properties?: readonly string[];
12
+ }
13
+ export type TileSourceConfig = SourceConfigBase & ({
14
+ readonly kind: 'flatgeobuf';
15
+ } | {
16
+ readonly kind: 'pmtiles';
17
+ readonly maxTiles?: number;
18
+ readonly layers?: readonly string[];
19
+ } | ({
20
+ readonly kind: 'ogc-features';
21
+ } & PagedConfig) | ({
22
+ readonly kind: 'socrata';
23
+ readonly geomField?: string;
24
+ } & PagedConfig));
25
+ export declare function createReader(config: TileSourceConfig): TileSourceReader;
26
+ export {};
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createReader = createReader;
4
+ const feature_api_js_1 = require("./feature-api.js");
5
+ const flatgeobuf_js_1 = require("./flatgeobuf.js");
6
+ const pmtiles_js_1 = require("./pmtiles.js");
7
+ function createReader(config) {
8
+ switch (config.kind) {
9
+ case 'flatgeobuf': return (0, flatgeobuf_js_1.flatGeobuf)(config.url, config);
10
+ case 'pmtiles': return (0, pmtiles_js_1.pmTiles)(config.url, config);
11
+ case 'ogc-features': return (0, feature_api_js_1.ogcApiFeatures)(config.url, config);
12
+ case 'socrata': return (0, feature_api_js_1.socrataGeoJSON)(config.url, config);
13
+ default: throw new TypeError('Unknown tile source kind');
14
+ }
15
+ }
package/source.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import type { Feature } from '@vim3d/geojson';
2
+ /** WGS84 [west, south, east, north]. Split antimeridian-crossing views into two queries. */
3
+ export type SourceBBox = readonly [number, number, number, number];
4
+ export interface SourceQuery {
5
+ readonly bbox: SourceBBox;
6
+ readonly zoom?: number;
7
+ }
8
+ export interface SourceReadOptions {
9
+ readonly signal: AbortSignal;
10
+ readonly zoom?: number;
11
+ readonly fetch?: typeof globalThis.fetch;
12
+ }
13
+ export interface TileSourceReader {
14
+ readonly attribution?: string;
15
+ query(bbox: SourceBBox, options: SourceReadOptions): AsyncIterable<readonly Feature[]>;
16
+ }
17
+ export interface SourceOptions {
18
+ readonly idField?: string;
19
+ readonly attribution?: string;
20
+ readonly minZoom?: number;
21
+ readonly maxZoom?: number;
22
+ }
23
+ export interface FeaturePageOptions extends SourceOptions {
24
+ readonly pageSize?: number;
25
+ /** Maximum features returned per bbox/zoom query, across all pages. */
26
+ readonly maxFeatures?: number | ((zoom: number) => number);
27
+ /** Request only these attributes at this zoom, where supported by the service. */
28
+ readonly properties?: readonly string[] | ((zoom: number) => readonly string[] | undefined);
29
+ }
30
+ export declare const defaultFetch: typeof globalThis.fetch;
31
+ export declare function sourceURL(input: string | URL): URL;
32
+ export declare function validateQuery(bbox: SourceBBox, zoom?: number): void;
33
+ export declare function positiveInteger(value: number, name: string): number;
34
+ export declare function withId(feature: Feature, field?: string): Feature & {
35
+ id: string | number;
36
+ };
37
+ export declare function featureKey(feature: Feature): string;
38
+ export declare function sourceReader(options: SourceOptions, read: (bbox: SourceBBox, context: SourceReadOptions, zoom: number) => AsyncIterable<readonly Feature[]>, defaultZoom?: (bbox: SourceBBox) => number): TileSourceReader;
39
+ export declare function readRange(url: URL, offset: number, length: number, { fetch, signal }: SourceReadOptions): Promise<{
40
+ data: ArrayBuffer;
41
+ etag?: string;
42
+ }>;
package/source.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultFetch = void 0;
4
+ exports.sourceURL = sourceURL;
5
+ exports.validateQuery = validateQuery;
6
+ exports.positiveInteger = positiveInteger;
7
+ exports.withId = withId;
8
+ exports.featureKey = featureKey;
9
+ exports.sourceReader = sourceReader;
10
+ exports.readRange = readRange;
11
+ const fetch_1 = require("@constructive-io/fetch");
12
+ const defaultFetch = (input, init) => {
13
+ // The Node localhost shim buffers the body before exposing the status.
14
+ if (input instanceof URL && (0, fetch_1.isLocalhostSubdomain)(input.hostname) && new Headers(init?.headers).has('range')) {
15
+ return globalThis.fetch(input, init);
16
+ }
17
+ return (0, fetch_1.createFetch)()(input, init);
18
+ };
19
+ exports.defaultFetch = defaultFetch;
20
+ function sourceURL(input) {
21
+ const url = new URL(input);
22
+ if (!['http:', 'https:'].includes(url.protocol))
23
+ throw new TypeError('Expected an HTTP(S) source URL');
24
+ return url;
25
+ }
26
+ function validateQuery(bbox, zoom) {
27
+ if (!Array.isArray(bbox) || bbox.length !== 4 || !Array.from(bbox).every(Number.isFinite)
28
+ || bbox[0] < -180 || bbox[2] > 180 || bbox[1] < -90 || bbox[3] > 90
29
+ || bbox[0] >= bbox[2] || bbox[1] >= bbox[3]) {
30
+ throw new RangeError('Expected a nonempty WGS84 bbox');
31
+ }
32
+ if (zoom !== undefined && !Number.isFinite(zoom))
33
+ throw new RangeError('Expected a finite source zoom');
34
+ }
35
+ function positiveInteger(value, name) {
36
+ if (!Number.isSafeInteger(value) || value < 1)
37
+ throw new RangeError(`${name} must be a positive integer`);
38
+ return value;
39
+ }
40
+ function isFeatureId(value) {
41
+ return (typeof value === 'string' && value.trim().length > 0)
42
+ || (typeof value === 'number' && Number.isFinite(value));
43
+ }
44
+ const propertyIds = new WeakSet();
45
+ function withId(feature, field) {
46
+ const preferred = field === undefined ? undefined : feature.properties?.[field];
47
+ const usesProperty = isFeatureId(preferred);
48
+ const id = usesProperty ? preferred : feature.id;
49
+ if (!isFeatureId(id)) {
50
+ throw new Error('Feature has no stable ID; configure idField or use a source with feature IDs');
51
+ }
52
+ const identified = { ...feature, id };
53
+ if (usesProperty)
54
+ propertyIds.add(identified);
55
+ return identified;
56
+ }
57
+ function featureKey(feature) {
58
+ return JSON.stringify([propertyIds.has(feature) ? 'property' : 'feature', feature.id]);
59
+ }
60
+ function sourceReader(options, read, defaultZoom = () => 0) {
61
+ const { attribution, minZoom = 0, maxZoom = Infinity } = options;
62
+ if (!Number.isSafeInteger(minZoom) || minZoom < 0
63
+ || (options.maxZoom !== undefined && (!Number.isSafeInteger(maxZoom) || maxZoom < minZoom))) {
64
+ throw new RangeError('Invalid source zoom range');
65
+ }
66
+ return {
67
+ attribution,
68
+ async *query(bbox, context) {
69
+ validateQuery(bbox, context.zoom);
70
+ context.signal.throwIfAborted();
71
+ const zoom = Math.max(minZoom, Math.min(maxZoom, context.zoom ?? defaultZoom(bbox)));
72
+ yield* read(bbox, context, zoom);
73
+ },
74
+ };
75
+ }
76
+ async function readRange(url, offset, length, { fetch = exports.defaultFetch, signal }) {
77
+ const end = offset + length - 1;
78
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(end) || length < 1) {
79
+ throw new RangeError('Invalid source byte range');
80
+ }
81
+ signal.throwIfAborted();
82
+ const response = await fetch(url, {
83
+ headers: { range: `bytes=${offset}-${end}` }, redirect: 'error', signal,
84
+ });
85
+ const range = /^bytes (\d+)-(\d+)\/(\d+)$/i.exec(response.headers.get('content-range') ?? '');
86
+ if (response.status !== 206 || !range || Number(range[1]) !== offset || Number(range[2]) !== end
87
+ || !Number.isSafeInteger(Number(range[3])) || end >= Number(range[3]) || (offset === 0 && end + 1 === Number(range[3]))) {
88
+ void response.body?.cancel().catch(() => { });
89
+ throw new Error(`Source requires a partial HTTP byte range: ${url} (${response.status})`);
90
+ }
91
+ signal.throwIfAborted();
92
+ const data = await response.arrayBuffer();
93
+ signal.throwIfAborted();
94
+ if (data.byteLength !== length)
95
+ throw new Error('Source byte range has the wrong length');
96
+ return { data, etag: response.headers.get('etag') ?? undefined };
97
+ }
package/terrarium.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { type GeoOrigin, type HeightGrid } from '@vim3d/core';
2
+ import { type SourceBBox, type SourceReadOptions } from './source.js';
3
+ /** Metric scene bounds: [minX, minZ, maxX, maxZ]. */
4
+ export type ElevationBounds = readonly [number, number, number, number];
5
+ export type TerrariumConfig = {
6
+ readonly origin: GeoOrigin;
7
+ readonly zoom: number;
8
+ readonly url: string;
9
+ readonly maxTiles?: number;
10
+ readonly spacing?: number;
11
+ } & ({
12
+ readonly bbox: SourceBBox;
13
+ readonly sceneBounds?: never;
14
+ } | {
15
+ readonly bbox?: never;
16
+ readonly sceneBounds: ElevationBounds;
17
+ });
18
+ export interface TerrariumElevation {
19
+ readonly bounds: ElevationBounds;
20
+ readonly height: (x: number, z: number) => number | null;
21
+ readonly grid: HeightGrid;
22
+ readonly datum: number;
23
+ readonly tileCount: number;
24
+ }
25
+ export declare function terrariumHeight(r: number, g: number, b: number): number;
26
+ /** Read a bounded Terrarium XYZ view and sample its triangulated height grid. */
27
+ export declare function readTerrarium(config: TerrariumConfig, { signal, fetch: fetchTile, }: SourceReadOptions): Promise<TerrariumElevation>;