@loaders.gl/shapefile 3.4.11 → 3.4.12

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.
@@ -1,244 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.replaceExtension = exports.loadShapefileSidecarFiles = exports.parseShapefile = exports.parseShapefileInBatches = void 0;
4
- const gis_1 = require("@loaders.gl/gis");
5
- const proj4_1 = require("@math.gl/proj4");
6
- const parse_shx_1 = require("./parse-shx");
7
- const zip_batch_iterators_1 = require("../streaming/zip-batch-iterators");
8
- const shp_loader_1 = require("../../shp-loader");
9
- const dbf_loader_1 = require("../../dbf-loader");
10
- /**
11
- * Parsing of file in batches
12
- */
13
- // eslint-disable-next-line max-statements, complexity
14
- async function* parseShapefileInBatches(asyncIterator, options, context) {
15
- const { reproject = false, _targetCrs = 'WGS84' } = options?.gis || {};
16
- const { shx, cpg, prj } = await loadShapefileSidecarFiles(options, context);
17
- // parse geometries
18
- // @ts-ignore context must be defined
19
- const shapeIterable = await context.parseInBatches(asyncIterator, shp_loader_1.SHPLoader, options);
20
- // parse properties
21
- let propertyIterable;
22
- // @ts-ignore context must be defined
23
- const dbfResponse = await context.fetch(replaceExtension(context?.url || '', 'dbf'));
24
- if (dbfResponse.ok) {
25
- // @ts-ignore context must be defined
26
- propertyIterable = await context.parseInBatches(dbfResponse, dbf_loader_1.DBFLoader, {
27
- ...options,
28
- dbf: { encoding: cpg || 'latin1' }
29
- });
30
- }
31
- // When `options.metadata` is `true`, there's an extra initial `metadata`
32
- // object before the iterator starts. zipBatchIterators expects to receive
33
- // batches of Array objects, and will fail with non-iterable batches, so it's
34
- // important to skip over the first batch.
35
- let shapeHeader = (await shapeIterable.next()).value;
36
- if (shapeHeader && shapeHeader.batchType === 'metadata') {
37
- shapeHeader = (await shapeIterable.next()).value;
38
- }
39
- let dbfHeader = {};
40
- if (propertyIterable) {
41
- dbfHeader = (await propertyIterable.next()).value;
42
- if (dbfHeader && dbfHeader.batchType === 'metadata') {
43
- dbfHeader = (await propertyIterable.next()).value;
44
- }
45
- }
46
- let iterator;
47
- if (propertyIterable) {
48
- iterator = (0, zip_batch_iterators_1.zipBatchIterators)(shapeIterable, propertyIterable);
49
- }
50
- else {
51
- iterator = shapeIterable;
52
- }
53
- for await (const item of iterator) {
54
- let geometries;
55
- let properties;
56
- if (!propertyIterable) {
57
- geometries = item;
58
- }
59
- else {
60
- [geometries, properties] = item;
61
- }
62
- const geojsonGeometries = parseGeometries(geometries);
63
- let features = joinProperties(geojsonGeometries, properties);
64
- if (reproject) {
65
- // @ts-ignore
66
- features = reprojectFeatures(features, prj, _targetCrs);
67
- }
68
- yield {
69
- encoding: cpg,
70
- prj,
71
- shx,
72
- header: shapeHeader,
73
- data: features
74
- };
75
- }
76
- }
77
- exports.parseShapefileInBatches = parseShapefileInBatches;
78
- /**
79
- * Parse shapefile
80
- *
81
- * @param arrayBuffer
82
- * @param options
83
- * @param context
84
- * @returns output of shapefile
85
- */
86
- async function parseShapefile(arrayBuffer, options, context) {
87
- const { reproject = false, _targetCrs = 'WGS84' } = options?.gis || {};
88
- const { shx, cpg, prj } = await loadShapefileSidecarFiles(options, context);
89
- // parse geometries
90
- // @ts-ignore context must be defined
91
- const { header, geometries } = await context.parse(arrayBuffer, shp_loader_1.SHPLoader, options); // {shp: shx}
92
- const geojsonGeometries = parseGeometries(geometries);
93
- // parse properties
94
- let properties = [];
95
- // @ts-ignore context must be defined
96
- const dbfResponse = await context.fetch(replaceExtension(context.url, 'dbf'));
97
- if (dbfResponse.ok) {
98
- // @ts-ignore context must be defined
99
- properties = await context.parse(dbfResponse, dbf_loader_1.DBFLoader, { dbf: { encoding: cpg || 'latin1' } });
100
- }
101
- let features = joinProperties(geojsonGeometries, properties);
102
- if (reproject) {
103
- features = reprojectFeatures(features, prj, _targetCrs);
104
- }
105
- return {
106
- encoding: cpg,
107
- prj,
108
- shx,
109
- header,
110
- data: features
111
- };
112
- }
113
- exports.parseShapefile = parseShapefile;
114
- /**
115
- * Parse geometries
116
- *
117
- * @param geometries
118
- * @returns geometries as an array
119
- */
120
- function parseGeometries(geometries) {
121
- const geojsonGeometries = [];
122
- for (const geom of geometries) {
123
- geojsonGeometries.push((0, gis_1.binaryToGeometry)(geom));
124
- }
125
- return geojsonGeometries;
126
- }
127
- /**
128
- * Join properties and geometries into features
129
- *
130
- * @param geometries [description]
131
- * @param properties [description]
132
- * @return [description]
133
- */
134
- function joinProperties(geometries, properties) {
135
- const features = [];
136
- for (let i = 0; i < geometries.length; i++) {
137
- const geometry = geometries[i];
138
- const feature = {
139
- type: 'Feature',
140
- geometry,
141
- // properties can be undefined if dbfResponse above was empty
142
- properties: (properties && properties[i]) || {}
143
- };
144
- features.push(feature);
145
- }
146
- return features;
147
- }
148
- /**
149
- * Reproject GeoJSON features to output CRS
150
- *
151
- * @param features parsed GeoJSON features
152
- * @param sourceCrs source coordinate reference system
153
- * @param targetCrs †arget coordinate reference system
154
- * @return Reprojected Features
155
- */
156
- function reprojectFeatures(features, sourceCrs, targetCrs) {
157
- if (!sourceCrs && !targetCrs) {
158
- return features;
159
- }
160
- const projection = new proj4_1.Proj4Projection({ from: sourceCrs || 'WGS84', to: targetCrs || 'WGS84' });
161
- return (0, gis_1.transformGeoJsonCoords)(features, (coord) => projection.project(coord));
162
- }
163
- /**
164
- *
165
- * @param options
166
- * @param context
167
- * @returns Promise
168
- */
169
- // eslint-disable-next-line max-statements
170
- async function loadShapefileSidecarFiles(options, context) {
171
- // Attempt a parallel load of the small sidecar files
172
- // @ts-ignore context must be defined
173
- const { url, fetch } = context;
174
- const shxPromise = fetch(replaceExtension(url, 'shx'));
175
- const cpgPromise = fetch(replaceExtension(url, 'cpg'));
176
- const prjPromise = fetch(replaceExtension(url, 'prj'));
177
- await Promise.all([shxPromise, cpgPromise, prjPromise]);
178
- let shx;
179
- let cpg;
180
- let prj;
181
- const shxResponse = await shxPromise;
182
- if (shxResponse.ok) {
183
- const arrayBuffer = await shxResponse.arrayBuffer();
184
- shx = (0, parse_shx_1.parseShx)(arrayBuffer);
185
- }
186
- const cpgResponse = await cpgPromise;
187
- if (cpgResponse.ok) {
188
- cpg = await cpgResponse.text();
189
- }
190
- const prjResponse = await prjPromise;
191
- if (prjResponse.ok) {
192
- prj = await prjResponse.text();
193
- }
194
- return {
195
- shx,
196
- cpg,
197
- prj
198
- };
199
- }
200
- exports.loadShapefileSidecarFiles = loadShapefileSidecarFiles;
201
- /**
202
- * Replace the extension at the end of a path.
203
- *
204
- * Matches the case of new extension with the case of the original file extension,
205
- * to increase the chance of finding files without firing off a request storm looking for various case combinations
206
- *
207
- * NOTE: Extensions can be both lower and uppercase
208
- * per spec, extensions should be lower case, but that doesn't mean they always are. See:
209
- * calvinmetcalf/shapefile-js#64, mapserver/mapserver#4712
210
- * https://trac.osgeo.org/mapserver/ticket/166
211
- */
212
- function replaceExtension(url, newExtension) {
213
- const baseName = basename(url);
214
- const extension = extname(url);
215
- const isUpperCase = extension === extension.toUpperCase();
216
- if (isUpperCase) {
217
- newExtension = newExtension.toUpperCase();
218
- }
219
- return `${baseName}.${newExtension}`;
220
- }
221
- exports.replaceExtension = replaceExtension;
222
- // NOTE - this gives the entire path minus extension (i.e. NOT same as path.basename)
223
- /**
224
- * @param url
225
- * @returns string
226
- */
227
- function basename(url) {
228
- const extIndex = url && url.lastIndexOf('.');
229
- if (typeof extIndex === 'number') {
230
- return extIndex >= 0 ? url.substr(0, extIndex) : '';
231
- }
232
- return extIndex;
233
- }
234
- /**
235
- * @param url
236
- * @returns string
237
- */
238
- function extname(url) {
239
- const extIndex = url && url.lastIndexOf('.');
240
- if (typeof extIndex === 'number') {
241
- return extIndex >= 0 ? url.substr(extIndex + 1) : '';
242
- }
243
- return extIndex;
244
- }
@@ -1,287 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseRecord = void 0;
4
- const LITTLE_ENDIAN = true;
5
- /**
6
- * Parse individual record
7
- *
8
- * @param view Record data
9
- * @return Binary Geometry Object
10
- */
11
- // eslint-disable-next-line complexity
12
- function parseRecord(view, options) {
13
- const { _maxDimensions = 4 } = options?.shp || {};
14
- let offset = 0;
15
- const type = view.getInt32(offset, LITTLE_ENDIAN);
16
- offset += Int32Array.BYTES_PER_ELEMENT;
17
- switch (type) {
18
- case 0:
19
- // Null Shape
20
- return parseNull();
21
- case 1:
22
- // Point
23
- return parsePoint(view, offset, Math.min(2, _maxDimensions));
24
- case 3:
25
- // PolyLine
26
- return parsePoly(view, offset, Math.min(2, _maxDimensions), 'LineString');
27
- case 5:
28
- // Polygon
29
- return parsePoly(view, offset, Math.min(2, _maxDimensions), 'Polygon');
30
- case 8:
31
- // MultiPoint
32
- return parseMultiPoint(view, offset, Math.min(2, _maxDimensions));
33
- // GeometryZ can have 3 or 4 dimensions, since the M is not required to
34
- // exist
35
- case 11:
36
- // PointZ
37
- return parsePoint(view, offset, Math.min(4, _maxDimensions));
38
- case 13:
39
- // PolyLineZ
40
- return parsePoly(view, offset, Math.min(4, _maxDimensions), 'LineString');
41
- case 15:
42
- // PolygonZ
43
- return parsePoly(view, offset, Math.min(4, _maxDimensions), 'Polygon');
44
- case 18:
45
- // MultiPointZ
46
- return parseMultiPoint(view, offset, Math.min(4, _maxDimensions));
47
- case 21:
48
- // PointM
49
- return parsePoint(view, offset, Math.min(3, _maxDimensions));
50
- case 23:
51
- // PolyLineM
52
- return parsePoly(view, offset, Math.min(3, _maxDimensions), 'LineString');
53
- case 25:
54
- // PolygonM
55
- return parsePoly(view, offset, Math.min(3, _maxDimensions), 'Polygon');
56
- case 28:
57
- // MultiPointM
58
- return parseMultiPoint(view, offset, Math.min(3, _maxDimensions));
59
- default:
60
- throw new Error(`unsupported shape type: ${type}`);
61
- }
62
- }
63
- exports.parseRecord = parseRecord;
64
- // TODO handle null
65
- /**
66
- * Parse Null geometry
67
- *
68
- * @return null
69
- */
70
- function parseNull() {
71
- return null;
72
- }
73
- /**
74
- * Parse point geometry
75
- *
76
- * @param view Geometry data
77
- * @param offset Offset in view
78
- * @param dim Dimension size
79
- */
80
- function parsePoint(view, offset, dim) {
81
- let positions;
82
- [positions, offset] = parsePositions(view, offset, 1, dim);
83
- return {
84
- positions: { value: positions, size: dim },
85
- type: 'Point'
86
- };
87
- }
88
- /**
89
- * Parse MultiPoint geometry
90
- *
91
- * @param view Geometry data
92
- * @param offset Offset in view
93
- * @param dim Input dimension
94
- * @return Binary geometry object
95
- */
96
- function parseMultiPoint(view, offset, dim) {
97
- // skip parsing box
98
- offset += 4 * Float64Array.BYTES_PER_ELEMENT;
99
- const nPoints = view.getInt32(offset, LITTLE_ENDIAN);
100
- offset += Int32Array.BYTES_PER_ELEMENT;
101
- let xyPositions = null;
102
- let mPositions = null;
103
- let zPositions = null;
104
- [xyPositions, offset] = parsePositions(view, offset, nPoints, 2);
105
- // Parse Z coordinates
106
- if (dim === 4) {
107
- // skip parsing range
108
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
109
- [zPositions, offset] = parsePositions(view, offset, nPoints, 1);
110
- }
111
- // Parse M coordinates
112
- if (dim >= 3) {
113
- // skip parsing range
114
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
115
- [mPositions, offset] = parsePositions(view, offset, nPoints, 1);
116
- }
117
- const positions = concatPositions(xyPositions, mPositions, zPositions);
118
- return {
119
- positions: { value: positions, size: dim },
120
- type: 'Point'
121
- };
122
- }
123
- /**
124
- * Polygon and PolyLine parsing
125
- *
126
- * @param view Geometry data
127
- * @param offset Offset in view
128
- * @param dim Input dimension
129
- * @param type Either 'Polygon' or 'Polyline'
130
- * @return Binary geometry object
131
- */
132
- // eslint-disable-next-line max-statements
133
- function parsePoly(view, offset, dim, type) {
134
- // skip parsing bounding box
135
- offset += 4 * Float64Array.BYTES_PER_ELEMENT;
136
- const nParts = view.getInt32(offset, LITTLE_ENDIAN);
137
- offset += Int32Array.BYTES_PER_ELEMENT;
138
- const nPoints = view.getInt32(offset, LITTLE_ENDIAN);
139
- offset += Int32Array.BYTES_PER_ELEMENT;
140
- // Create longer indices array by 1 because output format is expected to
141
- // include the last index as the total number of positions
142
- const bufferOffset = view.byteOffset + offset;
143
- const bufferLength = nParts * Int32Array.BYTES_PER_ELEMENT;
144
- const ringIndices = new Int32Array(nParts + 1);
145
- ringIndices.set(new Int32Array(view.buffer.slice(bufferOffset, bufferOffset + bufferLength)));
146
- ringIndices[nParts] = nPoints;
147
- offset += nParts * Int32Array.BYTES_PER_ELEMENT;
148
- let xyPositions = null;
149
- let mPositions = null;
150
- let zPositions = null;
151
- [xyPositions, offset] = parsePositions(view, offset, nPoints, 2);
152
- // Parse Z coordinates
153
- if (dim === 4) {
154
- // skip parsing range
155
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
156
- [zPositions, offset] = parsePositions(view, offset, nPoints, 1);
157
- }
158
- // Parse M coordinates
159
- if (dim >= 3) {
160
- // skip parsing range
161
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
162
- [mPositions, offset] = parsePositions(view, offset, nPoints, 1);
163
- }
164
- const positions = concatPositions(xyPositions, mPositions, zPositions);
165
- // parsePoly only accepts type = LineString or Polygon
166
- if (type === 'LineString') {
167
- return {
168
- type,
169
- positions: { value: positions, size: dim },
170
- pathIndices: { value: ringIndices, size: 1 }
171
- };
172
- }
173
- // for every ring, determine sign of polygon
174
- // Use only 2D positions for ring calc
175
- const polygonIndices = [];
176
- for (let i = 1; i < ringIndices.length; i++) {
177
- const startRingIndex = ringIndices[i - 1];
178
- const endRingIndex = ringIndices[i];
179
- // @ts-ignore
180
- const ring = xyPositions.subarray(startRingIndex * 2, endRingIndex * 2);
181
- const sign = getWindingDirection(ring);
182
- // A positive sign implies clockwise
183
- // A clockwise ring is a filled ring
184
- if (sign > 0) {
185
- polygonIndices.push(startRingIndex);
186
- }
187
- }
188
- polygonIndices.push(nPoints);
189
- return {
190
- type,
191
- positions: { value: positions, size: dim },
192
- primitivePolygonIndices: { value: ringIndices, size: 1 },
193
- // TODO: Dynamically choose Uint32Array over Uint16Array only when
194
- // necessary. I believe the implementation requires nPoints to be the
195
- // largest value in the array, so you should be able to use Uint32Array only
196
- // when nPoints > 65535.
197
- polygonIndices: { value: new Uint32Array(polygonIndices), size: 1 }
198
- };
199
- }
200
- /**
201
- * Parse a contiguous block of positions into a Float64Array
202
- *
203
- * @param view Geometry data
204
- * @param offset Offset in view
205
- * @param nPoints Number of points
206
- * @param dim Input dimension
207
- * @return Data and offset
208
- */
209
- function parsePositions(view, offset, nPoints, dim) {
210
- const bufferOffset = view.byteOffset + offset;
211
- const bufferLength = nPoints * dim * Float64Array.BYTES_PER_ELEMENT;
212
- return [
213
- new Float64Array(view.buffer.slice(bufferOffset, bufferOffset + bufferLength)),
214
- offset + bufferLength
215
- ];
216
- }
217
- /**
218
- * Concatenate and interleave positions arrays
219
- * xy positions are interleaved; mPositions, zPositions are their own arrays
220
- *
221
- * @param xyPositions 2d positions
222
- * @param mPositions M positions
223
- * @param zPositions Z positions
224
- * @return Combined interleaved positions
225
- */
226
- // eslint-disable-next-line complexity
227
- function concatPositions(xyPositions, mPositions, zPositions) {
228
- if (!(mPositions || zPositions)) {
229
- return xyPositions;
230
- }
231
- let arrayLength = xyPositions.length;
232
- let nDim = 2;
233
- if (zPositions && zPositions.length) {
234
- arrayLength += zPositions.length;
235
- nDim++;
236
- }
237
- if (mPositions && mPositions.length) {
238
- arrayLength += mPositions.length;
239
- nDim++;
240
- }
241
- const positions = new Float64Array(arrayLength);
242
- for (let i = 0; i < xyPositions.length / 2; i++) {
243
- positions[nDim * i] = xyPositions[i * 2];
244
- positions[nDim * i + 1] = xyPositions[i * 2 + 1];
245
- }
246
- if (zPositions && zPositions.length) {
247
- for (let i = 0; i < zPositions.length; i++) {
248
- // If Z coordinates exist; used as third coord in positions array
249
- positions[nDim * i + 2] = zPositions[i];
250
- }
251
- }
252
- if (mPositions && mPositions.length) {
253
- for (let i = 0; i < mPositions.length; i++) {
254
- // M is always last, either 3rd or 4th depending on if Z exists
255
- positions[nDim * i + (nDim - 1)] = mPositions[i];
256
- }
257
- }
258
- return positions;
259
- }
260
- /**
261
- * Returns the direction of the polygon path
262
- * A positive number is clockwise.
263
- * A negative number is counter clockwise.
264
- *
265
- * @param positions
266
- * @return Sign of polygon ring
267
- */
268
- function getWindingDirection(positions) {
269
- return Math.sign(getSignedArea(positions));
270
- }
271
- /**
272
- * Get signed area of flat typed array of 2d positions
273
- *
274
- * @param positions
275
- * @return Signed area of polygon ring
276
- */
277
- function getSignedArea(positions) {
278
- let area = 0;
279
- // Rings are closed according to shapefile spec
280
- const nCoords = positions.length / 2 - 1;
281
- for (let i = 0; i < nCoords; i++) {
282
- area +=
283
- (positions[i * 2] + positions[(i + 1) * 2]) *
284
- (positions[i * 2 + 1] - positions[(i + 1) * 2 + 1]);
285
- }
286
- return area / 2;
287
- }
@@ -1,43 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseSHPHeader = void 0;
4
- const LITTLE_ENDIAN = true;
5
- const BIG_ENDIAN = false;
6
- const SHP_MAGIC_NUMBER = 0x0000270a;
7
- /**
8
- * Extract the binary header
9
- * Note: Also used by SHX
10
- * @param headerView
11
- * @returns SHPHeader
12
- */
13
- function parseSHPHeader(headerView) {
14
- // Note: The SHP format switches endianness between fields!
15
- // https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
16
- const header = {
17
- magic: headerView.getInt32(0, BIG_ENDIAN),
18
- // Length is stored as # of 2-byte words; multiply by 2 to get # of bytes
19
- length: headerView.getInt32(24, BIG_ENDIAN) * 2,
20
- version: headerView.getInt32(28, LITTLE_ENDIAN),
21
- type: headerView.getInt32(32, LITTLE_ENDIAN),
22
- bbox: {
23
- minX: headerView.getFloat64(36, LITTLE_ENDIAN),
24
- minY: headerView.getFloat64(44, LITTLE_ENDIAN),
25
- minZ: headerView.getFloat64(68, LITTLE_ENDIAN),
26
- minM: headerView.getFloat64(84, LITTLE_ENDIAN),
27
- maxX: headerView.getFloat64(52, LITTLE_ENDIAN),
28
- maxY: headerView.getFloat64(60, LITTLE_ENDIAN),
29
- maxZ: headerView.getFloat64(76, LITTLE_ENDIAN),
30
- maxM: headerView.getFloat64(92, LITTLE_ENDIAN)
31
- }
32
- };
33
- if (header.magic !== SHP_MAGIC_NUMBER) {
34
- // eslint-disable-next-line
35
- console.error(`SHP file: bad magic number ${header.magic}`);
36
- }
37
- if (header.version !== 1000) {
38
- // eslint-disable-next-line
39
- console.error(`SHP file: bad version ${header.version}`);
40
- }
41
- return header;
42
- }
43
- exports.parseSHPHeader = parseSHPHeader;