diff --git a/package-lock.json b/package-lock.json index d565d9e..a2d8c4c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,12 +8,15 @@ "name": "@earthyscience/netcdf4-wasm", "version": "0.3.0", "license": "MIT", + "dependencies": { + "@types/emscripten": "^1.41.6" + }, "devDependencies": { "@biomejs/biome": "^2.6.4", "@types/node": "^22.20.5", "@vitest/coverage-v8": "^5.0.5", - "cpx2": "^8.0.0", - "rimraf": "^6.1.2", + "cpx2": "^9.0.0", + "rimraf": "^6.1.3", "typescript": "^5.0.0", "vitest": "^5.0.5" } @@ -642,6 +645,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/emscripten": { + "version": "1.41.6", + "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.6.tgz", + "integrity": "sha512-uN+9i8bFT5CUcZfyIEYDrSueACEyKGbUs5kC/72DGlZZoinh84sJfVV0i8UOJD1asdzkvLPBRrKs41kZ8MdEXg==", + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", @@ -805,9 +814,9 @@ } }, "node_modules/cpx2": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/cpx2/-/cpx2-8.0.2.tgz", - "integrity": "sha512-exLFEIh8XgWthEtrEq8hs+S6jxM5ZHpjQnRH6D7VU+2uAYS3amLSVOUSuirfx3HeN7WBCq+xFygHpt7l+gQtUA==", + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/cpx2/-/cpx2-9.0.3.tgz", + "integrity": "sha512-SHeJspK34eVoLWuCrBW6YdcflnZwJifgADJNRkitsuZN2bi4+iby4slavs1qANeNiiZnIWRFG4vNcHp8UHrE5g==", "dev": true, "license": "MIT", "dependencies": { @@ -817,7 +826,6 @@ "ignore": "^7.0.5", "minimatch": "^10.0.1", "p-map": "^7.0.0", - "resolve": "^1.12.0", "shell-quote": "^1.8.0", "subarg": "^1.0.0" }, @@ -825,7 +833,7 @@ "cpx": "bin/index.js" }, "engines": { - "node": "^20.0.0 || >=22.0.0", + "node": "^22.0.0 || >=24.0.0", "npm": ">=10" } }, @@ -853,16 +861,6 @@ "node": ">=8" } }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -931,16 +929,6 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/glob": { "version": "13.0.6", "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", @@ -971,19 +959,6 @@ "node": ">= 0.10" } }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/ignore": { "version": "7.0.14", "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz", @@ -994,22 +969,6 @@ "node": ">= 4" } }, - "node_modules/is-core-module": { - "version": "2.17.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", - "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/js-tokens": { "version": "10.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", @@ -1302,6 +1261,16 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/magic-string": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", @@ -1414,13 +1383,6 @@ "dev": true, "license": "BlueOak-1.0.0" }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, "node_modules/path-scurry": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", @@ -1438,16 +1400,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/path-scurry/node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1499,28 +1451,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/resolve": { - "version": "1.22.13", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz", - "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "is-core-module": "^2.17.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/rimraf": { "version": "6.1.3", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", @@ -1616,23 +1546,10 @@ "minimist": "^1.1.0" } }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/tinybench": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", - "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index a836798..ecdf2ee 100644 --- a/package.json +++ b/package.json @@ -52,12 +52,15 @@ } ], "license": "MIT", + "dependencies": { + "@types/emscripten": "^1.41.6" + }, "devDependencies": { "@biomejs/biome": "^2.6.4", "@types/node": "^22.20.5", "@vitest/coverage-v8": "^5.0.5", - "cpx2": "^8.0.0", - "rimraf": "^6.1.2", + "cpx2": "^9.0.0", + "rimraf": "^6.1.3", "typescript": "^5.0.0", "vitest": "^5.0.5" }, diff --git a/src/constants.ts b/src/constants.ts index a77e08a..8307cdc 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -174,7 +174,16 @@ export const NC_CONSTANTS = { // Shuffle filter NC_NOSHUFFLE: 0, NC_SHUFFLE: 1, -}; +} as const; + +// netcdf4-python modes: whether they create the file, and the nc_open/nc_create flags +export const FILE_MODES = { + r: { create: false, flags: NC_CONSTANTS.NC_NOWRITE }, + "r+": { create: false, flags: NC_CONSTANTS.NC_WRITE }, + a: { create: false, flags: NC_CONSTANTS.NC_WRITE }, + w: { create: true, flags: NC_CONSTANTS.NC_CLOBBER }, + "w-": { create: true, flags: NC_CONSTANTS.NC_NOCLOBBER }, +} as const; // Data type mapping from string names to NetCDF constants export const DATA_TYPE_MAP: { [key: string]: number } = { @@ -245,24 +254,3 @@ export const DATA_TYPE_SIZE: { [key: number]: number } = { 11: 8, // NC_UINT64 12: 0, // NC_STRING (variable length) }; - -// Human-readable type names -export const TYPE_NAMES: { [key: number]: string } = { - 0: "NAT", - 1: "byte", - 2: "char", - 3: "short", - 4: "int", - 5: "float", - 6: "double", - 7: "ubyte", - 8: "ushort", - 9: "uint", - 10: "int64", - 11: "uint64", - 12: "string", - 13: "vlen", - 14: "opaque", - 15: "enum", - 16: "compound", -}; diff --git a/src/errors.ts b/src/errors.ts new file mode 100644 index 0000000..8ae22d3 --- /dev/null +++ b/src/errors.ts @@ -0,0 +1,17 @@ +// Error handling helpers + +/** Turn a caught value, which can be anything that was thrown, into an Error. */ +export function toError(err: unknown): Error { + if (err instanceof Error) { + return err; + } + if ( + typeof err === "object" && + err !== null && + "message" in err && + typeof err.message === "string" + ) { + return new Error(err.message); + } + return new Error(String(err)); +} diff --git a/src/index.ts b/src/index.ts index 6d37429..15055e4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -30,12 +30,13 @@ import { NetCDF4 } from "./netcdf4.js"; import type { DatasetOptions, DatasetSource, + FileMode, RemoteDatasetOptions, } from "./types.js"; export async function Dataset( source: DatasetSource, - mode: string = "r", + mode: FileMode = "r", options: RemoteDatasetOptions = {}, ): Promise { // Type detection and routing @@ -61,7 +62,7 @@ export async function Dataset( // Legacy convenience functions for backward compatibility export async function DatasetFromBlob( blob: Blob, - mode: string = "r", + mode: FileMode = "r", options: DatasetOptions = {}, ): Promise { return await Dataset(blob, mode, options); @@ -69,7 +70,7 @@ export async function DatasetFromBlob( export async function DatasetFromArrayBuffer( buffer: ArrayBuffer, - mode: string = "r", + mode: FileMode = "r", options: DatasetOptions = {}, ): Promise { return await Dataset(buffer, mode, options); @@ -77,7 +78,7 @@ export async function DatasetFromArrayBuffer( export async function DatasetFromMemory( data: Uint8Array | ArrayBuffer, - mode: string = "r", + mode: FileMode = "r", options: DatasetOptions = {}, filename?: string, ): Promise { diff --git a/src/netcdf-getters.ts b/src/netcdf-getters.ts index caff05b..cc0ba1f 100644 --- a/src/netcdf-getters.ts +++ b/src/netcdf-getters.ts @@ -4,7 +4,7 @@ import { NC_CONSTANTS, } from "./constants.js"; import { type DimSelection, type ResolvedDim, resolveDim } from "./slice.js"; -import type { NetCDF4Module } from "./types.js"; +import type { AnyTypedArray, NetCDF4Module } from "./types.js"; export function getGroupVariables( module: NetCDF4Module, @@ -187,7 +187,7 @@ export function getAttributeValues( [NC_CONSTANTS.NC_UBYTE]: module.nc_get_att_uchar, [NC_CONSTANTS.NC_UINT]: module.nc_get_att_uint, [NC_CONSTANTS.NC_USHORT]: module.nc_get_att_ushort, - [NC_CONSTANTS.NC_LONGLONG]: module.nc_get_att_longlong, + [NC_CONSTANTS.NC_INT64]: module.nc_get_att_longlong, [NC_CONSTANTS.NC_UINT64]: module.nc_get_att_ulonglong, [NC_CONSTANTS.NC_STRING]: module.nc_get_att_string, }; @@ -595,18 +595,7 @@ export function getVariableArray( variable: number | string, groupPath?: string, options?: { convertEnumsToNames?: boolean }, -): - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array - | string[] { +): AnyTypedArray { const workingNcid = groupPath ? getGroupNCID(module, ncid, groupPath) : ncid; @@ -648,12 +637,8 @@ export function getVariableArray( module.nc_get_var_double(...args), [NC_CONSTANTS.NC_INT64]: (...args) => module.nc_get_var_longlong(...args), - [NC_CONSTANTS.NC_LONGLONG]: (...args) => - module.nc_get_var_longlong(...args), [NC_CONSTANTS.NC_UINT64]: (...args) => module.nc_get_var_ulonglong(...args), - [NC_CONSTANTS.NC_ULONGLONG]: (...args) => - module.nc_get_var_ulonglong(...args), [NC_CONSTANTS.NC_STRING]: (...args) => module.nc_get_var_string(...args), }; @@ -704,18 +689,7 @@ export function getSlicedVariableArray( count: number[], groupPath?: string, options?: { convertEnumsToNames?: boolean }, -): - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array - | string[] { +): AnyTypedArray { const workingNcid = groupPath ? getGroupNCID(module, ncid, groupPath) : ncid; @@ -802,19 +776,6 @@ export function getSlicedVariableArray( return arrayData.data; } -type AnyTypedArray = - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array - | string[]; - export function getVariableArrayWithSelection( module: NetCDF4Module, ncid: number, @@ -921,9 +882,7 @@ export function getVariableArrayWithSelection( [NC_CONSTANTS.NC_FLOAT]: () => new Float32Array(0), [NC_CONSTANTS.NC_DOUBLE]: () => new Float64Array(0), [NC_CONSTANTS.NC_INT64]: () => new BigInt64Array(0), - [NC_CONSTANTS.NC_LONGLONG]: () => new BigInt64Array(0), [NC_CONSTANTS.NC_UINT64]: () => new BigUint64Array(0), - [NC_CONSTANTS.NC_ULONGLONG]: () => new BigUint64Array(0), [NC_CONSTANTS.NC_STRING]: () => [], }; return (emptyReaders[arrayType] ?? (() => new Float64Array(0)))(); @@ -964,12 +923,8 @@ export function getVariableArrayWithSelection( module.nc_get_vars_double(...args), [NC_CONSTANTS.NC_INT64]: (...args) => module.nc_get_vars_longlong(...args), - [NC_CONSTANTS.NC_LONGLONG]: (...args) => - module.nc_get_vars_longlong(...args), [NC_CONSTANTS.NC_UINT64]: (...args) => module.nc_get_vars_ulonglong(...args), - [NC_CONSTANTS.NC_ULONGLONG]: (...args) => - module.nc_get_vars_ulonglong(...args), [NC_CONSTANTS.NC_STRING]: (...args) => module.nc_get_vars_string(...args), }; diff --git a/src/netcdf-worker.ts b/src/netcdf-worker.ts index 07afe2d..ef5e69f 100644 --- a/src/netcdf-worker.ts +++ b/src/netcdf-worker.ts @@ -1,3 +1,4 @@ +import { toError } from "./errors.js"; import { isOperationName, runOperation } from "./operations.js"; import { checkRangeSupport, @@ -75,10 +76,10 @@ self.onmessage = async (e: MessageEvent) => { }, mountPoint, ); - } catch (err: any) { + } catch (err) { console.warn( "Mount failed (might already be mounted):", - err.message, + toError(err).message, ); } @@ -99,9 +100,9 @@ self.onmessage = async (e: MessageEvent) => { const result = runOperation(mod, type, data.args); self.postMessage({ id, success: true, result }); - } catch (err: any) { + } catch (err) { // netCDF-C only sees EIO for a failed remote read; attach the actual cause - let message = err.message; + let message = toError(err).message; if (remoteFile?.lastError) { message += ` (${remoteFile.lastError.message})`; } diff --git a/src/netcdf4.ts b/src/netcdf4.ts index 7d13ac6..2f9bd4f 100644 --- a/src/netcdf4.ts +++ b/src/netcdf4.ts @@ -1,6 +1,7 @@ // Main NetCDF4 class implementation -import { NC_CONSTANTS } from "./constants.js"; +import { FILE_MODES, NC_CONSTANTS } from "./constants.js"; +import { toError } from "./errors.js"; import { Group } from "./group.js"; import { type OperationArgs, @@ -10,26 +11,40 @@ import { } from "./operations.js"; import type { DimSelection } from "./slice.js"; import type { + AnyTypedArray, DatasetOptions, + FileMode, MemoryDatasetSource, NetCDF4Module, + OpenMode, RemoteDatasetOptions, RemoteFileOptions, } from "./types.js"; import { WasmModuleLoader } from "./wasm-module.js"; +function isFileMode(mode: string): mode is FileMode { + return Object.hasOwn(FILE_MODES, mode); +} + +type WorkerSource = { + blob?: Blob; + url?: string; + remote?: RemoteFileOptions; + filename: string; +}; + +// Messages handled by netcdf-worker +type WorkerRequest = + | ({ type: "init" } & WorkerSource) + | { type: OperationName; args: OperationArgs }; + export class NetCDF4 extends Group { private module: NetCDF4Module | null = null; private initialized = false; private ncid: number = -1; private _isOpen = false; private memorySource?: MemoryDatasetSource; - private workerSource?: { - blob?: Blob; - url?: string; - remote?: RemoteFileOptions; - filename: string; - }; + private workerSource?: WorkerSource; private worker?: Worker; private workerReady?: Promise; // Set once the worker is terminated; later worker calls reject with it @@ -42,9 +57,10 @@ export class NetCDF4 extends Group { private mode: string = "r", private options: DatasetOptions = {}, ) { - super(null as any, "", -1); + // this can't be passed before super(), so it is set on the next line + super(null as unknown as NetCDF4, "", -1); // Set up self-reference for Group methods - (this as any).netcdf = this; + this.netcdf = this; } async initialize(): Promise { @@ -72,7 +88,7 @@ export class NetCDF4 extends Group { // Python-like factory method static async Dataset( filename: string | URL, - mode: string = "r", + mode: FileMode = "r", options: RemoteDatasetOptions = {}, ): Promise { if (filename instanceof URL || /^https?:\/\//i.test(filename)) { @@ -91,7 +107,7 @@ export class NetCDF4 extends Group { // Create dataset from Blob static async fromBlob( blob: Blob, - mode: string = "r", + mode: FileMode = "r", options: DatasetOptions = {}, ): Promise { const arrayBuffer = await blob.arrayBuffer(); @@ -101,7 +117,7 @@ export class NetCDF4 extends Group { // Create dataset from ArrayBuffer static async fromArrayBuffer( buffer: ArrayBuffer, - mode: string = "r", + mode: FileMode = "r", options: DatasetOptions = {}, ): Promise { const data = new Uint8Array(buffer); @@ -111,7 +127,7 @@ export class NetCDF4 extends Group { // Create dataset from memory data (Uint8Array or ArrayBuffer) static async fromMemory( data: Uint8Array | ArrayBuffer, - mode: string = "r", + mode: FileMode = "r", options: DatasetOptions = {}, filename?: string, ): Promise { @@ -158,9 +174,7 @@ export class NetCDF4 extends Group { // After worker is set up, open the file await dataset.open(); } catch (error) { - dataset.terminateWorker( - error instanceof Error ? error : new Error(String(error)), - ); + dataset.terminateWorker(toError(error)); throw error; } @@ -224,9 +238,7 @@ export class NetCDF4 extends Group { await dataset.initialize(); await dataset.open(); } catch (error) { - dataset.terminateWorker( - error instanceof Error ? error : new Error(String(error)), - ); + dataset.terminateWorker(toError(error)); throw error; } @@ -241,55 +253,32 @@ export class NetCDF4 extends Group { } // Check for valid modes early, before any WASM operations - const validModes = ["r", "w", "w-", "a", "r+"]; - if (!validModes.includes(this.mode)) { - throw new Error(`Unsupported mode: ${this.mode}`); - } - - // Worker path - if (this.worker) { - // Wait for worker to be ready first - await this.workerReady; - - const modeValue = - this.mode === "r" - ? NC_CONSTANTS.NC_NOWRITE - : NC_CONSTANTS.NC_WRITE; - this.ncid = await this.run("open", { - path: this.filename, - modeValue, - }); - - (this as any).groupId = this.ncid; - this._isOpen = true; - - return; + const mode = this.mode; + if (!isFileMode(mode)) { + throw new Error(`Unsupported mode: ${mode}`); } - if (this.mode === "w" || this.mode === "w-") { + if (!this.worker && (mode === "w" || mode === "w-")) { // Create new file - let createMode = NC_CONSTANTS.NC_CLOBBER; + let createMode: number = NC_CONSTANTS.NC_CLOBBER; if (this.options.format === "NETCDF4") { createMode |= NC_CONSTANTS.NC_NETCDF4; } - const result = await this.createFile(this.filename, createMode); - this.ncid = result; - (this as any).groupId = result; - } else if ( - this.mode === "r" || - this.mode === "a" || - this.mode === "r+" - ) { - // Open existing file - const modeValue = - this.mode === "r" - ? NC_CONSTANTS.NC_NOWRITE - : NC_CONSTANTS.NC_WRITE; - this.ncid = await this.openFile(this.filename, this.mode as any); - (this as any).groupId = this.ncid; - await this.load(); + this.ncid = await this.createFile(this.filename, createMode); + this.groupId = this.ncid; + } else { + // Worker datasets open the file inside the worker, where write + // modes open the existing file for writing like "a" + await this.workerReady; + this.ncid = await this.openFile( + this.filename, + mode === "w" || mode === "w-" ? "a" : mode, + ); + this.groupId = this.ncid; + if (!this.worker) { + await this.load(); + } } - this._isOpen = true; } @@ -360,10 +349,8 @@ export class NetCDF4 extends Group { } // Low-level NetCDF operations (used by Group methods) - async openFile(path: string, mode: "r" | "w" | "a" = "r"): Promise { - const modeValue = - mode === "r" ? NC_CONSTANTS.NC_NOWRITE : NC_CONSTANTS.NC_WRITE; - return this.run("open", { path, modeValue }); + async openFile(path: string, mode: OpenMode = "r"): Promise { + return this.run("open", { path, modeValue: FILE_MODES[mode].flags }); } async createFile( @@ -395,7 +382,10 @@ export class NetCDF4 extends Group { const fullArgs = { ncid: this.ncid, ...args } as OperationArgs; if (this.workerError) throw this.workerError; if (this.worker) { - return this.requestWorker({ type: name, args: fullArgs }); + return this.requestWorker>({ + type: name, + args: fullArgs, + }); } return runOperation(this.getModule(), name, fullArgs); } @@ -403,14 +393,14 @@ export class NetCDF4 extends Group { // Post a message to the worker and wait for the reply carrying the same id. // With startup set, a worker 'error' event also rejects, since a worker that // fails to load never replies. - private requestWorker( - message: { type: string; [key: string]: any }, + private requestWorker( + message: WorkerRequest, { startup = false } = {}, - ): Promise { + ): Promise { const worker = this.worker!; const id = ++this.requestId; - return new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { // Aborting it removes every listener this request added const listeners = new AbortController(); @@ -419,7 +409,8 @@ export class NetCDF4 extends Group { listeners.abort(); this.pendingRequests.delete(id); if (error) reject(error); - else resolve(result); + // The worker's reply can't be checked; it is trusted to match T + else resolve(result as T); }; worker.addEventListener( @@ -531,19 +522,7 @@ export class NetCDF4 extends Group { async getVariableArray( variable: number | string, groupPath?: string, - ): Promise< - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array - | string[] - > { + ): Promise { return this.run("getVariableArray", { variable, groupPath }); } @@ -552,19 +531,7 @@ export class NetCDF4 extends Group { start: number[], count: number[], groupPath?: string, - ): Promise< - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array - | string[] - > { + ): Promise { return this.run("getSlicedVariableArray", { variable, start, @@ -601,19 +568,7 @@ export class NetCDF4 extends Group { selection: DimSelection[], groupPath?: string, options?: { convertEnumsToNames?: boolean }, - ): Promise< - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | Float32Array - | Float64Array - | BigInt64Array - | BigUint64Array - | string[] - > { + ): Promise { return this.run("getVariableArrayWithSelection", { variable, selection, @@ -745,7 +700,7 @@ export class NetCDF4 extends Group { // Mount memory data in the WASM virtual file system private async mountMemoryData(): Promise { - if (!this.memorySource || !this.module) { + if (!this.memorySource?.filename || !this.module) { return; } @@ -758,14 +713,15 @@ export class NetCDF4 extends Group { // Ensure the /tmp directory exists try { module.FS.mkdir("/tmp"); - } catch (e) { + } catch { // Directory might already exist, ignore error } // Write the memory data to a virtual file + const { data, filename } = this.memorySource; module.FS.writeFile( - this.memorySource.filename, - this.memorySource.data, + filename, + data instanceof ArrayBuffer ? new Uint8Array(data) : data, ); } catch (error) { throw new Error(`Failed to mount memory data: ${error}`); @@ -789,7 +745,7 @@ export class NetCDF4 extends Group { return data.buffer.slice( data.byteOffset, data.byteOffset + data.byteLength, - ); + ) as ArrayBuffer; } catch (error) { throw new Error(`Failed to read data as ArrayBuffer: ${error}`); } diff --git a/src/operations.ts b/src/operations.ts index b00181b..62e9dc5 100644 --- a/src/operations.ts +++ b/src/operations.ts @@ -5,7 +5,7 @@ import { NC_CONSTANTS } from "./constants.js"; import * as NCGet from "./netcdf-getters.js"; import type { DimSelection } from "./slice.js"; -import type { NetCDF4Module } from "./types.js"; +import type { NetCDF4Module, OpenFlags } from "./types.js"; // Arguments of an operation: the ncid it runs on, plus its own type Args = { ncid: number } & T; @@ -15,7 +15,7 @@ type VariableArgs = Args<{ variable: number | string; groupPath?: string }>; export const operations = { open: ( module: NetCDF4Module, - { path, modeValue }: Args<{ path: string; modeValue: number }>, + { path, modeValue }: Args<{ path: string; modeValue: OpenFlags }>, ) => { const result = module.nc_open(path, modeValue); if (result.result !== NC_CONSTANTS.NC_NOERR) { diff --git a/src/remote-read.ts b/src/remote-read.ts index ba84c6d..5e80ba7 100644 --- a/src/remote-read.ts +++ b/src/remote-read.ts @@ -3,7 +3,12 @@ // be answered synchronously. Synchronous XHR is only allowed in Web Workers, // which is why remote files are only supported on the worker path. -import type { RemoteFileOptions } from "./types.js"; +import { toError } from "./errors.js"; +import type { + EmscriptenFileNode, + EmscriptenFS, + RemoteFileOptions, +} from "./types.js"; const DEFAULT_BLOCK_SIZE = 1024 * 1024; // 1 MiB const DEFAULT_CACHE_SIZE = 64 * 1024 * 1024; // 64 MiB @@ -54,9 +59,9 @@ export async function checkRangeSupport( headers: { ...options.headers, Range: "bytes=0-0" }, credentials: options.withCredentials ? "include" : "same-origin", }); - } catch (err: any) { + } catch (err) { throw new Error( - `Request to ${url} failed (network error or blocked by CORS): ${err?.message ?? err}`, + `Request to ${url} failed (network error or blocked by CORS): ${toError(err).message}`, ); } await response.body?.cancel(); @@ -165,9 +170,9 @@ export class XhrRangeSource implements RangeSource { try { xhr.send(null); - } catch (err: any) { + } catch (err) { throw new Error( - `Request to ${this.url} failed (network error or blocked by CORS): ${err?.message ?? err}`, + `Request to ${this.url} failed (network error or blocked by CORS): ${toError(err).message}`, ); } if (xhr.status !== 200 && xhr.status !== 206) { @@ -279,10 +284,10 @@ export class RemoteFile { * kept in file.lastError. */ export function createRemoteFileNode( - FS: any, + FS: EmscriptenFS, path: string, file: RemoteFile, -): any { +): EmscriptenFileNode { const slash = path.lastIndexOf("/"); const dir = path.slice(0, slash) || "/"; FS.mkdirTree(dir); @@ -293,8 +298,8 @@ export function createRemoteFileNode( node.stream_ops = { ...node.stream_ops, read( - _stream: any, - buffer: Int8Array, + _stream: FS.FSStream, + buffer: ArrayBufferView, offset: number, length: number, position: number, @@ -307,9 +312,8 @@ export function createRemoteFileNode( ); try { return file.read(target, position); - } catch (err: any) { - file.lastError = - err instanceof Error ? err : new Error(String(err)); + } catch (err) { + file.lastError = toError(err); throw new FS.ErrnoError(EIO); } }, diff --git a/src/types.ts b/src/types.ts index 5d52a62..87544e8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,45 +1,74 @@ // Type definitions for NetCDF4 WASM -export interface EmscriptenModule { - ccall: ( - name: string, - returnType: string, - argTypes: string[], - args: any[], - ) => any; - cwrap: ( +/// + +import type { FILE_MODES } from "./constants.js"; + +// A MEMFS file node. stream_ops.read is passed HEAP8, not the Uint8Array +// that @types/emscripten declares. +export type EmscriptenFileNode = FS.FSNode & { + usedBytes: number; + stream_ops: Omit & { + read( + stream: FS.FSStream, + buffer: Int8Array, + offset: number, + length: number, + position: number, + ): number; + }; +}; + +// FS.createFile exists at runtime but is missing from @types/emscripten +export type EmscriptenFS = typeof FS & { + createFile( + parent: string | FS.FSNode, name: string, - returnType: string, - argTypes: string[], - ) => (...args: any[]) => any; - getValue: (ptr: number, type: string) => number; - setValue: (ptr: number, value: number, type: string) => void; - UTF8ToString: (ptr: number) => string; - stringToUTF8: ( - str: string, - outPtr: number, - maxBytesToWrite: number, - ) => void; - lengthBytesUTF8: (str: string) => number; - _malloc: (size: number) => number; - _free: (ptr: number) => void; + properties: object, + canRead: boolean, + canWrite: boolean, + ): EmscriptenFileNode; +}; + +// The base interface (heaps, _malloc, _free, ...) comes from @types/emscripten. +// Runtime methods are only present when listed in EXPORTED_RUNTIME_METHODS +// (see scripts/build-wasm.sh), so they have to be added here. +export interface EmscriptenModule extends globalThis.EmscriptenModule { + ccall: typeof ccall; + cwrap: typeof cwrap; + getValue: typeof getValue; + setValue: typeof setValue; + UTF8ToString: typeof UTF8ToString; + stringToUTF8: typeof stringToUTF8; + lengthBytesUTF8: typeof lengthBytesUTF8; + FS: EmscriptenFS; + WORKERFS: Emscripten.FileSystemType; + // Defined in bindings/post.js allocateString: (str: string) => number; freeString: (ptr: number) => void; - FS: any; - WORKERFS: any; ready: Promise; - HEAPF64: Float64Array; - HEAP64: BigInt64Array; - HEAP32: Int32Array; - HEAP8: Int8Array; - HEAPF32: Float32Array; - HEAPU8: Uint8Array; - HEAP16: Int16Array; - HEAPU16: Uint16Array; - HEAPU32: Uint32Array; - HEAPU64: BigUint64Array; } +export type AnyTypedArray = + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array + | string[]; + +export type FileMode = keyof typeof FILE_MODES; +export type CreateMode = { + [M in FileMode]: (typeof FILE_MODES)[M]["create"] extends true ? M : never; +}[FileMode]; +export type OpenMode = Exclude; +// The flags nc_open accepts +export type OpenFlags = (typeof FILE_MODES)[OpenMode]["flags"]; export interface NetCDF4Module extends EmscriptenModule { // Wrapped NetCDF4 functions nc_open: (path: string, mode: number) => { result: number; ncid: number }; diff --git a/src/wasm-module.ts b/src/wasm-module.ts index 8645f95..0aa8625 100644 --- a/src/wasm-module.ts +++ b/src/wasm-module.ts @@ -973,7 +973,7 @@ export class WasmModuleLoader { const result = nc_inq_attlen_wrapper(ncid, varid, name, lenPtr); const len = result === NC_CONSTANTS.NC_NOERR - ? module.getValue(lenPtr, "i64") + ? Number(module.getValue(lenPtr, "i64")) : undefined; module._free(lenPtr); return { result, len }; @@ -1924,7 +1924,7 @@ export class WasmModuleLoader { const result = nc_inq_grpname_len_wrapper(ncid, lenpPtr); const lenp = result === NC_CONSTANTS.NC_NOERR - ? module.getValue(lenpPtr, "i64") + ? Number(module.getValue(lenpPtr, "i64")) : undefined; module._free(lenpPtr); diff --git a/tests/unit/errors.test.ts b/tests/unit/errors.test.ts new file mode 100644 index 0000000..6cf0471 --- /dev/null +++ b/tests/unit/errors.test.ts @@ -0,0 +1,21 @@ +// Normalising caught values to Error + +import { describe, expect, test } from "vitest"; +import { toError } from "../../src/errors.js"; + +describe("toError", () => { + test("returns Error instances unchanged", () => { + const err = new TypeError("boom"); + expect(toError(err)).toBe(err); + }); + + test("keeps the message of error-like objects", () => { + expect(toError({ message: "boom" }).message).toBe("boom"); + }); + + test("stringifies anything else", () => { + expect(toError("boom").message).toBe("boom"); + expect(toError(29).message).toBe("29"); + expect(toError(undefined).message).toBe("undefined"); + }); +}); diff --git a/tests/unit/remote-read.test.ts b/tests/unit/remote-read.test.ts index 9e21032..0943259 100644 --- a/tests/unit/remote-read.test.ts +++ b/tests/unit/remote-read.test.ts @@ -16,6 +16,7 @@ import { RemoteFile, XhrRangeSource, } from "../../src/remote-read.js"; +import type { EmscriptenFS } from "../../src/types.js"; const GiB = 1024 ** 3; const URL_ = "https://example.org/data.nc"; @@ -369,12 +370,17 @@ describe("createRemoteFileNode", () => { }, }; - const node = createRemoteFileNode(FS, "/remote/data.nc", file); + const node = createRemoteFileNode( + FS as unknown as EmscriptenFS, + "/remote/data.nc", + file, + ); + const stream = {} as FS.FSStream; expect(FS.mkdirTree).toHaveBeenCalledWith("/remote"); expect(node.usedBytes).toBe(length); const heap = new Int8Array(10); - expect(node.stream_ops.read({}, heap, 2, 3, length - 3)).toBe(3); + expect(node.stream_ops.read(stream, heap, 2, 3, length - 3)).toBe(3); expect(new Uint8Array(heap.buffer, 2, 3)).toEqual( bytesAt(length - 3, length), ); @@ -382,7 +388,7 @@ describe("createRemoteFileNode", () => { bytes.read.mockImplementationOnce(() => { throw new Error("HTTP 403"); }); - expect(() => node.stream_ops.read({}, heap, 0, 1, 0)).toThrow("29"); + expect(() => node.stream_ops.read(stream, heap, 0, 1, 0)).toThrow("29"); expect(file.lastError?.message).toBe("HTTP 403"); }); });