ol-load-geopackage 2.0.1 → 2.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.
package/API.md CHANGED
@@ -14,7 +14,10 @@ Parameters:
14
14
 
15
15
  - string `sqlJsWasmDir` (optional): URL or path relative to root of folder containing sql-wasm.wasm file. Default value is root folder.
16
16
 
17
- (No return value)
17
+ Returns a Promise which delivers:
18
+ - WebAssembly: sql.js SQLITE database access library
19
+
20
+ Note that unless you require access to sql.js outside ol-load-geopackage, then the returned promise can be ignored; [loadGpkg()](#loadgpkggpkgfile-displayprojection) will wait if necessary and handle any errors loading the WASM file. The only other reason to monitor the returned promise is if you are unlikely to invoke loadGpkg() for a long time and want to ensure the WASM has been successfully loaded.
18
21
 
19
22
  If you want to load the associated WebAssembly binary (sql-wasm.wasm) from an external Content Delivery Network (CDN) then it is important that you load the WASM file that matches the version of the sql.js module being imported by ol-load-geopackage. Thus you will need to incorporate the _sql_js_version_ constant in the calling parameter, for example (from the proj4_example):
20
23
 
@@ -29,8 +32,7 @@ initSqlJsWasm(sqlJsWasmDir);
29
32
  Begin asynchronous loading of a single OGC GeoPackage, then extract vector data tables into OpenLayers Vector Sources, transforming the data (if necessary) to match the specified display projection. If a "layer_styles" table is found (as generated by QGIS [Package Layers](https://docs.qgis.org/3.16/en/docs/user_manual/processing_algs/qgis/database.html#package-layers) Processing Toolbox command), it will extract the constituent SLD XML styling data associated with each vector data table.
30
33
 
31
34
  Parameters:
32
-
33
- - string `gpkgFile`: OGC GeoPackage file URL or path relative to root
35
+ - string|File|Blob|URL `gpkgFile`: OGC GeoPackage URL string or File/URL object (URL can be path relative to document's base URI)
34
36
  - string `displayProjection`: Map display projection for output sources (e.g. 'EPSG:3857'). Note that projections not built in to OpenLayers must be defined before calling the function. This is most easily done using the Proj4JS library - see Proj4 [Example](README.md#examples-in-github-repository).
35
37
 
36
38
  Returns a Promise which delivers an array of 2 objects:
@@ -55,10 +57,16 @@ Notes:
55
57
  3. In the output GeoPackage from QGIS [Package Layers](https://docs.qgis.org/3.16/en/docs/user_manual/processing_algs/qgis/database.html#package-layers) the "table name" used for each vector data table will be exactly the same as the "layer name" used to index the SLD style strings in the "layer_styles" table.
56
58
 
57
59
  Errors thrown on these events:
58
- - Unable to load WebAssembly binary (sql-wasm.wasm)
59
- - Unable to load requested OGC GeoPackage
60
- - Missing requested display projection
60
+ - SQL WASM loading not previously started, i.e. mmissing a preceding call to initSqlJsWasm()
61
+ - ol/proj is missing the requested display projection (can be added beforehand using ol/proj/proj4.js)
62
+
63
+ Promise rejected on these events:
64
+ - Unable to load SQLite JS WebAssembly binary (sql-wasm.wasm)
65
+ - `gpkgFile` parameter not of type URL string or URL/File/Blob object
66
+ - Unable to load requested GeoPackage
61
67
  - Missing a data projection (from any of Geopackage tables)
68
+ - Failure trying to extract feature tables from GeoPackage
69
+ - Invalid geometry envelope size flag in a GeoPackage table feature
62
70
 
63
71
 
64
72
  ## sql_js_version
package/README.md CHANGED
@@ -37,7 +37,7 @@ Use Node.js to install the NPM package: [ol-load-geopackage](https://www.npmjs.c
37
37
  npm install --save ol-load-geopackage
38
38
  ```
39
39
 
40
- After running npm install, the sql.js WebAssembly file (sql-wasm.wasm) will need to be copied from folder _node_modules/sql.js/dist/_ to a folder where the web page can load it from.
40
+ After running npm install, the sql.js WebAssembly file (sql-wasm.wasm) will need to be copied from folder _node_modules/sql.js/dist/_ to a folder where the web page can load it from (unless you plan to load it from a CDN).
41
41
 
42
42
  ## Basic usage
43
43
 
@@ -47,7 +47,12 @@ This package must be imported as a module - it is not designed to be loaded dire
47
47
  import { initSqlJsWasm, loadGpkg } from 'ol-load-geopackage';
48
48
 
49
49
  initSqlJsWasm('.');
50
- var gpkgPromise = loadGpkg(<gpkgFile>, <displayProjection>);
50
+ var gpkgPromise;
51
+ try {
52
+ gpkgPromise = loadGpkg(<gpkgFile>, <displayProjection>);
53
+ } catch (error) {
54
+ alert('loadGpkg() failed before Promise set-up:\n' + error);
55
+ }
51
56
  gpkgPromise
52
57
  .then(([dataFromGpkg, sldsFromGpkg]) => {
53
58
  for (var table in dataFromGpkg) {
@@ -59,7 +64,7 @@ gpkgPromise
59
64
  // sldsFromGpkg[layerName]
60
65
  }
61
66
  })
62
- .catch(error => alert('ol-load-geopackage error: ' + error));
67
+ .catch(error => alert('ol-load-geopackage error:\n' + error));
63
68
  ```
64
69
 
65
70
  Note that the _initSqlJsWasm()_ statement will start the asynchronous loading of the required sql.js WebAssembly binary file sql-wasm.wasm (from the current folder in this case), so is best placed early in the code.
@@ -116,7 +121,7 @@ npm run-script dev
116
121
  The JavaScript module has 3 exported functions/constants which are described in the separate [API Specification](API.md):
117
122
 
118
123
  - [initSqlJsWasm()](API.md#initsqljswasmsqljswasmdir) - Initialisation: start loading of required sql.js WASM file
119
- - [loadGpkg()](API.md#loadgpkggpkgfile-displayprojection) - start loading and data extraction of GeoPackage
124
+ - [loadGpkg()](API.md#loadgpkggpkgfile-displayprojection) - start asynchronous loading and data extraction of GeoPackage
120
125
  - [sql_js_version](API.md#sql_js_version) - NPM version number of underlying sql.js module
121
126
 
122
127
  ## Migrating from ol-load-geopackage v1.x.x
@@ -7,7 +7,7 @@
7
7
  * Both Sources and SLDs are returned in objects with table names used as keys.
8
8
  */
9
9
 
10
- import initSqlJs from "sql.js";
10
+ import initSqlJs from 'sql.js';
11
11
  import {get as ol_proj_get} from 'ol/proj.js';
12
12
  import ol_source_Vector from 'ol/source/Vector.js';
13
13
  import ol_format_WKB from 'ol/format/WKB.js';
@@ -25,13 +25,18 @@ var promiseSqlWasmLoaded;
25
25
  export { initSqlJsWasm, loadGpkg, sql_js_version };
26
26
 
27
27
  /**
28
- * Initialisation: start asynchronous loading of WASM file required by sql.js
28
+ * Initialisation: start asynchronous loading of WASM file required by sql.js.
29
+ * Note that unless you require access to sql.js outside ol-load-geopackage,
30
+ * then the returned promise can be ignored; loadGpkg() will wait if necessary
31
+ * and handle any errors loading the WASM file.
29
32
  * @param {string} sqlJsWasmDir - URL of folder containing sql-wasm.wasm file to load for sql.js
33
+ * @returns {Promise<WebAssembly>} Promise which delivers:
34
+ * sql.js SQLITE database access library WebAssembly
30
35
  */
31
36
  function initSqlJsWasm(sqlJsWasmDir) {
32
37
  // If the WASM file location isn't specified look for it in the root folder
33
38
  if (sqlJsWasmDir === undefined) {
34
- sqlJsWasmDir = "";
39
+ sqlJsWasmDir = '';
35
40
  }
36
41
 
37
42
  // For reading OGC GeoPackage files, use the sql.js SQLite reader;
@@ -41,44 +46,62 @@ function initSqlJsWasm(sqlJsWasmDir) {
41
46
  });
42
47
  promiseSqlWasmLoaded
43
48
  .catch(error => {
44
- // Only need report error here - any later calls to loadGpkg() will throw error
45
- console.error(`initSqlJsWasm() unable to load SQLite JS binary (sql-wasm.wasm) from folder:\n` +
46
- `${sqlJsWasmDir}/\n` +
47
- `[sql.js error message]: ${error}`);
49
+ // Only reporting error to console here to simplify error handling;
50
+ // Error will be dealt with on later call(s) to loadGpkg()
51
+ console.error('initSqlJsWasm() unable to load SQLite JS binary ' +
52
+ `(sql-wasm.wasm) from URL folder:\n` +
53
+ ` ${sqlJsWasmDir}/\n` +
54
+ error);
48
55
  });
56
+
57
+ return promiseSqlWasmLoaded;
49
58
  }
50
59
 
51
60
  /**
52
61
  * Wrapper to load a single OGC GeoPackage
53
- * @param {string} gpkgFile - OGC GeoPackage file path
62
+ * @param {(string|File|Blob|URL)} gpkgFile - OGC GeoPackage URL string or File/URL object
54
63
  * @param {string} displayProjection - map display projection (e.g. EPSG:3857)
55
- * @returns {Promise} Promise which delivers array of 2 objects:
64
+ * @returns {Promise<[Object, Object]>} Promise delivering array of 2 objects:
56
65
  * data tables (OpenLayers vector sources, indexed by table name),
57
66
  * styles (SLD layer_styles XML strings, indexed by layer name)
67
+ * @throws {Error} If SQL WASM loading not previously started
68
+ * @throws {Error} If ol/proj is missing the requested display projection
58
69
  */
59
70
  function loadGpkg(gpkgFile, displayProjection) {
60
71
 
61
- // Start OGC GeoPackage load and processing to extract data/SLDs
62
- var gpkgReadPromise = readRawGpkg(gpkgFile);
72
+ // Check SQL WASM loading was initiated
73
+ if (promiseSqlWasmLoaded === undefined) {
74
+ throw new Error('SQL WASM loading has not started; ' +
75
+ 'did you forget to run initSqlJsWasm() first?');
76
+ }
63
77
 
64
78
  // Check if we have a definition for the display projection (SRS)
65
79
  if (!ol_proj_get(displayProjection)) {
66
- throw new Error("Missing requested display projection [" +
80
+ throw new Error('Missing requested display projection [' +
67
81
  displayProjection +
68
82
  '] - can be added beforehand with ol/proj/proj4');
69
83
  }
70
84
 
85
+ // Start OGC GeoPackage load and processing to extract data/SLDs
86
+ var gpkgReadPromise = readRawGpkg(gpkgFile);
87
+
71
88
  return Promise.allSettled([promiseSqlWasmLoaded, gpkgReadPromise])
72
89
  .then((results) => {
73
90
  if (results[0].status === 'rejected') {
74
- throw new Error('Unable to load SQLite JS binary (sql-wasm.wasm)');
91
+ // Throw (initSqlJs() failure) will convert to rejected promise
92
+ throw new Error(
93
+ 'Unable to load SQLite JS binary (sql-wasm.wasm).\n' +
94
+ results[0].reason);
75
95
  }
76
96
  if (results[1].status === 'rejected') {
77
- throw new Error(`Unable to read raw GeoPackage data from file: ${gpkgFile}`);
97
+ // Propagate exact Error object from readRawGpkg().
98
+ // Throw will convert to rejected promise
99
+ throw results[1].reason;
78
100
  }
79
101
  const sqlWasm = results[0].value;
80
- const gpkgArrayBuffer = results[1].value;
81
- return processGpkgData(gpkgFile, gpkgArrayBuffer, sqlWasm, displayProjection);
102
+ const gpkgByteArray = results[1].value;
103
+ const gpkgFileName = (gpkgFile instanceof File) ? gpkgFile.name : gpkgFile.toString();
104
+ return processGpkgData(gpkgFileName, gpkgByteArray, sqlWasm, displayProjection);
82
105
  }
83
106
  );
84
107
  }
@@ -87,44 +110,60 @@ function loadGpkg(gpkgFile, displayProjection) {
87
110
 
88
111
  /**
89
112
  * Read raw data from source for a single OGC GeoPackage
90
- * @param {string} gpkgFile - OGC GeoPackage file path
91
- * @returns {Promise} Promise with Gpkg contents in ArrayBuffer format
113
+ * @param {(string|File|Blob|URL)} input - OGC GeoPackage URL string or File/URL object
114
+ * @returns {Promise<Uint8Array>} Promise with Gpkg contents in byte array format
92
115
  */
93
- function readRawGpkg(gpkgFile) {
94
- return new Promise(function(succeed, fail) {
95
- var oReq = new XMLHttpRequest();
96
- oReq.responseType = "arraybuffer";
97
- oReq.onreadystatechange = function() {
116
+ async function readRawGpkg(input) {
98
117
 
99
- // When request finished and response is ready
100
- if (this.readyState == 4) {
101
- var gpkgArrayBuffer = this.response;
102
- if (this.status === 200 && gpkgArrayBuffer) {
103
- succeed(gpkgArrayBuffer);
104
- } else {
105
- fail(new Error(
106
- 'Requested GPKG file could not be loaded: ' +
107
- gpkgFile));
108
- }
109
- }
110
- };
111
- oReq.open("GET", gpkgFile);
112
- oReq.send();
113
- });
118
+ // Fetch() or File/Blob object (both have the equivalent methods we need)
119
+ let gpkgSource;
120
+
121
+ // File object is a specific type of Blob
122
+ if (input instanceof Blob) {
123
+ gpkgSource = input;
124
+ } else if (typeof input === 'string' || input instanceof URL) {
125
+ const response = await fetch(input);
126
+ if (!response.ok) {
127
+ // Throw will convert to rejected promise (as an async function)
128
+ throw new Error('GPKG file could not be loaded from URL:\n' +
129
+ ` ${input}\n` +
130
+ `Response: (${response.status}) ${response.statusText}`);
131
+ }
132
+ gpkgSource = response;
133
+ } else {
134
+ // Throw will convert to rejected promise (as an async function)
135
+ throw new TypeError('Input must be URL string or URL/File/Blob object');
136
+ }
137
+
138
+ try {
139
+ // Use .bytes() method if available (most browsers since Jan 2025)
140
+ if (typeof gpkgSource.bytes === 'function') {
141
+ return await gpkgSource.bytes();
142
+ }
143
+
144
+ // Fallback approach: Convert ArrayBuffer to Uint8Array
145
+ //console.log('readRawGpkg(): using fallback .arrayBuffer() + Uint8Array() methods');
146
+ const buffer = await gpkgSource.arrayBuffer();
147
+ return new Uint8Array(buffer);
148
+ } catch (error) {
149
+ // Throw will convert to rejected promise (as an async function)
150
+ throw new Error('Requested GPKG file could not be loaded.\n' + error);
151
+ }
114
152
  }
115
153
 
116
154
  /**
117
- * Process OGC GeoPackage (SQLite database) once loaded
118
- * @param {*} loadedGpkgFile - name of GeoPackage file (for diagnostics only)
119
- * @param {ArrayBuffer} gpkgArrayBuffer - ArrayBuffer containing Gpkg data read
155
+ * Process OGC GeoPackage (based on SQLite database) once loaded
156
+ * @param {string} loadedGpkgFile - name of GeoPackage file (for diagnostics only)
157
+ * @param {Uint8Array} gpkgByteArray - Byte Array containing Gpkg data read
120
158
  * @param {WebAssembly} sqlWasm - sql.js SQLITE database access library
121
159
  * @param {string} displayProjection - map display projection (e.g. EPSG:3857)
122
- * @returns {object[]} array of 2 objects: [<data tables>, <slds>]
123
- * <data tables>: OpenLayers vector sources, indexed by table name
124
- * <slds>: SLD XML strings, indexed by layer name
160
+ * @returns {[Object, Object]} Array of 2 objects:
161
+ * data tables (OpenLayers vector sources, indexed by table name),
162
+ * styles (SLD layer_styles XML strings, indexed by layer name)
163
+ * @throws {Error} If unable to extract feature tables from OGC GeoPackage file
164
+ * @throws {Error} If ol/proj is missing required projection for a data table
125
165
  */
126
- function processGpkgData(loadedGpkgFile, gpkgArrayBuffer, sqlWasm,
127
- displayProjection) {
166
+ function processGpkgData(loadedGpkgFile, gpkgByteArray, sqlWasm, displayProjection) {
128
167
  var db;
129
168
 
130
169
  // Data and associated SLD styles loaded both from GPKG
@@ -134,9 +173,6 @@ function processGpkgData(loadedGpkgFile, gpkgArrayBuffer, sqlWasm,
134
173
  // DEBUG: measure GPKG processing time
135
174
  //var startProcessing = Date.now();
136
175
 
137
- // Convert Array Buffer to Byte Array for SQLite
138
- var gpkgByteArray = new Uint8Array(gpkgArrayBuffer);
139
-
140
176
  try {
141
177
  db = new sqlWasm.Database(gpkgByteArray);
142
178
 
@@ -158,16 +194,16 @@ function processGpkgData(loadedGpkgFile, gpkgArrayBuffer, sqlWasm,
158
194
  while (stmt.step()) {
159
195
  let row = stmt.get();
160
196
  featureTableNames.push({
161
- "table_name": row[0],
162
- "srs_id": row[1].toString(),
163
- "geometry_column_name": row[2]
197
+ 'table_name': row[0],
198
+ 'srs_id': row[1].toString(),
199
+ 'geometry_column_name': row[2]
164
200
  });
165
201
  }
166
202
  }
167
203
  catch (err) {
168
204
  throw new Error(
169
- 'Unable to extract feature tables from OGC GeoPackage file "' +
170
- loadedGpkgFile + '":\n' + err);
205
+ 'Unable to extract feature tables from OGC GeoPackage file.\n' +
206
+ err);
171
207
  }
172
208
 
173
209
  // Extract SLD styles for each layer (if styles included in the gpkg)
@@ -177,7 +213,7 @@ function processGpkgData(loadedGpkgFile, gpkgArrayBuffer, sqlWasm,
177
213
  WHERE gpkg_contents.table_name='layer_styles'
178
214
  `);
179
215
  if (stmt.step()) {
180
- stmt = db.prepare("SELECT f_table_name,styleSLD FROM layer_styles");
216
+ stmt = db.prepare('SELECT f_table_name,styleSLD FROM layer_styles');
181
217
  while (stmt.step()) {
182
218
  let row = stmt.get();
183
219
  sldsFromGpkg[row[0]] = row[1];
@@ -194,11 +230,12 @@ function processGpkgData(loadedGpkgFile, gpkgArrayBuffer, sqlWasm,
194
230
 
195
231
  // Check if we have a definition for the data projection (SRS)
196
232
  if (!ol_proj_get(tableDataProjection)) {
197
- throw new Error("Missing data projection [" +
233
+ throw new Error('Missing data projection [' +
198
234
  tableDataProjection + '] for table "' + table_name +
199
235
  '" - can be added beforehand with ol/proj/proj4');
200
236
  }
201
237
 
238
+ //console.log(`Extracting table "${table_name}" (SRS: ${tableDataProjection})`);
202
239
  stmt = db.prepare("SELECT * FROM '" + table_name + "'");
203
240
  let vectorSource = new ol_source_Vector();
204
241
  let geometry_column_name = table.geometry_column_name;
@@ -226,7 +263,7 @@ function processGpkgData(loadedGpkgFile, gpkgArrayBuffer, sqlWasm,
226
263
  }
227
264
 
228
265
  // For information only, save details of original projection (SRS)
229
- vectorSource.setProperties({"origProjection": tableDataProjection});
266
+ vectorSource.setProperties({'origProjection': tableDataProjection});
230
267
  dataFromGpkg[table_name] = vectorSource;
231
268
  }
232
269
  /*
@@ -241,8 +278,9 @@ function processGpkgData(loadedGpkgFile, gpkgArrayBuffer, sqlWasm,
241
278
  /**
242
279
  * Extract (SRS ID &) WKB from an OGC GeoPackage feature
243
280
  * (i.e. strip off the variable length header)
244
- * @param {object} gpkgBinGeom feature geometry property (includes header)
245
- * @returns feature geometry in WKB (Well Known Binary) format
281
+ * @param {Uint8Array} gpkgBinGeom - feature geometry property (includes header)
282
+ * @returns {Uint8Array} feature geometry in WKB (Well Known Binary) format
283
+ * @throws {Error} If invalid geometry envelope size flag in GeoPackage
246
284
  */
247
285
  function parseGpkgGeom(gpkgBinGeom) {
248
286
  var flags = gpkgBinGeom[3];
@@ -263,7 +301,7 @@ function parseGpkgGeom(gpkgBinGeom) {
263
301
  envelopeSize = 64;
264
302
  break;
265
303
  default:
266
- throw new Error("Invalid geometry envelope size flag in GeoPackage");
304
+ throw new Error('Invalid geometry envelope size flag in GeoPackage');
267
305
  }
268
306
  /*
269
307
  // Extract SRS (EPSG code)
@@ -281,11 +319,11 @@ function parseGpkgGeom(gpkgBinGeom) {
281
319
  // DEBUG: display other properties of the feature
282
320
  console.log('gpkgBinGeom Header: ' + (littleEndian ? 'Little' : 'Big')
283
321
  + ' Endian');
284
- console.log("gpkgBinGeom Magic: 0x${gpkgBinGeom[0].toString(16)}${gpkgBinGeom[1].toString(16)}");
285
- console.log("gpkgBinGeom Version:", gpkgBinGeom[2]);
286
- console.log("gpkgBinGeom Flags:", flags);
287
- console.log("gpkgBinGeom srs_id:", srsId);
288
- console.log("gpkgBinGeom envelope size (bytes):", envelopeSize);
322
+ console.log('gpkgBinGeom Magic: 0x${gpkgBinGeom[0].toString(16)}${gpkgBinGeom[1].toString(16)}');
323
+ console.log('gpkgBinGeom Version:', gpkgBinGeom[2]);
324
+ console.log('gpkgBinGeom Flags:', flags);
325
+ console.log('gpkgBinGeom srs_id:', srsId);
326
+ console.log('gpkgBinGeom envelope size (bytes):', envelopeSize);
289
327
  */
290
328
  // Extract WKB which starts after variable-size "envelope" field
291
329
  var wkbOffset = envelopeSize + 8;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ol-load-geopackage",
3
- "version": "2.0.1",
3
+ "version": "2.2.0",
4
4
  "description": "Loads OGC GeoPackage vector data tables into OpenLayers Vector Sources",
5
5
  "files": [
6
6
  "dist/",
@@ -24,8 +24,7 @@
24
24
  "license": "ISC",
25
25
  "dependencies": {
26
26
  "ol": ">=6.7.0",
27
- "sql.js": "^1.6.1",
28
- "util": "^0.12.4"
27
+ "sql.js": "^1.6.1"
29
28
  },
30
29
  "repository": {
31
30
  "type": "git",